prompt
large_stringlengths
70
991k
completion
large_stringlengths
0
1.02k
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>/* 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 https://mozilla.org/MPL/2.0/. */ //! Calculate [specified][specified] and [computed values][computed] from a //! tree of DOM nodes and a set of stylesheets. //! //! [computed]: https://drafts.csswg.org/css-cascade/#computed //! [specified]: https://drafts.csswg.org/css-cascade/#specified //! //! In particular, this crate contains the definitions of supported properties, //! the code to parse them into specified values and calculate the computed //! values based on the specified values, as well as the code to serialize both //! specified and computed values. //! //! The main entry point is [`recalc_style_at`][recalc_style_at]. //! //! [recalc_style_at]: traversal/fn.recalc_style_at.html //! //! Major dependencies are the [cssparser][cssparser] and [selectors][selectors] //! crates. //! //! [cssparser]: ../cssparser/index.html //! [selectors]: ../selectors/index.html #![deny(missing_docs)] extern crate app_units; extern crate arrayvec; extern crate atomic_refcell; #[macro_use] extern crate bitflags; #[allow(unused_extern_crates)] extern crate byteorder; #[cfg(feature = "servo")] extern crate crossbeam_channel; #[macro_use] extern crate cssparser; #[macro_use] extern crate debug_unreachable; #[macro_use] extern crate derive_more; extern crate euclid; extern crate fallible; extern crate fxhash; #[cfg(feature = "gecko")] #[macro_use] pub mod gecko_string_cache; extern crate hashglobe; #[cfg(feature = "servo")] #[macro_use] extern crate html5ever; extern crate indexmap; extern crate itertools; extern crate itoa; #[macro_use] extern crate lazy_static;<|fim▁hole|>#[macro_use] extern crate malloc_size_of; #[macro_use] extern crate malloc_size_of_derive; #[allow(unused_extern_crates)] #[macro_use] extern crate matches; #[cfg(feature = "gecko")] pub extern crate nsstring; #[cfg(feature = "gecko")] extern crate num_cpus; #[macro_use] extern crate num_derive; extern crate num_integer; extern crate num_traits; extern crate ordered_float; extern crate owning_ref; extern crate parking_lot; extern crate precomputed_hash; extern crate rayon; extern crate selectors; #[macro_use] extern crate serde; pub extern crate servo_arc; #[cfg(feature = "servo")] #[macro_use] extern crate servo_atoms; #[cfg(feature = "servo")] extern crate servo_config; #[cfg(feature = "servo")] extern crate servo_url; extern crate smallbitvec; extern crate smallvec; #[cfg(feature = "gecko")] extern crate static_prefs; #[cfg(feature = "servo")] extern crate string_cache; #[macro_use] extern crate style_derive; extern crate style_traits; #[cfg(feature = "gecko")] extern crate thin_slice; extern crate time; extern crate to_shmem; #[macro_use] extern crate to_shmem_derive; extern crate uluru; extern crate unicode_bidi; #[allow(unused_extern_crates)] extern crate unicode_segmentation; extern crate void; #[macro_use] mod macros; pub mod animation; pub mod applicable_declarations; #[allow(missing_docs)] // TODO. #[cfg(feature = "servo")] pub mod attr; pub mod author_styles; pub mod bezier; pub mod bloom; pub mod context; pub mod counter_style; pub mod custom_properties; pub mod data; pub mod dom; pub mod dom_apis; pub mod driver; pub mod element_state; #[cfg(feature = "servo")] mod encoding_support; pub mod error_reporting; pub mod font_face; pub mod font_metrics; #[cfg(feature = "gecko")] #[allow(unsafe_code)] pub mod gecko_bindings; pub mod global_style_data; pub mod hash; pub mod invalidation; #[allow(missing_docs)] // TODO. pub mod logical_geometry; pub mod matching; #[macro_use] pub mod media_queries; pub mod parallel; pub mod parser; pub mod rule_cache; pub mod rule_collector; pub mod rule_tree; pub mod scoped_tls; pub mod selector_map; pub mod selector_parser; pub mod shared_lock; pub mod sharing; pub mod str; pub mod style_adjuster; pub mod style_resolver; pub mod stylesheet_set; pub mod stylesheets; pub mod stylist; pub mod thread_state; pub mod timer; pub mod traversal; pub mod traversal_flags; pub mod use_counters; #[macro_use] #[allow(non_camel_case_types)] pub mod values; #[cfg(feature = "gecko")] pub use crate::gecko_string_cache as string_cache; #[cfg(feature = "gecko")] pub use crate::gecko_string_cache::Atom; #[cfg(feature = "gecko")] pub use crate::gecko_string_cache::Atom as Prefix; #[cfg(feature = "gecko")] pub use crate::gecko_string_cache::Atom as LocalName; #[cfg(feature = "gecko")] pub use crate::gecko_string_cache::Namespace; #[cfg(feature = "servo")] pub use html5ever::LocalName; #[cfg(feature = "servo")] pub use html5ever::Namespace; #[cfg(feature = "servo")] pub use html5ever::Prefix; #[cfg(feature = "servo")] pub use servo_atoms::Atom; pub use style_traits::arc_slice::ArcSlice; pub use style_traits::owned_slice::OwnedSlice; pub use style_traits::owned_str::OwnedStr; /// The CSS properties supported by the style system. /// Generated from the properties.mako.rs template by build.rs #[macro_use] #[allow(unsafe_code)] #[deny(missing_docs)] pub mod properties { include!(concat!(env!("OUT_DIR"), "/properties.rs")); } #[cfg(feature = "gecko")] #[allow(unsafe_code)] pub mod gecko; // uses a macro from properties #[cfg(feature = "servo")] #[allow(unsafe_code)] pub mod servo; #[cfg(feature = "gecko")] #[allow(unsafe_code, missing_docs)] pub mod gecko_properties { include!(concat!(env!("OUT_DIR"), "/gecko_properties.rs")); } macro_rules! reexport_computed_values { ( $( { $name: ident, $boxed: expr } )+ ) => { /// Types for [computed values][computed]. /// /// [computed]: https://drafts.csswg.org/css-cascade/#computed pub mod computed_values { $( pub use crate::properties::longhands::$name::computed_value as $name; )+ // Don't use a side-specific name needlessly: pub use crate::properties::longhands::border_top_style::computed_value as border_style; } } } longhand_properties_idents!(reexport_computed_values); #[cfg(feature = "gecko")] use crate::gecko_string_cache::WeakAtom; #[cfg(feature = "servo")] use servo_atoms::Atom as WeakAtom; /// Extension methods for selectors::attr::CaseSensitivity pub trait CaseSensitivityExt { /// Return whether two atoms compare equal according to this case sensitivity. fn eq_atom(self, a: &WeakAtom, b: &WeakAtom) -> bool; } impl CaseSensitivityExt for selectors::attr::CaseSensitivity { fn eq_atom(self, a: &WeakAtom, b: &WeakAtom) -> bool { match self { selectors::attr::CaseSensitivity::CaseSensitive => a == b, selectors::attr::CaseSensitivity::AsciiCaseInsensitive => a.eq_ignore_ascii_case(b), } } } /// A trait pretty much similar to num_traits::Zero, but without the need of /// implementing `Add`. pub trait Zero { /// Returns the zero value. fn zero() -> Self; /// Returns whether this value is zero. fn is_zero(&self) -> bool; } impl<T> Zero for T where T: num_traits::Zero, { fn zero() -> Self { <Self as num_traits::Zero>::zero() } fn is_zero(&self) -> bool { <Self as num_traits::Zero>::is_zero(self) } }<|fim▁end|>
#[macro_use] extern crate log;
<|file_name|>unary.spec.js<|end_file_name|><|fim▁begin|>const test = require('tape') const helpers = require('../test/helpers') const bindFunc = helpers.bindFunc const unary = require('./unary') test('unary helper', t => { const f = bindFunc(unary) const err = /unary: Argument must be a Function/ t.throws(f(undefined), err, 'throws with undefined') t.throws(f(null), err, 'throws with null') t.throws(f(0), err, 'throws with falsey number') t.throws(f(1), err, 'throws with truthy number') t.throws(f(''), err, 'throws with falsey string') t.throws(f('string'), err, 'throws with truthy string') t.throws(f(false), err, 'throws with false') t.throws(f(true), err, 'throws with true') t.throws(f({}), err, 'throws with object')<|fim▁hole|> t.same(fn(1, 2, 3), { x: 1, y: undefined, z: undefined }, 'only applies first argument to function') t.end() })<|fim▁end|>
t.throws(f([]), err, 'throws with array') const fn = unary((x, y, z) => ({ x: x, y: y, z: z }))
<|file_name|>TelaPrincipal.cpp<|end_file_name|><|fim▁begin|>#include "TelaPrincipal.h" TelaPrincipal::TelaPrincipal() {<|fim▁hole|><|fim▁end|>
}
<|file_name|>impl_aep_asyncio.py<|end_file_name|><|fim▁begin|>from osrf_pycommon.process_utils import asyncio from osrf_pycommon.process_utils.async_execute_process import async_execute_process from osrf_pycommon.process_utils import get_loop from .impl_aep_protocol import create_protocol loop = get_loop() <|fim▁hole|>@asyncio.coroutine def run(cmd, **kwargs): transport, protocol = yield from async_execute_process( create_protocol(), cmd, **kwargs) retcode = yield from protocol.complete return protocol.stdout_buffer, protocol.stderr_buffer, retcode<|fim▁end|>
<|file_name|>Main.js<|end_file_name|><|fim▁begin|>/************************************************************* * * MathJax/jax/output/HTML-CSS/fonts/Asana-Math/Size1/Regular/Main.js * * Copyright (c) 2013-2014 The MathJax Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ MathJax.OutputJax['HTML-CSS'].FONTDATA.FONTS['AsanaMathJax_Size1'] = { directory: 'Size1/Regular', family: 'AsanaMathJax_Size1', testString: '\u0302\u0303\u0305\u0306\u030C\u0332\u0333\u033F\u2016\u2044\u2045\u2046\u20D6\u20D7\u220F', 0x20: [0,0,249,0,0], 0x28: [981,490,399,84,360], 0x29: [981,490,399,40,316], 0x5B: [984,492,350,84,321], 0x5D: [984,492,350,84,321], 0x7B: [981,490,362,84,328], 0x7C: [908,367,241,86,156], 0x7D: [981,490,362,84,328],<|fim▁hole|> 0x303: [763,-654,700,0,701], 0x305: [587,-542,510,0,511], 0x306: [664,-506,383,0,384], 0x30C: [783,-627,736,0,737], 0x332: [-130,175,510,0,511], 0x333: [-130,283,510,0,511], 0x33F: [695,-542,510,0,511], 0x2016: [908,367,436,86,351], 0x2044: [742,463,382,-69,383], 0x2045: [943,401,353,64,303], 0x2046: [943,401,358,30,269], 0x20D6: [790,-519,807,0,807], 0x20D7: [790,-519,807,0,807], 0x220F: [901,448,1431,78,1355], 0x2210: [901,448,1431,78,1355], 0x2211: [893,446,1224,89,1135], 0x221A: [1280,0,770,63,803], 0x2229: [1039,520,1292,124,1169], 0x222B: [1310,654,1000,54,1001], 0x222C: [1310,654,1659,54,1540], 0x222D: [1310,654,2198,54,2079], 0x222E: [1310,654,1120,54,1001], 0x222F: [1310,654,1659,54,1540], 0x2230: [1310,654,2198,54,2079], 0x2231: [1310,654,1120,54,1001], 0x2232: [1310,654,1146,80,1027], 0x2233: [1310,654,1120,54,1001], 0x22C0: [1040,519,1217,85,1132], 0x22C1: [1040,519,1217,85,1132], 0x22C2: [1039,520,1292,124,1169], 0x22C3: [1039,520,1292,124,1169], 0x2308: [980,490,390,84,346], 0x2309: [980,490,390,84,346], 0x230A: [980,490,390,84,346], 0x230B: [980,490,390,84,346], 0x23B4: [755,-518,977,0,978], 0x23B5: [-238,475,977,0,978], 0x23DC: [821,-545,972,0,973], 0x23DD: [-545,821,972,0,973], 0x23DE: [789,-545,1572,51,1522], 0x23DF: [-545,789,1572,51,1522], 0x23E0: [755,-545,1359,0,1360], 0x23E1: [-545,755,1359,0,1360], 0x27C5: [781,240,450,53,397], 0x27C6: [781,240,450,53,397], 0x27E6: [684,341,502,84,473], 0x27E7: [684,341,502,84,473], 0x27E8: [681,340,422,53,371], 0x27E9: [681,340,422,53,371], 0x27EA: [681,340,605,53,554], 0x27EB: [681,340,605,53,554], 0x29FC: [915,457,518,50,469], 0x29FD: [915,457,518,49,469], 0x2A00: [1100,550,1901,124,1778], 0x2A01: [1100,550,1901,124,1778], 0x2A02: [1100,550,1901,124,1778], 0x2A03: [1039,520,1292,124,1169], 0x2A04: [1039,520,1292,124,1169], 0x2A05: [1024,513,1292,124,1169], 0x2A06: [1024,513,1292,124,1169], 0x2A07: [1039,520,1415,86,1330], 0x2A08: [1039,520,1415,86,1330], 0x2A09: [888,445,1581,124,1459], 0x2A0C: [1310,654,2736,54,2617], 0x2A0D: [1310,654,1120,54,1001], 0x2A0E: [1310,654,1120,54,1001], 0x2A0F: [1310,654,1120,54,1001], 0x2A10: [1310,654,1120,54,1001], 0x2A11: [1310,654,1182,54,1063], 0x2A12: [1310,654,1120,54,1001], 0x2A13: [1310,654,1120,54,1001], 0x2A14: [1310,654,1120,54,1001], 0x2A15: [1310,654,1120,54,1001], 0x2A16: [1310,654,1120,54,1001], 0x2A17: [1310,654,1431,54,1362], 0x2A18: [1310,654,1120,54,1001], 0x2A19: [1310,654,1120,54,1001], 0x2A1A: [1310,654,1120,54,1001], 0x2A1B: [1471,654,1130,54,1011], 0x2A1C: [1471,654,1156,80,1037] }; MathJax.Callback.Queue( ["initFont",MathJax.OutputJax["HTML-CSS"],"AsanaMathJax_Size1"], ["loadComplete",MathJax.Ajax,MathJax.OutputJax["HTML-CSS"].fontDir+"/Size1/Regular/Main.js"] );<|fim▁end|>
0x302: [783,-627,453,0,453],
<|file_name|>urls.py<|end_file_name|><|fim▁begin|># Copyright The IETF Trust 2008, All Rights Reserved from django.conf.urls.defaults import patterns, include from ietf.wginfo import views, edit, milestones from django.views.generic.simple import redirect_to urlpatterns = patterns('',<|fim▁hole|> (r'^summary-by-acronym.txt', redirect_to, { 'url':'/wg/1wg-summary-by-acronym.txt' }), (r'^1wg-summary.txt', views.wg_summary_area), (r'^1wg-summary-by-acronym.txt', views.wg_summary_acronym), (r'^1wg-charters.txt', views.wg_charters), (r'^1wg-charters-by-acronym.txt', views.wg_charters_by_acronym), (r'^chartering/$', views.chartering_wgs), (r'^bofs/$', views.bofs), (r'^chartering/create/$', edit.edit, {'action': "charter"}, "wg_create"), (r'^bofs/create/$', edit.edit, {'action': "create"}, "bof_create"), (r'^(?P<acronym>[a-zA-Z0-9-]+)/documents/txt/$', views.wg_documents_txt), (r'^(?P<acronym>[a-zA-Z0-9-]+)/$', views.wg_documents_html, None, "wg_docs"), (r'^(?P<acronym>[a-zA-Z0-9-]+)/charter/$', views.wg_charter, None, 'wg_charter'), (r'^(?P<acronym>[a-zA-Z0-9-]+)/init-charter/', edit.submit_initial_charter, None, "wg_init_charter"), (r'^(?P<acronym>[a-zA-Z0-9-]+)/history/$', views.history), (r'^(?P<acronym>[a-zA-Z0-9-]+)/edit/$', edit.edit, {'action': "edit"}, "wg_edit"), (r'^(?P<acronym>[a-zA-Z0-9-]+)/conclude/$', edit.conclude, None, "wg_conclude"), (r'^(?P<acronym>[a-zA-Z0-9-]+)/milestones/$', milestones.edit_milestones, {'milestone_set': "current"}, "wg_edit_milestones"), (r'^(?P<acronym>[a-zA-Z0-9-]+)/milestones/charter/$', milestones.edit_milestones, {'milestone_set': "charter"}, "wg_edit_charter_milestones"), (r'^(?P<acronym>[a-zA-Z0-9-]+)/milestones/charter/reset/$', milestones.reset_charter_milestones, None, "wg_reset_charter_milestones"), (r'^(?P<acronym>[a-zA-Z0-9-]+)/ajax/searchdocs/$', milestones.ajax_search_docs, None, "wg_ajax_search_docs"), (r'^(?P<acronym>[^/]+)/management/', include('ietf.wgchairs.urls')), )<|fim▁end|>
(r'^$', views.wg_dir), (r'^summary.txt', redirect_to, { 'url':'/wg/1wg-summary.txt' }), (r'^summary-by-area.txt', redirect_to, { 'url':'/wg/1wg-summary.txt' }),
<|file_name|>uses-optimized-images.js<|end_file_name|><|fim▁begin|>/** * @license Copyright 2017 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* * @fileoverview This audit determines if the images used are sufficiently larger * than JPEG compressed images without metadata at quality 85. */ 'use strict'; const ByteEfficiencyAudit = require('./byte-efficiency-audit'); const URL = require('../../lib/url-shim'); const IGNORE_THRESHOLD_IN_BYTES = 4096; class UsesOptimizedImages extends ByteEfficiencyAudit { /** * @return {!AuditMeta} */ static get meta() { return { name: 'uses-optimized-images', description: 'Optimize images', informative: true, helpText: 'Optimized images load faster and consume less cellular data. ' + '[Learn more](https://developers.google.com/web/tools/lighthouse/audits/optimize-images).', requiredArtifacts: ['OptimizedImages', 'devtoolsLogs'], }; } /** * @param {{originalSize: number, webpSize: number, jpegSize: number}} image * @param {string} type * @return {{bytes: number, percent: number}} */ static computeSavings(image, type) { const bytes = image.originalSize - image[type + 'Size']; const percent = 100 * bytes / image.originalSize; return {bytes, percent}; } /** * @param {!Artifacts} artifacts * @return {!Audit.HeadingsResult} */ static audit_(artifacts) { const images = artifacts.OptimizedImages; const failedImages = []; const results = []; images.forEach(image => { if (image.failed) { failedImages.push(image); return; } else if (/(jpeg|bmp)/.test(image.mimeType) === false || image.originalSize < image.jpegSize + IGNORE_THRESHOLD_IN_BYTES) { return;<|fim▁hole|> } const url = URL.elideDataURI(image.url); const jpegSavings = UsesOptimizedImages.computeSavings(image, 'jpeg'); results.push({ url, fromProtocol: image.fromProtocol, isCrossOrigin: !image.isSameOrigin, preview: {url: image.url, mimeType: image.mimeType, type: 'thumbnail'}, totalBytes: image.originalSize, wastedBytes: jpegSavings.bytes, }); }); let debugString; if (failedImages.length) { const urls = failedImages.map(image => URL.getURLDisplayName(image.url)); debugString = `Lighthouse was unable to decode some of your images: ${urls.join(', ')}`; } const headings = [ {key: 'preview', itemType: 'thumbnail', text: ''}, {key: 'url', itemType: 'url', text: 'URL'}, {key: 'totalKb', itemType: 'text', text: 'Original'}, {key: 'potentialSavings', itemType: 'text', text: 'Potential Savings'}, ]; return { debugString, results, headings, }; } } module.exports = UsesOptimizedImages;<|fim▁end|>
<|file_name|>angular-locale_zgh-ma.js<|end_file_name|><|fim▁begin|>'use strict'; angular.module("ngLocale", [], ["$provide", function ($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "\u2d5c\u2d49\u2d3c\u2d30\u2d61\u2d5c", "\u2d5c\u2d30\u2d37\u2d33\u2d33\u2d6f\u2d30\u2d5c" ], "DAY": [ "\u2d30\u2d59\u2d30\u2d4e\u2d30\u2d59", "\u2d30\u2d62\u2d4f\u2d30\u2d59", "\u2d30\u2d59\u2d49\u2d4f\u2d30\u2d59", "\u2d30\u2d3d\u2d55\u2d30\u2d59", "\u2d30\u2d3d\u2d61\u2d30\u2d59", "\u2d30\u2d59\u2d49\u2d4e\u2d61\u2d30\u2d59", "\u2d30\u2d59\u2d49\u2d39\u2d62\u2d30\u2d59" ], "ERANAMES": [ "\u2d37\u2d30\u2d5c \u2d4f \u2d44\u2d49\u2d59\u2d30", "\u2d37\u2d3c\u2d3c\u2d49\u2d54 \u2d4f \u2d44\u2d49\u2d59\u2d30" ], "ERAS": [ "\u2d37\u2d30\u2d44", "\u2d37\u2d3c\u2d44" ], "FIRSTDAYOFWEEK": 0, "MONTH": [ "\u2d49\u2d4f\u2d4f\u2d30\u2d62\u2d54", "\u2d31\u2d55\u2d30\u2d62\u2d55", "\u2d4e\u2d30\u2d55\u2d5a", "\u2d49\u2d31\u2d54\u2d49\u2d54", "\u2d4e\u2d30\u2d62\u2d62\u2d53", "\u2d62\u2d53\u2d4f\u2d62\u2d53", "\u2d62\u2d53\u2d4d\u2d62\u2d53\u2d63", "\u2d56\u2d53\u2d5b\u2d5c", "\u2d5b\u2d53\u2d5c\u2d30\u2d4f\u2d31\u2d49\u2d54", "\u2d3d\u2d5c\u2d53\u2d31\u2d54", "\u2d4f\u2d53\u2d61\u2d30\u2d4f\u2d31\u2d49\u2d54", "\u2d37\u2d53\u2d4a\u2d30\u2d4f\u2d31\u2d49\u2d54" ], "SHORTDAY": [ "\u2d30\u2d59\u2d30", "\u2d30\u2d62\u2d4f", "\u2d30\u2d59\u2d49", "\u2d30\u2d3d\u2d55", "\u2d30\u2d3d\u2d61", "\u2d30\u2d59\u2d49\u2d4e", "\u2d30\u2d59\u2d49\u2d39" ], "SHORTMONTH": [ "\u2d49\u2d4f\u2d4f", "\u2d31\u2d55\u2d30", "\u2d4e\u2d30\u2d55",<|fim▁hole|> "\u2d49\u2d31\u2d54", "\u2d4e\u2d30\u2d62", "\u2d62\u2d53\u2d4f", "\u2d62\u2d53\u2d4d", "\u2d56\u2d53\u2d5b", "\u2d5b\u2d53\u2d5c", "\u2d3d\u2d5c\u2d53", "\u2d4f\u2d53\u2d61", "\u2d37\u2d53\u2d4a" ], "STANDALONEMONTH": [ "\u2d49\u2d4f\u2d4f\u2d30\u2d62\u2d54", "\u2d31\u2d55\u2d30\u2d62\u2d55", "\u2d4e\u2d30\u2d55\u2d5a", "\u2d49\u2d31\u2d54\u2d49\u2d54", "\u2d4e\u2d30\u2d62\u2d62\u2d53", "\u2d62\u2d53\u2d4f\u2d62\u2d53", "\u2d62\u2d53\u2d4d\u2d62\u2d53\u2d63", "\u2d56\u2d53\u2d5b\u2d5c", "\u2d5b\u2d53\u2d5c\u2d30\u2d4f\u2d31\u2d49\u2d54", "\u2d3d\u2d5c\u2d53\u2d31\u2d54", "\u2d4f\u2d53\u2d61\u2d30\u2d4f\u2d31\u2d49\u2d54", "\u2d37\u2d53\u2d4a\u2d30\u2d4f\u2d31\u2d49\u2d54" ], "WEEKENDRANGE": [ 5, 6 ], "fullDate": "EEEE d MMMM y", "longDate": "d MMMM y", "medium": "d MMM, y HH:mm:ss", "mediumDate": "d MMM, y", "mediumTime": "HH:mm:ss", "short": "d/M/y HH:mm", "shortDate": "d/M/y", "shortTime": "HH:mm" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "dh", "DECIMAL_SEP": ",", "GROUP_SEP": "\u00a0", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "-", "negSuf": "\u00a4", "posPre": "", "posSuf": "\u00a4" } ] }, "id": "zgh-ma", "localeID": "zgh_MA", "pluralCat": function (n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER; } }); }]);<|fim▁end|>
<|file_name|>simple-tuple.rs<|end_file_name|><|fim▁begin|>// Copyright 2013-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. // min-lldb-version: 310 // ignore-gdb // Test temporarily ignored due to debuginfo tests being disabled, see PR 47155 // compile-flags:-g // === GDB TESTS =================================================================================== // gdbg-command:print/d 'simple_tuple::NO_PADDING_8' // gdbr-command:print simple_tuple::NO_PADDING_8 // gdbg-check:$1 = {__0 = -50, __1 = 50}<|fim▁hole|>// gdbr-command:print simple_tuple::NO_PADDING_16 // gdbg-check:$2 = {__0 = -1, __1 = 2, __2 = 3} // gdbr-check:$2 = (-1, 2, 3) // gdbg-command:print 'simple_tuple::NO_PADDING_32' // gdbr-command:print simple_tuple::NO_PADDING_32 // gdbg-check:$3 = {__0 = 4, __1 = 5, __2 = 6} // gdbr-check:$3 = (4, 5, 6) // gdbg-command:print 'simple_tuple::NO_PADDING_64' // gdbr-command:print simple_tuple::NO_PADDING_64 // gdbg-check:$4 = {__0 = 7, __1 = 8, __2 = 9} // gdbr-check:$4 = (7, 8, 9) // gdbg-command:print 'simple_tuple::INTERNAL_PADDING_1' // gdbr-command:print simple_tuple::INTERNAL_PADDING_1 // gdbg-check:$5 = {__0 = 10, __1 = 11} // gdbr-check:$5 = (10, 11) // gdbg-command:print 'simple_tuple::INTERNAL_PADDING_2' // gdbr-command:print simple_tuple::INTERNAL_PADDING_2 // gdbg-check:$6 = {__0 = 12, __1 = 13, __2 = 14, __3 = 15} // gdbr-check:$6 = (12, 13, 14, 15) // gdbg-command:print 'simple_tuple::PADDING_AT_END' // gdbr-command:print simple_tuple::PADDING_AT_END // gdbg-check:$7 = {__0 = 16, __1 = 17} // gdbr-check:$7 = (16, 17) // gdb-command:run // gdbg-command:print/d noPadding8 // gdbr-command:print noPadding8 // gdbg-check:$8 = {__0 = -100, __1 = 100} // gdbr-check:$8 = (-100, 100) // gdb-command:print noPadding16 // gdbg-check:$9 = {__0 = 0, __1 = 1, __2 = 2} // gdbr-check:$9 = (0, 1, 2) // gdb-command:print noPadding32 // gdbg-check:$10 = {__0 = 3, __1 = 4.5, __2 = 5} // gdbr-check:$10 = (3, 4.5, 5) // gdb-command:print noPadding64 // gdbg-check:$11 = {__0 = 6, __1 = 7.5, __2 = 8} // gdbr-check:$11 = (6, 7.5, 8) // gdb-command:print internalPadding1 // gdbg-check:$12 = {__0 = 9, __1 = 10} // gdbr-check:$12 = (9, 10) // gdb-command:print internalPadding2 // gdbg-check:$13 = {__0 = 11, __1 = 12, __2 = 13, __3 = 14} // gdbr-check:$13 = (11, 12, 13, 14) // gdb-command:print paddingAtEnd // gdbg-check:$14 = {__0 = 15, __1 = 16} // gdbr-check:$14 = (15, 16) // gdbg-command:print/d 'simple_tuple::NO_PADDING_8' // gdbr-command:print simple_tuple::NO_PADDING_8 // gdbg-check:$15 = {__0 = -127, __1 = 127} // gdbr-check:$15 = (-127, 127) // gdbg-command:print 'simple_tuple::NO_PADDING_16' // gdbr-command:print simple_tuple::NO_PADDING_16 // gdbg-check:$16 = {__0 = -10, __1 = 10, __2 = 9} // gdbr-check:$16 = (-10, 10, 9) // gdbg-command:print 'simple_tuple::NO_PADDING_32' // gdbr-command:print simple_tuple::NO_PADDING_32 // gdbg-check:$17 = {__0 = 14, __1 = 15, __2 = 16} // gdbr-check:$17 = (14, 15, 16) // gdbg-command:print 'simple_tuple::NO_PADDING_64' // gdbr-command:print simple_tuple::NO_PADDING_64 // gdbg-check:$18 = {__0 = 17, __1 = 18, __2 = 19} // gdbr-check:$18 = (17, 18, 19) // gdbg-command:print 'simple_tuple::INTERNAL_PADDING_1' // gdbr-command:print simple_tuple::INTERNAL_PADDING_1 // gdbg-check:$19 = {__0 = 110, __1 = 111} // gdbr-check:$19 = (110, 111) // gdbg-command:print 'simple_tuple::INTERNAL_PADDING_2' // gdbr-command:print simple_tuple::INTERNAL_PADDING_2 // gdbg-check:$20 = {__0 = 112, __1 = 113, __2 = 114, __3 = 115} // gdbr-check:$20 = (112, 113, 114, 115) // gdbg-command:print 'simple_tuple::PADDING_AT_END' // gdbr-command:print simple_tuple::PADDING_AT_END // gdbg-check:$21 = {__0 = 116, __1 = 117} // gdbr-check:$21 = (116, 117) // === LLDB TESTS ================================================================================== // lldb-command:run // lldb-command:print/d noPadding8 // lldbg-check:[...]$0 = (-100, 100) // lldbr-check:((i8, u8)) noPadding8 = { = -100 -100 = 100 100 } // lldb-command:print noPadding16 // lldbg-check:[...]$1 = (0, 1, 2) // lldbr-check:((i16, i16, u16)) noPadding16 = { = 0 = 1 = 2 } // lldb-command:print noPadding32 // lldbg-check:[...]$2 = (3, 4.5, 5) // lldbr-check:((i32, f32, u32)) noPadding32 = { = 3 = 4.5 = 5 } // lldb-command:print noPadding64 // lldbg-check:[...]$3 = (6, 7.5, 8) // lldbr-check:((i64, f64, u64)) noPadding64 = { = 6 = 7.5 = 8 } // lldb-command:print internalPadding1 // lldbg-check:[...]$4 = (9, 10) // lldbr-check:((i16, i32)) internalPadding1 = { = 9 = 10 } // lldb-command:print internalPadding2 // lldbg-check:[...]$5 = (11, 12, 13, 14) // lldbr-check:((i16, i32, u32, u64)) internalPadding2 = { = 11 = 12 = 13 = 14 } // lldb-command:print paddingAtEnd // lldbg-check:[...]$6 = (15, 16) // lldbr-check:((i32, i16)) paddingAtEnd = { = 15 = 16 } #![allow(unused_variables)] #![allow(dead_code)] #![feature(omit_gdb_pretty_printer_section)] #![omit_gdb_pretty_printer_section] static mut NO_PADDING_8: (i8, u8) = (-50, 50); static mut NO_PADDING_16: (i16, i16, u16) = (-1, 2, 3); static mut NO_PADDING_32: (i32, f32, u32) = (4, 5.0, 6); static mut NO_PADDING_64: (i64, f64, u64) = (7, 8.0, 9); static mut INTERNAL_PADDING_1: (i16, i32) = (10, 11); static mut INTERNAL_PADDING_2: (i16, i32, u32, u64) = (12, 13, 14, 15); static mut PADDING_AT_END: (i32, i16) = (16, 17); fn main() { let noPadding8: (i8, u8) = (-100, 100); let noPadding16: (i16, i16, u16) = (0, 1, 2); let noPadding32: (i32, f32, u32) = (3, 4.5, 5); let noPadding64: (i64, f64, u64) = (6, 7.5, 8); let internalPadding1: (i16, i32) = (9, 10); let internalPadding2: (i16, i32, u32, u64) = (11, 12, 13, 14); let paddingAtEnd: (i32, i16) = (15, 16); unsafe { NO_PADDING_8 = (-127, 127); NO_PADDING_16 = (-10, 10, 9); NO_PADDING_32 = (14, 15.0, 16); NO_PADDING_64 = (17, 18.0, 19); INTERNAL_PADDING_1 = (110, 111); INTERNAL_PADDING_2 = (112, 113, 114, 115); PADDING_AT_END = (116, 117); } zzz(); // #break } fn zzz() {()}<|fim▁end|>
// gdbr-check:$1 = (-50, 50) // gdbg-command:print 'simple_tuple::NO_PADDING_16'
<|file_name|>integral.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # integeral.py import numpy as num def integral(x,y): """ ROUTINE: INTEGRAL USEAGE: RESULT = INTEGRAL( X, Y ) PURPOSE: Integrate tabulated data using Simpson's rule with 3-point Lagragian interpolation. Data may be regularly sampled in X, or irregularly sampled. INPUT: X Vector of x axis points. (Elements must be unique and monotonically increasing) Y Vector of corresponding Y axis points. KEYWORD_INPUT: None. OUTPUT: Result of integration. EXAMPLE: Example 1: Define 11 x-values on the closed interval [0.0 , 0.8]. X = [ 0.0, .12, .22, .32, .36, .40, .44, .54, .64, .70, .80 ] Define 11 f-values corresponding to x(i). F = [ 0.200000, 1.30973, 1.30524, 1.74339, 2.07490, 2.45600, $ 2.84299, 3.50730, 3.18194, 2.36302, 0.231964 ] Compute the integral. RESULT = INTEGRAL( X, F )<|fim▁hole|> (f = .2 + 25*x - 200*x^2 + 675*x^3 - 900*x^4 + 400*x^5) The Multiple Application Trapezoid Method yields; result = 1.5648 The Multiple Application Simpson's Method yields; result = 1.6036 IDL User Library INT_TABULATED.PRO yields; result = 1.6232 INTEGRAL.PRO yields; result = 1.6274 The Exact Solution (4 decimal accuracy) yields; result = 1.6405 AUTHOR: Liam Gumley, CIMSS/SSEC (liam.gumley@ssec.wisc.edu) Based on a FORTRAN-77 version by Paul van Delst, CIMSS/SSEC 22-DEC-95 REVISIONS: None. """ n = x.size x0 = x[0:n-2] x1 = x[1:n-1] x2 = x[2:n-0] y0 = y[0:n-2] y1 = y[1:n-1] y2 = y[2:n-0] # # compute interpolation delta and midpoint arrays # dx = x1-x0 xmid = 0.5*(x1+x0) # # compute 3 point lagrange interpolation # l0 = ((xmid-x1)/(x0-x1))*((xmid-x2)/(x0-x2)) l1 = ((xmid-x0)/(x1-x0))*((xmid-x2)/(x1-x2)) l2 = ((xmid-x0)/(x2-x0))*((xmid-x1)/(x2-x1)) ymid = y0*l0 + y1*l1 + y2*l2; # # compute integral sum # integ = sum(1.0/6.0*dx*(y0+4.0*ymid+y1)) # # handle last 3 points similarly # x0 = x[n-3] x1 = x[n-2] x2 = x[n-1] y0 = y[n-3] y1 = y[n-2] y2 = y[n-1] dx = x2 - x1 xmid = 0.5*(x2+x1) l0 = ((xmid-x1)/(x0-x1))*((xmid-x2)/(x0-x2)) l1 = ((xmid-x0)/(x1-x0))*((xmid-x2)/(x1-x2)) l2 = ((xmid-x0)/(x2-x0))*((xmid-x1)/(x2-x1)) ymid = y0*l0 + y1*l1 + y2*l2; integ = integ + 1.0/6.0*dx*(y1+4.0*ymid+y2) return integ if __name__ == '__main__': print(integral.__doc__) X = num.array((0.0, .12, .22, .32, .36, .40, .44, .54, .64, .70, .80)) Y = num.array((0.200000, 1.30973, 1.30524, 1.74339, 2.07490, 2.45600, 2.84299, 3.50730, 3.18194, 2.36302, 0.231964)) i = integral(X,Y) print(i)<|fim▁end|>
In this example, the f-values are generated from a known function,
<|file_name|>customsearch-gen.go<|end_file_name|><|fim▁begin|>// Package customsearch provides access to the CustomSearch API. // // See https://developers.google.com/custom-search/v1/using_rest // // Usage example: // // import "google.golang.org/api/customsearch/v1" // ... // customsearchService, err := customsearch.New(oauthHttpClient) package customsearch // import "google.golang.org/api/customsearch/v1" import ( "bytes" "encoding/json" "errors" "fmt" "golang.org/x/net/context" "golang.org/x/net/context/ctxhttp" "google.golang.org/api/googleapi" "google.golang.org/api/internal" "io" "net/http" "net/url" "strconv" "strings" ) // Always reference these packages, just in case the auto-generated code // below doesn't. var _ = bytes.NewBuffer var _ = strconv.Itoa var _ = fmt.Sprintf var _ = json.NewDecoder var _ = io.Copy var _ = url.Parse var _ = googleapi.Version var _ = errors.New var _ = strings.Replace var _ = internal.MarshalJSON const apiId = "customsearch:v1" const apiName = "customsearch" const apiVersion = "v1" const basePath = "https://www.googleapis.com/customsearch/" func New(client *http.Client) (*Service, error) { if client == nil { return nil, errors.New("client is nil") } s := &Service{client: client, BasePath: basePath} s.Cse = NewCseService(s) return s, nil } type Service struct { client *http.Client BasePath string // API endpoint base URL UserAgent string // optional additional User-Agent fragment Cse *CseService } func (s *Service) userAgent() string { if s.UserAgent == "" { return googleapi.UserAgent } return googleapi.UserAgent + " " + s.UserAgent } func NewCseService(s *Service) *CseService { rs := &CseService{s: s} return rs } type CseService struct { s *Service } type Context struct { Facets [][]*ContextFacetsItem `json:"facets,omitempty"` Title string `json:"title,omitempty"` // ForceSendFields is a list of field names (e.g. "Facets") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` } func (s *Context) MarshalJSON() ([]byte, error) { type noMethod Context raw := noMethod(*s) return internal.MarshalJSON(raw, s.ForceSendFields) } type ContextFacetsItem struct { Anchor string `json:"anchor,omitempty"` Label string `json:"label,omitempty"` LabelWithOp string `json:"label_with_op,omitempty"` // ForceSendFields is a list of field names (e.g. "Anchor") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` } func (s *ContextFacetsItem) MarshalJSON() ([]byte, error) { type noMethod ContextFacetsItem raw := noMethod(*s) return internal.MarshalJSON(raw, s.ForceSendFields) } type Promotion struct { BodyLines []*PromotionBodyLines `json:"bodyLines,omitempty"` DisplayLink string `json:"displayLink,omitempty"` HtmlTitle string `json:"htmlTitle,omitempty"` Image *PromotionImage `json:"image,omitempty"` Link string `json:"link,omitempty"` Title string `json:"title,omitempty"` // ForceSendFields is a list of field names (e.g. "BodyLines") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` } func (s *Promotion) MarshalJSON() ([]byte, error) { type noMethod Promotion raw := noMethod(*s) return internal.MarshalJSON(raw, s.ForceSendFields) } type PromotionBodyLines struct { HtmlTitle string `json:"htmlTitle,omitempty"` Link string `json:"link,omitempty"` Title string `json:"title,omitempty"` Url string `json:"url,omitempty"` // ForceSendFields is a list of field names (e.g. "HtmlTitle") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` } func (s *PromotionBodyLines) MarshalJSON() ([]byte, error) { type noMethod PromotionBodyLines raw := noMethod(*s) return internal.MarshalJSON(raw, s.ForceSendFields) } type PromotionImage struct { Height int64 `json:"height,omitempty"` Source string `json:"source,omitempty"` Width int64 `json:"width,omitempty"` // ForceSendFields is a list of field names (e.g. "Height") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` } func (s *PromotionImage) MarshalJSON() ([]byte, error) { type noMethod PromotionImage raw := noMethod(*s) return internal.MarshalJSON(raw, s.ForceSendFields) } type Query struct { Count int64 `json:"count,omitempty"` Cr string `json:"cr,omitempty"` Cref string `json:"cref,omitempty"` Cx string `json:"cx,omitempty"` DateRestrict string `json:"dateRestrict,omitempty"` DisableCnTwTranslation string `json:"disableCnTwTranslation,omitempty"` ExactTerms string `json:"exactTerms,omitempty"` ExcludeTerms string `json:"excludeTerms,omitempty"` FileType string `json:"fileType,omitempty"` Filter string `json:"filter,omitempty"` Gl string `json:"gl,omitempty"` GoogleHost string `json:"googleHost,omitempty"` HighRange string `json:"highRange,omitempty"` Hl string `json:"hl,omitempty"` Hq string `json:"hq,omitempty"` ImgColorType string `json:"imgColorType,omitempty"` ImgDominantColor string `json:"imgDominantColor,omitempty"` ImgSize string `json:"imgSize,omitempty"` ImgType string `json:"imgType,omitempty"` InputEncoding string `json:"inputEncoding,omitempty"` Language string `json:"language,omitempty"` LinkSite string `json:"linkSite,omitempty"` LowRange string `json:"lowRange,omitempty"` OrTerms string `json:"orTerms,omitempty"` OutputEncoding string `json:"outputEncoding,omitempty"` RelatedSite string `json:"relatedSite,omitempty"` Rights string `json:"rights,omitempty"` Safe string `json:"safe,omitempty"` SearchTerms string `json:"searchTerms,omitempty"` SearchType string `json:"searchType,omitempty"` SiteSearch string `json:"siteSearch,omitempty"` SiteSearchFilter string `json:"siteSearchFilter,omitempty"` Sort string `json:"sort,omitempty"` StartIndex int64 `json:"startIndex,omitempty"` StartPage int64 `json:"startPage,omitempty"` Title string `json:"title,omitempty"` TotalResults int64 `json:"totalResults,omitempty,string"` // ForceSendFields is a list of field names (e.g. "Count") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` } func (s *Query) MarshalJSON() ([]byte, error) { type noMethod Query raw := noMethod(*s) return internal.MarshalJSON(raw, s.ForceSendFields) } type Result struct { CacheId string `json:"cacheId,omitempty"` DisplayLink string `json:"displayLink,omitempty"` FileFormat string `json:"fileFormat,omitempty"` FormattedUrl string `json:"formattedUrl,omitempty"` HtmlFormattedUrl string `json:"htmlFormattedUrl,omitempty"` HtmlSnippet string `json:"htmlSnippet,omitempty"` HtmlTitle string `json:"htmlTitle,omitempty"` Image *ResultImage `json:"image,omitempty"` Kind string `json:"kind,omitempty"` Labels []*ResultLabels `json:"labels,omitempty"` Link string `json:"link,omitempty"` Mime string `json:"mime,omitempty"` Pagemap *ResultPagemap `json:"pagemap,omitempty"` Snippet string `json:"snippet,omitempty"` Title string `json:"title,omitempty"` // ForceSendFields is a list of field names (e.g. "CacheId") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` } func (s *Result) MarshalJSON() ([]byte, error) { type noMethod Result raw := noMethod(*s) return internal.MarshalJSON(raw, s.ForceSendFields) } type ResultImage struct { ByteSize int64 `json:"byteSize,omitempty"` ContextLink string `json:"contextLink,omitempty"` Height int64 `json:"height,omitempty"` ThumbnailHeight int64 `json:"thumbnailHeight,omitempty"` ThumbnailLink string `json:"thumbnailLink,omitempty"` ThumbnailWidth int64 `json:"thumbnailWidth,omitempty"` Width int64 `json:"width,omitempty"` // ForceSendFields is a list of field names (e.g. "ByteSize") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` } func (s *ResultImage) MarshalJSON() ([]byte, error) { type noMethod ResultImage raw := noMethod(*s) return internal.MarshalJSON(raw, s.ForceSendFields) } type ResultLabels struct { DisplayName string `json:"displayName,omitempty"` LabelWithOp string `json:"label_with_op,omitempty"` Name string `json:"name,omitempty"` // ForceSendFields is a list of field names (e.g. "DisplayName") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` } func (s *ResultLabels) MarshalJSON() ([]byte, error) { type noMethod ResultLabels raw := noMethod(*s) return internal.MarshalJSON(raw, s.ForceSendFields) } type ResultPagemap struct { } type Search struct { Context *Context `json:"context,omitempty"` Items []*Result `json:"items,omitempty"` Kind string `json:"kind,omitempty"` Promotions []*Promotion `json:"promotions,omitempty"` Queries map[string][]Query `json:"queries,omitempty"` SearchInformation *SearchSearchInformation `json:"searchInformation,omitempty"` Spelling *SearchSpelling `json:"spelling,omitempty"` Url *SearchUrl `json:"url,omitempty"` // ServerResponse contains the HTTP response code and headers from the // server. googleapi.ServerResponse `json:"-"` // ForceSendFields is a list of field names (e.g. "Context") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` } func (s *Search) MarshalJSON() ([]byte, error) { type noMethod Search raw := noMethod(*s) return internal.MarshalJSON(raw, s.ForceSendFields) } type SearchSearchInformation struct { FormattedSearchTime string `json:"formattedSearchTime,omitempty"` FormattedTotalResults string `json:"formattedTotalResults,omitempty"` SearchTime float64 `json:"searchTime,omitempty"` TotalResults int64 `json:"totalResults,omitempty,string"` // ForceSendFields is a list of field names (e.g. "FormattedSearchTime") // to unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` } func (s *SearchSearchInformation) MarshalJSON() ([]byte, error) { type noMethod SearchSearchInformation raw := noMethod(*s) return internal.MarshalJSON(raw, s.ForceSendFields) } type SearchSpelling struct { CorrectedQuery string `json:"correctedQuery,omitempty"` HtmlCorrectedQuery string `json:"htmlCorrectedQuery,omitempty"` // ForceSendFields is a list of field names (e.g. "CorrectedQuery") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` } func (s *SearchSpelling) MarshalJSON() ([]byte, error) { type noMethod SearchSpelling raw := noMethod(*s) return internal.MarshalJSON(raw, s.ForceSendFields) } type SearchUrl struct { Template string `json:"template,omitempty"` Type string `json:"type,omitempty"` // ForceSendFields is a list of field names (e.g. "Template") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` } func (s *SearchUrl) MarshalJSON() ([]byte, error) { type noMethod SearchUrl raw := noMethod(*s) return internal.MarshalJSON(raw, s.ForceSendFields) } // method id "search.cse.list": type CseListCall struct { s *Service q string opt_ map[string]interface{} ctx_ context.Context } // List: Returns metadata about the search performed, metadata about the // custom search engine used for the search, and the search results. func (r *CseService) List(q string) *CseListCall { c := &CseListCall{s: r.s, opt_: make(map[string]interface{})} c.q = q return c } // C2coff sets the optional parameter "c2coff": Turns off the // translation between zh-CN and zh-TW. func (c *CseListCall) C2coff(c2coff string) *CseListCall { c.opt_["c2coff"] = c2coff return c } // Cr sets the optional parameter "cr": Country restrict(s). func (c *CseListCall) Cr(cr string) *CseListCall { c.opt_["cr"] = cr return c } // Cref sets the optional parameter "cref": The URL of a linked custom // search engine func (c *CseListCall) Cref(cref string) *CseListCall { c.opt_["cref"] = cref return c } // Cx sets the optional parameter "cx": The custom search engine ID to // scope this search query func (c *CseListCall) Cx(cx string) *CseListCall { c.opt_["cx"] = cx return c } // DateRestrict sets the optional parameter "dateRestrict": Specifies // all search results are from a time period func (c *CseListCall) DateRestrict(dateRestrict string) *CseListCall { c.opt_["dateRestrict"] = dateRestrict return c } // ExactTerms sets the optional parameter "exactTerms": Identifies a // phrase that all documents in the search results must contain func (c *CseListCall) ExactTerms(exactTerms string) *CseListCall { c.opt_["exactTerms"] = exactTerms return c } // ExcludeTerms sets the optional parameter "excludeTerms": Identifies a // word or phrase that should not appear in any documents in the search // results func (c *CseListCall) ExcludeTerms(excludeTerms string) *CseListCall { c.opt_["excludeTerms"] = excludeTerms return c } // FileType sets the optional parameter "fileType": Returns images of a // specified type. Some of the allowed values are: bmp, gif, png, jpg, // svg, pdf, ... func (c *CseListCall) FileType(fileType string) *CseListCall { c.opt_["fileType"] = fileType return c } // Filter sets the optional parameter "filter": Controls turning on or // off the duplicate content filter. // // Possible values: // "0" - Turns off duplicate content filter. // "1" - Turns on duplicate content filter. func (c *CseListCall) Filter(filter string) *CseListCall { c.opt_["filter"] = filter return c } // Gl sets the optional parameter "gl": Geolocation of end user. func (c *CseListCall) Gl(gl string) *CseListCall { c.opt_["gl"] = gl return c } // Googlehost sets the optional parameter "googlehost": The local Google // domain to use to perform the search. func (c *CseListCall) Googlehost(googlehost string) *CseListCall { c.opt_["googlehost"] = googlehost return c } // HighRange sets the optional parameter "highRange": Creates a range in // form as_nlo value..as_nhi value and attempts to append it to query func (c *CseListCall) HighRange(highRange string) *CseListCall { c.opt_["highRange"] = highRange return c } // Hl sets the optional parameter "hl": Sets the user interface // language. func (c *CseListCall) Hl(hl string) *CseListCall { c.opt_["hl"] = hl return c } // Hq sets the optional parameter "hq": Appends the extra query terms to // the query. func (c *CseListCall) Hq(hq string) *CseListCall { c.opt_["hq"] = hq return c } // ImgColorType sets the optional parameter "imgColorType": Returns // black and white, grayscale, or color images: mono, gray, and color. // // Possible values: // "color" - color // "gray" - gray // "mono" - mono func (c *CseListCall) ImgColorType(imgColorType string) *CseListCall { c.opt_["imgColorType"] = imgColorType return c } // ImgDominantColor sets the optional parameter "imgDominantColor": // Returns images of a specific dominant color: yellow, green, teal, // blue, purple, pink, white, gray, black and brown. //<|fim▁hole|>// "gray" - gray // "green" - green // "pink" - pink // "purple" - purple // "teal" - teal // "white" - white // "yellow" - yellow func (c *CseListCall) ImgDominantColor(imgDominantColor string) *CseListCall { c.opt_["imgDominantColor"] = imgDominantColor return c } // ImgSize sets the optional parameter "imgSize": Returns images of a // specified size, where size can be one of: icon, small, medium, large, // xlarge, xxlarge, and huge. // // Possible values: // "huge" - huge // "icon" - icon // "large" - large // "medium" - medium // "small" - small // "xlarge" - xlarge // "xxlarge" - xxlarge func (c *CseListCall) ImgSize(imgSize string) *CseListCall { c.opt_["imgSize"] = imgSize return c } // ImgType sets the optional parameter "imgType": Returns images of a // type, which can be one of: clipart, face, lineart, news, and photo. // // Possible values: // "clipart" - clipart // "face" - face // "lineart" - lineart // "news" - news // "photo" - photo func (c *CseListCall) ImgType(imgType string) *CseListCall { c.opt_["imgType"] = imgType return c } // LinkSite sets the optional parameter "linkSite": Specifies that all // search results should contain a link to a particular URL func (c *CseListCall) LinkSite(linkSite string) *CseListCall { c.opt_["linkSite"] = linkSite return c } // LowRange sets the optional parameter "lowRange": Creates a range in // form as_nlo value..as_nhi value and attempts to append it to query func (c *CseListCall) LowRange(lowRange string) *CseListCall { c.opt_["lowRange"] = lowRange return c } // Lr sets the optional parameter "lr": The language restriction for the // search results // // Possible values: // "lang_ar" - Arabic // "lang_bg" - Bulgarian // "lang_ca" - Catalan // "lang_cs" - Czech // "lang_da" - Danish // "lang_de" - German // "lang_el" - Greek // "lang_en" - English // "lang_es" - Spanish // "lang_et" - Estonian // "lang_fi" - Finnish // "lang_fr" - French // "lang_hr" - Croatian // "lang_hu" - Hungarian // "lang_id" - Indonesian // "lang_is" - Icelandic // "lang_it" - Italian // "lang_iw" - Hebrew // "lang_ja" - Japanese // "lang_ko" - Korean // "lang_lt" - Lithuanian // "lang_lv" - Latvian // "lang_nl" - Dutch // "lang_no" - Norwegian // "lang_pl" - Polish // "lang_pt" - Portuguese // "lang_ro" - Romanian // "lang_ru" - Russian // "lang_sk" - Slovak // "lang_sl" - Slovenian // "lang_sr" - Serbian // "lang_sv" - Swedish // "lang_tr" - Turkish // "lang_zh-CN" - Chinese (Simplified) // "lang_zh-TW" - Chinese (Traditional) func (c *CseListCall) Lr(lr string) *CseListCall { c.opt_["lr"] = lr return c } // Num sets the optional parameter "num": Number of search results to // return func (c *CseListCall) Num(num int64) *CseListCall { c.opt_["num"] = num return c } // OrTerms sets the optional parameter "orTerms": Provides additional // search terms to check for in a document, where each document in the // search results must contain at least one of the additional search // terms func (c *CseListCall) OrTerms(orTerms string) *CseListCall { c.opt_["orTerms"] = orTerms return c } // RelatedSite sets the optional parameter "relatedSite": Specifies that // all search results should be pages that are related to the specified // URL func (c *CseListCall) RelatedSite(relatedSite string) *CseListCall { c.opt_["relatedSite"] = relatedSite return c } // Rights sets the optional parameter "rights": Filters based on // licensing. Supported values include: cc_publicdomain, cc_attribute, // cc_sharealike, cc_noncommercial, cc_nonderived and combinations of // these. func (c *CseListCall) Rights(rights string) *CseListCall { c.opt_["rights"] = rights return c } // Safe sets the optional parameter "safe": Search safety level // // Possible values: // "high" - Enables highest level of safe search filtering. // "medium" - Enables moderate safe search filtering. // "off" (default) - Disables safe search filtering. func (c *CseListCall) Safe(safe string) *CseListCall { c.opt_["safe"] = safe return c } // SearchType sets the optional parameter "searchType": Specifies the // search type: image. // // Possible values: // "image" - custom image search func (c *CseListCall) SearchType(searchType string) *CseListCall { c.opt_["searchType"] = searchType return c } // SiteSearch sets the optional parameter "siteSearch": Specifies all // search results should be pages from a given site func (c *CseListCall) SiteSearch(siteSearch string) *CseListCall { c.opt_["siteSearch"] = siteSearch return c } // SiteSearchFilter sets the optional parameter "siteSearchFilter": // Controls whether to include or exclude results from the site named in // the as_sitesearch parameter // // Possible values: // "e" - exclude // "i" - include func (c *CseListCall) SiteSearchFilter(siteSearchFilter string) *CseListCall { c.opt_["siteSearchFilter"] = siteSearchFilter return c } // Sort sets the optional parameter "sort": The sort expression to apply // to the results func (c *CseListCall) Sort(sort string) *CseListCall { c.opt_["sort"] = sort return c } // Start sets the optional parameter "start": The index of the first // result to return func (c *CseListCall) Start(start int64) *CseListCall { c.opt_["start"] = start return c } // Fields allows partial responses to be retrieved. // See https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *CseListCall) Fields(s ...googleapi.Field) *CseListCall { c.opt_["fields"] = googleapi.CombineFields(s) return c } // IfNoneMatch sets the optional parameter which makes the operation // fail if the object's ETag matches the given value. This is useful for // getting updates only after the object has changed since the last // request. Use googleapi.IsNotModified to check whether the response // error from Do is the result of In-None-Match. func (c *CseListCall) IfNoneMatch(entityTag string) *CseListCall { c.opt_["ifNoneMatch"] = entityTag return c } // Context sets the context to be used in this call's Do method. // Any pending HTTP request will be aborted if the provided context // is canceled. func (c *CseListCall) Context(ctx context.Context) *CseListCall { c.ctx_ = ctx return c } func (c *CseListCall) doRequest(alt string) (*http.Response, error) { var body io.Reader = nil params := make(url.Values) params.Set("alt", alt) params.Set("q", fmt.Sprintf("%v", c.q)) if v, ok := c.opt_["c2coff"]; ok { params.Set("c2coff", fmt.Sprintf("%v", v)) } if v, ok := c.opt_["cr"]; ok { params.Set("cr", fmt.Sprintf("%v", v)) } if v, ok := c.opt_["cref"]; ok { params.Set("cref", fmt.Sprintf("%v", v)) } if v, ok := c.opt_["cx"]; ok { params.Set("cx", fmt.Sprintf("%v", v)) } if v, ok := c.opt_["dateRestrict"]; ok { params.Set("dateRestrict", fmt.Sprintf("%v", v)) } if v, ok := c.opt_["exactTerms"]; ok { params.Set("exactTerms", fmt.Sprintf("%v", v)) } if v, ok := c.opt_["excludeTerms"]; ok { params.Set("excludeTerms", fmt.Sprintf("%v", v)) } if v, ok := c.opt_["fileType"]; ok { params.Set("fileType", fmt.Sprintf("%v", v)) } if v, ok := c.opt_["filter"]; ok { params.Set("filter", fmt.Sprintf("%v", v)) } if v, ok := c.opt_["gl"]; ok { params.Set("gl", fmt.Sprintf("%v", v)) } if v, ok := c.opt_["googlehost"]; ok { params.Set("googlehost", fmt.Sprintf("%v", v)) } if v, ok := c.opt_["highRange"]; ok { params.Set("highRange", fmt.Sprintf("%v", v)) } if v, ok := c.opt_["hl"]; ok { params.Set("hl", fmt.Sprintf("%v", v)) } if v, ok := c.opt_["hq"]; ok { params.Set("hq", fmt.Sprintf("%v", v)) } if v, ok := c.opt_["imgColorType"]; ok { params.Set("imgColorType", fmt.Sprintf("%v", v)) } if v, ok := c.opt_["imgDominantColor"]; ok { params.Set("imgDominantColor", fmt.Sprintf("%v", v)) } if v, ok := c.opt_["imgSize"]; ok { params.Set("imgSize", fmt.Sprintf("%v", v)) } if v, ok := c.opt_["imgType"]; ok { params.Set("imgType", fmt.Sprintf("%v", v)) } if v, ok := c.opt_["linkSite"]; ok { params.Set("linkSite", fmt.Sprintf("%v", v)) } if v, ok := c.opt_["lowRange"]; ok { params.Set("lowRange", fmt.Sprintf("%v", v)) } if v, ok := c.opt_["lr"]; ok { params.Set("lr", fmt.Sprintf("%v", v)) } if v, ok := c.opt_["num"]; ok { params.Set("num", fmt.Sprintf("%v", v)) } if v, ok := c.opt_["orTerms"]; ok { params.Set("orTerms", fmt.Sprintf("%v", v)) } if v, ok := c.opt_["relatedSite"]; ok { params.Set("relatedSite", fmt.Sprintf("%v", v)) } if v, ok := c.opt_["rights"]; ok { params.Set("rights", fmt.Sprintf("%v", v)) } if v, ok := c.opt_["safe"]; ok { params.Set("safe", fmt.Sprintf("%v", v)) } if v, ok := c.opt_["searchType"]; ok { params.Set("searchType", fmt.Sprintf("%v", v)) } if v, ok := c.opt_["siteSearch"]; ok { params.Set("siteSearch", fmt.Sprintf("%v", v)) } if v, ok := c.opt_["siteSearchFilter"]; ok { params.Set("siteSearchFilter", fmt.Sprintf("%v", v)) } if v, ok := c.opt_["sort"]; ok { params.Set("sort", fmt.Sprintf("%v", v)) } if v, ok := c.opt_["start"]; ok { params.Set("start", fmt.Sprintf("%v", v)) } if v, ok := c.opt_["fields"]; ok { params.Set("fields", fmt.Sprintf("%v", v)) } urls := googleapi.ResolveRelative(c.s.BasePath, "v1") urls += "?" + params.Encode() req, _ := http.NewRequest("GET", urls, body) googleapi.SetOpaque(req.URL) req.Header.Set("User-Agent", c.s.userAgent()) if v, ok := c.opt_["ifNoneMatch"]; ok { req.Header.Set("If-None-Match", fmt.Sprintf("%v", v)) } if c.ctx_ != nil { return ctxhttp.Do(c.ctx_, c.s.client, req) } return c.s.client.Do(req) } // Do executes the "search.cse.list" call. // Exactly one of *Search or error will be non-nil. Any non-2xx status // code is an error. Response headers are in either // *Search.ServerResponse.Header or (if a response was returned at all) // in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to // check whether the returned error was because http.StatusNotModified // was returned. func (c *CseListCall) Do() (*Search, error) { res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &Search{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { return nil, err } return ret, nil // { // "description": "Returns metadata about the search performed, metadata about the custom search engine used for the search, and the search results.", // "httpMethod": "GET", // "id": "search.cse.list", // "parameterOrder": [ // "q" // ], // "parameters": { // "c2coff": { // "description": "Turns off the translation between zh-CN and zh-TW.", // "location": "query", // "type": "string" // }, // "cr": { // "description": "Country restrict(s).", // "location": "query", // "type": "string" // }, // "cref": { // "description": "The URL of a linked custom search engine", // "location": "query", // "type": "string" // }, // "cx": { // "description": "The custom search engine ID to scope this search query", // "location": "query", // "type": "string" // }, // "dateRestrict": { // "description": "Specifies all search results are from a time period", // "location": "query", // "type": "string" // }, // "exactTerms": { // "description": "Identifies a phrase that all documents in the search results must contain", // "location": "query", // "type": "string" // }, // "excludeTerms": { // "description": "Identifies a word or phrase that should not appear in any documents in the search results", // "location": "query", // "type": "string" // }, // "fileType": { // "description": "Returns images of a specified type. Some of the allowed values are: bmp, gif, png, jpg, svg, pdf, ...", // "location": "query", // "type": "string" // }, // "filter": { // "description": "Controls turning on or off the duplicate content filter.", // "enum": [ // "0", // "1" // ], // "enumDescriptions": [ // "Turns off duplicate content filter.", // "Turns on duplicate content filter." // ], // "location": "query", // "type": "string" // }, // "gl": { // "description": "Geolocation of end user.", // "location": "query", // "type": "string" // }, // "googlehost": { // "description": "The local Google domain to use to perform the search.", // "location": "query", // "type": "string" // }, // "highRange": { // "description": "Creates a range in form as_nlo value..as_nhi value and attempts to append it to query", // "location": "query", // "type": "string" // }, // "hl": { // "description": "Sets the user interface language.", // "location": "query", // "type": "string" // }, // "hq": { // "description": "Appends the extra query terms to the query.", // "location": "query", // "type": "string" // }, // "imgColorType": { // "description": "Returns black and white, grayscale, or color images: mono, gray, and color.", // "enum": [ // "color", // "gray", // "mono" // ], // "enumDescriptions": [ // "color", // "gray", // "mono" // ], // "location": "query", // "type": "string" // }, // "imgDominantColor": { // "description": "Returns images of a specific dominant color: yellow, green, teal, blue, purple, pink, white, gray, black and brown.", // "enum": [ // "black", // "blue", // "brown", // "gray", // "green", // "pink", // "purple", // "teal", // "white", // "yellow" // ], // "enumDescriptions": [ // "black", // "blue", // "brown", // "gray", // "green", // "pink", // "purple", // "teal", // "white", // "yellow" // ], // "location": "query", // "type": "string" // }, // "imgSize": { // "description": "Returns images of a specified size, where size can be one of: icon, small, medium, large, xlarge, xxlarge, and huge.", // "enum": [ // "huge", // "icon", // "large", // "medium", // "small", // "xlarge", // "xxlarge" // ], // "enumDescriptions": [ // "huge", // "icon", // "large", // "medium", // "small", // "xlarge", // "xxlarge" // ], // "location": "query", // "type": "string" // }, // "imgType": { // "description": "Returns images of a type, which can be one of: clipart, face, lineart, news, and photo.", // "enum": [ // "clipart", // "face", // "lineart", // "news", // "photo" // ], // "enumDescriptions": [ // "clipart", // "face", // "lineart", // "news", // "photo" // ], // "location": "query", // "type": "string" // }, // "linkSite": { // "description": "Specifies that all search results should contain a link to a particular URL", // "location": "query", // "type": "string" // }, // "lowRange": { // "description": "Creates a range in form as_nlo value..as_nhi value and attempts to append it to query", // "location": "query", // "type": "string" // }, // "lr": { // "description": "The language restriction for the search results", // "enum": [ // "lang_ar", // "lang_bg", // "lang_ca", // "lang_cs", // "lang_da", // "lang_de", // "lang_el", // "lang_en", // "lang_es", // "lang_et", // "lang_fi", // "lang_fr", // "lang_hr", // "lang_hu", // "lang_id", // "lang_is", // "lang_it", // "lang_iw", // "lang_ja", // "lang_ko", // "lang_lt", // "lang_lv", // "lang_nl", // "lang_no", // "lang_pl", // "lang_pt", // "lang_ro", // "lang_ru", // "lang_sk", // "lang_sl", // "lang_sr", // "lang_sv", // "lang_tr", // "lang_zh-CN", // "lang_zh-TW" // ], // "enumDescriptions": [ // "Arabic", // "Bulgarian", // "Catalan", // "Czech", // "Danish", // "German", // "Greek", // "English", // "Spanish", // "Estonian", // "Finnish", // "French", // "Croatian", // "Hungarian", // "Indonesian", // "Icelandic", // "Italian", // "Hebrew", // "Japanese", // "Korean", // "Lithuanian", // "Latvian", // "Dutch", // "Norwegian", // "Polish", // "Portuguese", // "Romanian", // "Russian", // "Slovak", // "Slovenian", // "Serbian", // "Swedish", // "Turkish", // "Chinese (Simplified)", // "Chinese (Traditional)" // ], // "location": "query", // "type": "string" // }, // "num": { // "default": "10", // "description": "Number of search results to return", // "format": "uint32", // "location": "query", // "type": "integer" // }, // "orTerms": { // "description": "Provides additional search terms to check for in a document, where each document in the search results must contain at least one of the additional search terms", // "location": "query", // "type": "string" // }, // "q": { // "description": "Query", // "location": "query", // "required": true, // "type": "string" // }, // "relatedSite": { // "description": "Specifies that all search results should be pages that are related to the specified URL", // "location": "query", // "type": "string" // }, // "rights": { // "description": "Filters based on licensing. Supported values include: cc_publicdomain, cc_attribute, cc_sharealike, cc_noncommercial, cc_nonderived and combinations of these.", // "location": "query", // "type": "string" // }, // "safe": { // "default": "off", // "description": "Search safety level", // "enum": [ // "high", // "medium", // "off" // ], // "enumDescriptions": [ // "Enables highest level of safe search filtering.", // "Enables moderate safe search filtering.", // "Disables safe search filtering." // ], // "location": "query", // "type": "string" // }, // "searchType": { // "description": "Specifies the search type: image.", // "enum": [ // "image" // ], // "enumDescriptions": [ // "custom image search" // ], // "location": "query", // "type": "string" // }, // "siteSearch": { // "description": "Specifies all search results should be pages from a given site", // "location": "query", // "type": "string" // }, // "siteSearchFilter": { // "description": "Controls whether to include or exclude results from the site named in the as_sitesearch parameter", // "enum": [ // "e", // "i" // ], // "enumDescriptions": [ // "exclude", // "include" // ], // "location": "query", // "type": "string" // }, // "sort": { // "description": "The sort expression to apply to the results", // "location": "query", // "type": "string" // }, // "start": { // "description": "The index of the first result to return", // "format": "uint32", // "location": "query", // "type": "integer" // } // }, // "path": "v1", // "response": { // "$ref": "Search" // } // } }<|fim▁end|>
// Possible values: // "black" - black // "blue" - blue // "brown" - brown
<|file_name|>RepositorySetRepositories.js<|end_file_name|><|fim▁begin|>import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { Alert, Spinner } from 'patternfly-react'; import { translate as __ } from 'foremanReact/common/I18n'; import loadRepositorySetRepos from '../../../redux/actions/RedHatRepositories/repositorySetRepositories'; import RepositorySetRepository from './RepositorySetRepository/'; import { yStream } from './RepositorySetRepositoriesHelpers'; class RepositorySetRepositories extends Component { componentDidMount() { const { contentId, productId } = this.props; if (this.props.data.loading) { this.props.loadRepositorySetRepos(contentId, productId); } } sortedRepos = repos => [...repos.filter(({ enabled }) => !enabled)] .sort((repo1, repo2) => { const repo1YStream = yStream(repo1.releasever || ''); const repo2YStream = yStream(repo2.releasever || ''); if (repo1YStream < repo2YStream) { return -1; } if (repo2YStream < repo1YStream) { return 1; } if (repo1.arch === repo2.arch) { const repo1MajorMinor = repo1.releasever.split('.'); const repo2MajorMinor = repo2.releasever.split('.'); const repo1Major = parseInt(repo1MajorMinor[0], 10); const repo2Major = parseInt(repo2MajorMinor[0], 10); if (repo1Major === repo2Major) { const repo1Minor = parseInt(repo1MajorMinor[1], 10); const repo2Minor = parseInt(repo2MajorMinor[1], 10); if (repo1Minor === repo2Minor) { return 0; } return (repo1Minor > repo2Minor) ? -1 : 1; } return (repo1Major > repo2Major) ? -1 : 1; } return (repo1.arch > repo2.arch) ? -1 : 1; }); render() { const { data, type } = this.props; if (data.error) { return ( <Alert type="danger"> <span>{data.error.displayMessage}</span> </Alert> ); } const availableRepos = this.sortedRepos(data.repositories).map(repo => ( <RepositorySetRepository key={repo.arch + repo.releasever} type={type} {...repo} /> )); const repoMessage = (data.repositories.length > 0 && availableRepos.length === 0 ? __('All available architectures for this repo are enabled.') : __('No repositories available.'));<|fim▁hole|> return ( <Spinner loading={data.loading}> {availableRepos.length ? availableRepos : <div>{repoMessage}</div>} </Spinner> ); } } RepositorySetRepositories.propTypes = { loadRepositorySetRepos: PropTypes.func.isRequired, contentId: PropTypes.number.isRequired, productId: PropTypes.number.isRequired, type: PropTypes.string, data: PropTypes.shape({ loading: PropTypes.bool.isRequired, repositories: PropTypes.arrayOf(PropTypes.object), error: PropTypes.shape({ displayMessage: PropTypes.string, }), }).isRequired, }; RepositorySetRepositories.defaultProps = { type: '', }; const mapStateToProps = ( { katello: { redHatRepositories: { repositorySetRepositories } } }, props, ) => ({ data: repositorySetRepositories[props.contentId] || { loading: true, repositories: [], error: null, }, }); export default connect(mapStateToProps, { loadRepositorySetRepos, })(RepositorySetRepositories);<|fim▁end|>
<|file_name|>cs.js<|end_file_name|><|fim▁begin|><|fim▁hole|>/* Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'specialchar', 'cs', { options: 'Nastavení speciálních znaků', title: 'Výběr speciálního znaku', toolbar: 'Vložit speciální znaky' } );<|fim▁end|>
<|file_name|>attach.go<|end_file_name|><|fim▁begin|>package operation import ( "fmt" "os" "github.com/runabove/sail/internal" "github.com/spf13/cobra" ) var cmdOperationAttach = &cobra.Command{ Use: "attach", Short: "Attach to an ongoing operation output: sail operation attach [applicationName] <operationId>", Long: `Attach to an ongoing operation output: sail operation attach [applicationName] <operationId> <|fim▁hole|>Example: sail operation attach devel/redis fa853ede-6c05-4823-8b20-46a5389fe0de If the applicationName is not passed, the default application name will be used (the user's username). `, Run: func(cmd *cobra.Command, args []string) { switch len(args) { case 1: // applicationName was not passed. Using default one. applicationName := internal.GetUserName() operationAttach(applicationName, args[0]) case 2: operationAttach(args[0], args[1]) default: fmt.Fprintln(os.Stderr, "Invalid usage. sail operation attach [applicationName] <operationId>. Please see sail operation attach --help") } }, } func operationAttach(app, operationID string) { // Split namespace and service internal.StreamPrint("GET", fmt.Sprintf("/applications/%s/operation/%s/attach", app, operationID), nil) internal.ExitAfterCtrlC() }<|fim▁end|>
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""StoreServer provides a number of plugins which can provide a store service on a server. <|fim▁hole|>These can be used to simplify provision of a store, e.g using the ``webserver`` StoreServer instead of installing a 3rd party webserver such as Apache. """<|fim▁end|>
There are currently 2 plugins available: ``webserver`` and ``gitdaemon``.
<|file_name|>OgreQuake3Shader.cpp<|end_file_name|><|fim▁begin|>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2011 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreQuake3Shader.h" #include "OgreSceneManager.h" #include "OgreMaterial.h" #include "OgreTechnique.h" #include "OgrePass.h" #include "OgreTextureUnitState.h" #include "OgreMath.h" #include "OgreLogManager.h" #include "OgreTextureManager.h" #include "OgreRoot.h" #include "OgreMaterialManager.h" namespace Ogre { //----------------------------------------------------------------------- Quake3Shader::Quake3Shader(const String& name) { mName = name; numPasses = 0; deformFunc = DEFORM_FUNC_NONE; farbox = false; skyDome = false; flags = 0; fog = false; cullMode = MANUAL_CULL_BACK; } //----------------------------------------------------------------------- Quake3Shader::~Quake3Shader() { } //----------------------------------------------------------------------- MaterialPtr Quake3Shader::createAsMaterial(int lightmapNumber) { String matName; StringUtil::StrStreamType str; String resourceGroup = ResourceGroupManager::getSingleton().getWorldResourceGroupName(); str << mName << "#" << lightmapNumber; matName = str.str(); MaterialPtr mat = MaterialManager::getSingleton().create(matName, resourceGroup); Ogre::Pass* ogrePass = mat->getTechnique(0)->getPass(0); LogManager::getSingleton().logMessage("Using Q3 shader " + mName, LML_CRITICAL); for (int p = 0; p < numPasses; ++p) { TextureUnitState* t; // Create basic texture if (pass[p].textureName == "$lightmap") { StringUtil::StrStreamType str2; str2 << "@lightmap" << lightmapNumber; t = ogrePass->createTextureUnitState(str2.str()); } // Animated texture support else if (pass[p].animNumFrames > 0) { Real sequenceTime = pass[p].animNumFrames / pass[p].animFps; /* Pre-load textures We need to know if each one was loaded OK since extensions may change for each Quake3 can still include alternate extension filenames e.g. jpg instead of tga Pain in the arse - have to check for each frame as letters<n>.tga for example is different per frame! */ for (unsigned int alt = 0; alt < pass[p].animNumFrames; ++alt) { if (!ResourceGroupManager::getSingleton().resourceExists( resourceGroup, pass[p].frames[alt])) { // Try alternate extension pass[p].frames[alt] = getAlternateName(pass[p].frames[alt]); if (!ResourceGroupManager::getSingleton().resourceExists( resourceGroup, pass[p].frames[alt])) { <|fim▁hole|> // stuffed - no texture continue; } } } t = ogrePass->createTextureUnitState(""); t->setAnimatedTextureName(pass[p].frames, pass[p].animNumFrames, sequenceTime); } else { // Quake3 can still include alternate extension filenames e.g. jpg instead of tga // Pain in the arse - have to check for failure if (!ResourceGroupManager::getSingleton().resourceExists( resourceGroup, pass[p].textureName)) { // Try alternate extension pass[p].textureName = getAlternateName(pass[p].textureName); if (!ResourceGroupManager::getSingleton().resourceExists( resourceGroup, pass[p].textureName)) { // stuffed - no texture continue; } } t = ogrePass->createTextureUnitState(pass[p].textureName); } // Blending if (p == 0) { // scene blend mat->setSceneBlending(pass[p].blendSrc, pass[p].blendDest); if (mat->isTransparent()) mat->setDepthWriteEnabled(false); t->setColourOperation(LBO_REPLACE); // Alpha mode ogrePass->setAlphaRejectSettings( pass[p].alphaFunc, pass[p].alphaVal); } else { if (pass[p].customBlend) { // Fallback for now t->setColourOperation(LBO_MODULATE); } else { // simple layer blend t->setColourOperation(pass[p].blend); } // Alpha mode, prefer 'most alphary' CompareFunction currFunc = ogrePass->getAlphaRejectFunction(); unsigned char currVal = ogrePass->getAlphaRejectValue(); if (pass[p].alphaFunc > currFunc || (pass[p].alphaFunc == currFunc && pass[p].alphaVal < currVal)) { ogrePass->setAlphaRejectSettings( pass[p].alphaFunc, pass[p].alphaVal); } } // Tex coords if (pass[p].texGen == TEXGEN_BASE) { t->setTextureCoordSet(0); } else if (pass[p].texGen == TEXGEN_LIGHTMAP) { t->setTextureCoordSet(1); } else if (pass[p].texGen == TEXGEN_ENVIRONMENT) { t->setEnvironmentMap(true, TextureUnitState::ENV_PLANAR); } // Tex mod // Scale t->setTextureUScale(pass[p].tcModScale[0]); t->setTextureVScale(pass[p].tcModScale[1]); // Procedural mods // Custom - don't use mod if generating environment // Because I do env a different way it look horrible if (pass[p].texGen != TEXGEN_ENVIRONMENT) { if (pass[p].tcModRotate) { t->setRotateAnimation(pass[p].tcModRotate); } if (pass[p].tcModScroll[0] || pass[p].tcModScroll[1]) { if (pass[p].tcModTurbOn) { // Turbulent scroll if (pass[p].tcModScroll[0]) { t->setTransformAnimation(TextureUnitState::TT_TRANSLATE_U, WFT_SINE, pass[p].tcModTurb[0], pass[p].tcModTurb[3], pass[p].tcModTurb[2], pass[p].tcModTurb[1]); } if (pass[p].tcModScroll[1]) { t->setTransformAnimation(TextureUnitState::TT_TRANSLATE_V, WFT_SINE, pass[p].tcModTurb[0], pass[p].tcModTurb[3], pass[p].tcModTurb[2], pass[p].tcModTurb[1]); } } else { // Constant scroll t->setScrollAnimation(pass[p].tcModScroll[0], pass[p].tcModScroll[1]); } } if (pass[p].tcModStretchWave != SHADER_FUNC_NONE) { WaveformType wft = WFT_SINE; switch(pass[p].tcModStretchWave) { case SHADER_FUNC_SIN: wft = WFT_SINE; break; case SHADER_FUNC_TRIANGLE: wft = WFT_TRIANGLE; break; case SHADER_FUNC_SQUARE: wft = WFT_SQUARE; break; case SHADER_FUNC_SAWTOOTH: wft = WFT_SAWTOOTH; break; case SHADER_FUNC_INVERSESAWTOOTH: wft = WFT_INVERSE_SAWTOOTH; break; default: break; } // Create wave-based stretcher t->setTransformAnimation(TextureUnitState::TT_SCALE_U, wft, pass[p].tcModStretchParams[3], pass[p].tcModStretchParams[0], pass[p].tcModStretchParams[2], pass[p].tcModStretchParams[1]); t->setTransformAnimation(TextureUnitState::TT_SCALE_V, wft, pass[p].tcModStretchParams[3], pass[p].tcModStretchParams[0], pass[p].tcModStretchParams[2], pass[p].tcModStretchParams[1]); } } // Address mode t->setTextureAddressingMode(pass[p].addressMode); //assert(!t->isBlank()); } // Do farbox (create new material) // Set culling mode and lighting to defaults mat->setCullingMode(CULL_NONE); mat->setManualCullingMode(cullMode); mat->setLightingEnabled(false); mat->load(); return mat; } String Quake3Shader::getAlternateName(const String& texName) { // Get alternative JPG to TGA and vice versa size_t pos; String ext, base; pos = texName.find_last_of("."); ext = texName.substr(pos, 4); StringUtil::toLowerCase(ext); base = texName.substr(0,pos); if (ext == ".jpg") { return base + ".tga"; } else { return base + ".jpg"; } } }<|fim▁end|>
<|file_name|>gendocert.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import sys from httplib import HTTPConnection from urllib import urlencode from urlparse import urljoin from json import loads from reportlab.pdfgen import canvas OUTPUTFILE = 'certificate.pdf' def get_brooklyn_integer(): ''' Ask Brooklyn Integers for a single integer.<|fim▁hole|> From: https://github.com/migurski/ArtisinalInts/ ''' body = 'method=brooklyn.integers.create' head = {'Content-Type': 'application/x-www-form-urlencoded'} conn = HTTPConnection('api.brooklynintegers.com', 80) conn.request('POST', '/rest/', body, head) resp = conn.getresponse() if resp.status not in range(200, 299): raise Exception('Non-2XX response code from Brooklyn: %d' % resp.status) data = loads(resp.read()) value = data['integer'] return value def draw_pdf(sparklydevop): certimage = './devops.cert.png' # TODO make this a function of image size width = 1116 height = 1553 # Times Roman better fits the other fonts on the template font_name = "Times-Roman" # TODO make font size a function of name length font_size = 72 c = canvas.Canvas(OUTPUTFILE, pagesize=(width, height)) c.setFont(font_name, font_size) # Print Name name_offset = c.stringWidth(sparklydevop) try: c.drawImage(certimage, 1, 1) except IOError: print "I/O error trying to open %s" % certimage else: c.drawString((width-name_offset)/2, height*3/4, sparklydevop) # Print Certificate Number cert_number = "Certificate No. " + str(get_brooklyn_integer()) cert_offset = c.stringWidth(cert_number) c.drawString((width-cert_offset)/2, height*3/4-font_size*2, cert_number) c.showPage() # TODO check for write permissions/failure try: c.save() except IOError: print "I/O error trying to save %s" % OUTPUTFILE if __name__ == "__main__": if len(sys.argv) != 2: print 'Usage: gendocert.py "Firstname Lastname"' sys.exit(1) else: # TODO if this is run as a CGI need to sanitize input draw_pdf(sys.argv[1])<|fim▁end|>
Returns a tuple with number and integer permalink.
<|file_name|>setup_pkgresource.py<|end_file_name|><|fim▁begin|>def _setup_pkgresources(): import pkg_resources import os import plistlib pl = plistlib.readPlist(os.path.join( os.path.dirname(os.getenv('RESOURCEPATH')), "Info.plist")) appname = pl.get('CFBundleIdentifier') if appname is None: appname = pl['CFBundleDisplayName'] path = os.path.expanduser('~/Library/Caches/%s/python-eggs' % (appname,))<|fim▁hole|>_setup_pkgresources()<|fim▁end|>
pkg_resources.set_extraction_path(path)
<|file_name|>palette.js<|end_file_name|><|fim▁begin|>Palette = function(name,colors){ this.name = name; this.colors = colors; }; Palette.prototype.hasName = function(name){ return this.name.toLowerCase() == name.toLowerCase()?true:false; }; Palette.prototype.getRandomColor = function(){ return this.colors[(Math.floor(Math.random() * this.colors.length))]; }; Palette.prototype.getName = function(){ return this.name; }; Palette.prototype.setName = function(name){ this.name = name; }; <|fim▁hole|>}; Palette.prototype.setColors = function(colors){ this.colors = colors; }; Palette.generateRandomPalette = function(){ var colors = []; for(var i = 0; i< 5; i++){ colors.push(('#'+Math.floor(Math.random()*16777215).toString(16)).toUpperCase()); } return new Palette("RandomizePalette",colors); };<|fim▁end|>
Palette.prototype.getColors = function(){ return this.colors;
<|file_name|>upload_test.go<|end_file_name|><|fim▁begin|>package host import ( "errors" "io/ioutil" "path/filepath" "testing" "time" "github.com/NebulousLabs/Sia/crypto" "github.com/NebulousLabs/Sia/modules" "github.com/NebulousLabs/Sia/modules/renter" "github.com/NebulousLabs/Sia/types" ) const ( testUploadDuration = 20 // Duration in blocks of a standard upload during testing. // Helper variables to indicate whether renew is being toggled as input to // uploadFile. renewEnabled = true renewDisabled = false ) // uploadFile uploads a file to the host from the tester's renter. The data // used to make the file is returned. The nickname of the file in the renter is // the same as the name provided as input. func (ht *hostTester) uploadFile(path string, renew bool) ([]byte, error) { // Check that renting is initialized properly. err := ht.initRenting() if err != nil { return nil, err } // Create a file to upload to the host. source := filepath.Join(ht.persistDir, path+".testfile") datasize := uint64(1024) data, err := crypto.RandBytes(int(datasize)) if err != nil { return nil, err } err = ioutil.WriteFile(source, data, 0600) if err != nil { return nil, err }<|fim▁hole|> return nil, err } fup := modules.FileUploadParams{ Source: source, SiaPath: path, Duration: testUploadDuration, Renew: renew, ErasureCode: rsc, PieceSize: 0, } err = ht.renter.Upload(fup) if err != nil { return nil, err } // Wait until the upload has finished. for i := 0; i < 100; i++ { time.Sleep(time.Millisecond * 100) // Asynchronous processes in the host access obligations by id, // therefore a lock is required to scan the set of obligations. if func() bool { ht.host.mu.Lock() defer ht.host.mu.Unlock() for _, ob := range ht.host.obligationsByID { if ob.fileSize() >= datasize { return true } } return false }() { break } } // Block until the renter is at 50 upload progress - it takes time for the // contract to confirm renter-side. complete := false for i := 0; i < 50 && !complete; i++ { fileInfos := ht.renter.FileList() for _, fileInfo := range fileInfos { if fileInfo.UploadProgress >= 50 { complete = true } } if complete { break } time.Sleep(time.Millisecond * 50) } if !complete { return nil, errors.New("renter never recognized that the upload completed") } // The rest of the upload can be performed under lock. ht.host.mu.Lock() defer ht.host.mu.Unlock() if len(ht.host.obligationsByID) != 1 { return nil, errors.New("expecting a single obligation") } for _, ob := range ht.host.obligationsByID { if ob.fileSize() >= datasize { return data, nil } } return nil, errors.New("ht.uploadFile: upload failed") } // TestRPCUPload attempts to upload a file to the host, adding coverage to the // upload function. func TestRPCUpload(t *testing.T) { if testing.Short() { t.SkipNow() } ht, err := newHostTester("TestRPCUpload") if err != nil { t.Fatal(err) } ht.host.mu.RLock() baselineAnticipatedRevenue := ht.host.anticipatedRevenue baselineSpace := ht.host.spaceRemaining ht.host.mu.RUnlock() _, err = ht.uploadFile("TestRPCUpload - 1", renewDisabled) if err != nil { t.Fatal(err) } var expectedRevenue types.Currency func() { ht.host.mu.RLock() defer ht.host.mu.RUnlock() if ht.host.anticipatedRevenue.Cmp(baselineAnticipatedRevenue) <= 0 { t.Error("Anticipated revenue did not increase after a file was uploaded") } if baselineSpace <= ht.host.spaceRemaining { t.Error("space remaining on the host does not seem to have decreased") } expectedRevenue = ht.host.anticipatedRevenue }() // Mine until the storage proof goes through, and the obligation gets // cleared. for i := types.BlockHeight(0); i <= testUploadDuration+confirmationRequirement+defaultWindowSize; i++ { _, err := ht.miner.AddBlock() if err != nil { t.Fatal(err) } } // Check that the storage proof has succeeded. ht.host.mu.Lock() defer ht.host.mu.Unlock() if len(ht.host.obligationsByID) != 0 { t.Error("host still has obligation, when it should have completed the obligation and submitted a storage proof.") } if !ht.host.anticipatedRevenue.IsZero() { t.Error("host anticipated revenue was not set back to zero") } if ht.host.spaceRemaining != baselineSpace { t.Error("host does not seem to have reclaimed the space after a successful obligation") } if expectedRevenue.Cmp(ht.host.revenue) != 0 { t.Error("host's revenue was not moved from anticipated to expected") } } // TestRPCRenew attempts to upload a file to the host, adding coverage to the // upload function. func TestRPCRenew(t *testing.T) { t.Skip("test skipped because the renter renew function isn't block based") if testing.Short() { t.SkipNow() } ht, err := newHostTester("TestRPCRenew") if err != nil { t.Fatal(err) } _, err = ht.uploadFile("TestRPCRenew- 1", renewEnabled) if err != nil { t.Fatal(err) } ht.host.mu.RLock() expectedRevenue := ht.host.anticipatedRevenue expectedSpaceRemaining := ht.host.spaceRemaining ht.host.mu.RUnlock() // Mine until the storage proof goes through, and the obligation gets // cleared. for i := types.BlockHeight(0); i <= testUploadDuration+confirmationRequirement+defaultWindowSize; i++ { _, err := ht.miner.AddBlock() if err != nil { t.Fatal(err) } } // Check that the rewards for the first obligation went through, and that // there is another from the contract being renewed. ht.host.mu.Lock() defer ht.host.mu.Unlock() if len(ht.host.obligationsByID) != 1 { t.Error("file contract was not renenwed after being completed") } if ht.host.anticipatedRevenue.IsZero() { t.Error("host anticipated revenue should be nonzero") } if ht.host.spaceRemaining != expectedSpaceRemaining { t.Error("host space remaining changed after a renew happened") } if expectedRevenue.Cmp(ht.host.revenue) > 0 { t.Error("host's revenue was not increased though a proof was successful") } // TODO: Download the file that got renewed, see if the data is correct. } // TestFailedObligation tests that the host correctly handles missing a storage // proof. func TestFailedObligation(t *testing.T) { if testing.Short() { t.SkipNow() } ht, err := newHostTester("TestFailedObligation") if err != nil { t.Fatal(err) } ht.host.mu.RLock() baselineSpace := ht.host.spaceRemaining ht.host.mu.RUnlock() _, err = ht.uploadFile("TestFailedObligation - 1", renewDisabled) if err != nil { t.Fatal(err) } ht.host.mu.RLock() expectedLostRevenue := ht.host.anticipatedRevenue ht.host.mu.RUnlock() // Close the host, then mine enough blocks that the host has missed the // storage proof window. err = ht.host.Close() if err != nil { t.Fatal(err) } for i := types.BlockHeight(0); i <= testUploadDuration+defaultWindowSize+2; i++ { _, err := ht.miner.AddBlock() if err != nil { t.Fatal(err) } } // Restart the host. While catching up, the host should realize that it // missed a storage proof, and should delete the obligation. rebootHost, err := New(ht.cs, ht.tpool, ht.wallet, ":0", filepath.Join(ht.persistDir, modules.HostDir)) if err != nil { t.Fatal(err) } // Host should delete the obligation before finishing startup. rebootHost.mu.Lock() defer rebootHost.mu.Unlock() if len(rebootHost.obligationsByID) != 0 { t.Error("host did not delete a dead storage proof at startup") } if !rebootHost.anticipatedRevenue.IsZero() { t.Error("host did not subtract out anticipated revenue") } if rebootHost.spaceRemaining != baselineSpace { t.Error("host did not reallocate space after failed storage proof") } if rebootHost.lostRevenue.Cmp(expectedLostRevenue) != 0 { t.Error("host did not correctly report lost revenue") } } // TestRestartSuccessObligation tests that a host who went offline for a few // blocks is still able to successfully submit a storage proof. func TestRestartSuccessObligation(t *testing.T) { if testing.Short() { t.SkipNow() } ht, err := newHostTester("TestRestartSuccessObligation") if err != nil { t.Fatal(err) } ht.host.mu.RLock() baselineSpace := ht.host.spaceRemaining ht.host.mu.RUnlock() _, err = ht.uploadFile("TestRestartSuccessObligation - 1", renewDisabled) if err != nil { t.Fatal(err) } ht.host.mu.RLock() expectedRevenue := ht.host.anticipatedRevenue ht.host.mu.RUnlock() // Close the host, then mine some blocks, but not enough that the host // misses the storage proof. err = ht.host.Close() if err != nil { t.Fatal(err) } for i := 0; i <= 5; i++ { _, err := ht.miner.AddBlock() if err != nil { t.Fatal(err) } } // Restart the host, and mine enough blocks that the host can submit a // successful storage proof. rebootHost, err := New(ht.cs, ht.tpool, ht.wallet, ":0", filepath.Join(ht.persistDir, modules.HostDir)) if err != nil { t.Fatal(err) } if rebootHost.blockHeight != ht.cs.Height() { t.Error("Host block height does not match the cs block height") } for i := types.BlockHeight(0); i <= testUploadDuration+defaultWindowSize+confirmationRequirement-5; i++ { _, err := ht.miner.AddBlock() if err != nil { t.Fatal(err) } } // Confirm that the storage proof was successful. rebootHost.mu.Lock() defer rebootHost.mu.Unlock() if len(rebootHost.obligationsByID) != 0 { t.Error("host did not delete a finished obligation") } if !rebootHost.anticipatedRevenue.IsZero() { t.Error("host did not subtract out anticipated revenue") } if rebootHost.spaceRemaining != baselineSpace { t.Error("host did not reallocate space after storage proof") } if rebootHost.revenue.Cmp(expectedRevenue) != 0 { t.Error("host did not correctly report revenue gains") } } // TestRestartCorruptSuccessObligation tests that a host who went offline for a // few blocks, corrupted the consensus database, but is still able to correctly // create a storage proof. func TestRestartCorruptSuccessObligation(t *testing.T) { if testing.Short() { t.SkipNow() } ht, err := newHostTester("TestRestartCorruptSuccessObligation") if err != nil { t.Fatal(err) } ht.host.mu.RLock() baselineSpace := ht.host.spaceRemaining ht.host.mu.RUnlock() _, err = ht.uploadFile("TestRestartCorruptSuccessObligation - 1", renewDisabled) if err != nil { t.Fatal(err) } ht.host.mu.RLock() expectedRevenue := ht.host.anticipatedRevenue ht.host.mu.RUnlock() // Corrupt the host's consensus tracking, close the host, then mine some // blocks, but not enough that the host misses the storage proof. The host // will need to perform a rescan and update its obligations correctly. ht.host.mu.Lock() ht.host.recentChange[0]++ ht.host.mu.Unlock() err = ht.host.Close() if err != nil { t.Fatal(err) } for i := 0; i <= 3; i++ { _, err := ht.miner.AddBlock() if err != nil { t.Fatal(err) } } // Restart the host, and mine enough blocks that the host can submit a // successful storage proof. rebootHost, err := New(ht.cs, ht.tpool, ht.wallet, ":0", filepath.Join(ht.persistDir, modules.HostDir)) if err != nil { t.Fatal(err) } if rebootHost.blockHeight != ht.cs.Height() { t.Error("Host block height does not match the cs block height") } if len(rebootHost.obligationsByID) == 0 { t.Error("host did not correctly reload its obligation") } for i := types.BlockHeight(0); i <= testUploadDuration+defaultWindowSize+confirmationRequirement-3; i++ { _, err := ht.miner.AddBlock() if err != nil { t.Fatal(err) } } // Confirm that the storage proof was successful. rebootHost.mu.Lock() defer rebootHost.mu.Unlock() if len(rebootHost.obligationsByID) != 0 { t.Error("host did not delete a finished obligation") } if !rebootHost.anticipatedRevenue.IsZero() { t.Error("host did not subtract out anticipated revenue") } if rebootHost.spaceRemaining != baselineSpace { t.Error("host did not reallocate space after storage proof") } if rebootHost.revenue.Cmp(expectedRevenue) != 0 { t.Error("host did not correctly report revenue gains") } if rebootHost.lostRevenue.Cmp(expectedRevenue) == 0 { t.Error("host is reporting losses on the file contract") } }<|fim▁end|>
// Have the renter upload to the host. rsc, err := renter.NewRSCode(1, 1) if err != nil {
<|file_name|>controller.py<|end_file_name|><|fim▁begin|># # controller.py # # Copyright (C) 2013-2014 Ashwin Menon <ashwin.menon@gmail.com> # Copyright (C) 2015-2018 Track Master Steve <trackmastersteve@gmail.com> # # Alienfx is free software. # # You may redistribute it and/or modify it under the terms of the # GNU General Public License, as published by the Free Software # Foundation; either version 3 of the License, or (at your option) # any later version. # # Alienfx is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with alienfx. If not, write to: # The Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor # Boston, MA 02110-1301, USA. # """ Base classes for AlienFX controller chips. These must be subclassed for specific controllers. This module provides the following classes: AlienFXController: base class for AlienFX controller chips """ from builtins import hex from builtins import object import logging import alienfx.core.usbdriver as alienfx_usbdriver import alienfx.core.cmdpacket as alienfx_cmdpacket from alienfx.core.themefile import AlienFXThemeFile from functools import reduce class AlienFXController(object): """ Provides facilities to communicate with an AlienFX controller. This class provides methods to send commands to an AlienFX controller, and receive status from the controller. It must be overridden to provide behaviour specific to a particular AlienFX controller. """ # List of all subclasses of this class. Subclasses must add instances of # themselves to this list. See README for details. supported_controllers = [] # Zone names ZONE_LEFT_KEYBOARD = "Left Keyboard" ZONE_MIDDLE_LEFT_KEYBOARD = "Middle-left Keyboard" ZONE_MIDDLE_RIGHT_KEYBOARD = "Middle-right Keyboard" ZONE_RIGHT_KEYBOARD = "Right Keyboard" ZONE_RIGHT_SPEAKER = "Right Speaker" ZONE_LEFT_SPEAKER = "Left Speaker" ZONE_ALIEN_HEAD = "Alien Head" ZONE_LOGO = "Logo" ZONE_TOUCH_PAD = "Touchpad" ZONE_MEDIA_BAR = "Media Bar" ZONE_STATUS_LEDS = "Status LEDs" ZONE_POWER_BUTTON = "Power Button" ZONE_HDD_LEDS = "HDD LEDs" ZONE_RIGHT_DISPLAY = "Right Display" # LED-bar display right side, as built in the AW17R4 ZONE_LEFT_DISPLAY = "Left Display" # LED-bar display left side, as built in the AW17R4 # State names STATE_BOOT = "Boot" STATE_AC_SLEEP = "AC Sleep" STATE_AC_CHARGED = "AC Charged" STATE_AC_CHARGING = "AC Charging" STATE_BATTERY_SLEEP = "Battery Sleep" STATE_BATTERY_ON = "Battery On" STATE_BATTERY_CRITICAL = "Battery Critical" ALIENFX_CONTROLLER_TYPE = "old" # Default controllertype=old. Note that modern controllers are using 8 bits per color. older ones just 4 def __init__(self, conrev=1): # conrev defaulting to 1 to maintain compatibility with old definitions # conrev=1 -> old controllers (DEFAULT) # conrev=2 -> newer controllers (17R4 ...) self.zone_map = {} self.power_zones = [] self.reset_types = {} self.state_map = {} self.vendor_id = 0 self.product_id = 0 self.cmd_packet = alienfx_cmdpacket.AlienFXCmdPacket(conrev) # Loads the cmdpacket. self._driver = alienfx_usbdriver.AlienFXUSBDriver(self) def get_zone_name(self, pkt): """ Given 3 bytes of a command packet, return a string zone name corresponding to it """ zone_mask = (pkt[0] << 16) + (pkt[1] << 8) + pkt[2] zone_name = "" for zone in self.zone_map: bit_mask = self.zone_map[zone] if zone_mask & bit_mask:<|fim▁hole|> zone_name += "," zone_name += zone zone_mask &= ~bit_mask if zone_mask != 0: if zone_name != "": zone_name += "," zone_name += "UNKNOWN({})".format(hex(zone_mask)) return zone_name def get_state_name(self, state): """ Given a state number, return a string state name """ for state_name in self.state_map: if self.state_map[state_name] == state: return state_name return "UNKNOWN" def get_reset_type_name(self, num): """ Given a reset number, return a string reset name """ if num in list(self.reset_types.keys()): return self.reset_types[num] else: return "UNKNOWN" def _ping(self): """ Send a get-status command to the controller.""" pkt = self.cmd_packet.make_cmd_get_status() logging.debug("SENDING: {}".format(self.pkt_to_string(pkt))) self._driver.write_packet(pkt) self._driver.read_packet() def _reset(self, reset_type): """ Send a "reset" packet to the AlienFX controller.""" reset_code = self._get_reset_code(reset_type) pkt = self.cmd_packet.make_cmd_reset(reset_code) logging.debug("SENDING: {}".format(self.pkt_to_string(pkt))) self._driver.write_packet(pkt) def _wait_controller_ready(self): """ Keep sending a "get status" packet to the AlienFX controller and return only when the controller is ready """ ready = False errcount=0 while not ready: pkt = self.cmd_packet.make_cmd_get_status() logging.debug("SENDING: {}".format(self.pkt_to_string(pkt))) self._driver.write_packet(pkt) try: resp = self._driver.read_packet() ready = (resp[0] == self.cmd_packet.STATUS_READY) except TypeError: errcount += 1 logging.debug("No Status received yet... Failed tries=" + str(errcount)) if errcount > 50: logging.error("Controller status could not be retrieved. Is the device already in use?") quit(-99) def pkt_to_string(self, pkt_bytes): """ Return a human readable string representation of an AlienFX command packet. """ return self.cmd_packet.pkt_to_string(pkt_bytes, self) def _get_no_zone_code(self): """ Return a zone code corresponding to all non-visible zones.""" zone_codes = [self.zone_map[x] for x in self.zone_map] return ~reduce(lambda x,y: x|y, zone_codes, 0) def _get_zone_codes(self, zone_names): """ Given zone names, return the zone codes they refer to. """ zones = 0 for zone in zone_names: if zone in self.zone_map: zones |= self.zone_map[zone] return zones def _get_reset_code(self, reset_name): """ Given the name of a reset action, return its code. """ for reset in self.reset_types: if reset_name == self.reset_types[reset]: return reset logging.warning("Unknown reset type: {}".format(reset_name)) return 0 def _make_loop_cmds(self, themefile, zones, block, loop_items): """ Given loop-items from the theme file, return a list of loop commands. """ loop_cmds = [] pkt = self.cmd_packet for item in loop_items: item_type = themefile.get_action_type(item) item_colours = themefile.get_action_colours(item) if item_type == AlienFXThemeFile.KW_ACTION_TYPE_FIXED: if len(item_colours) != 1: logging.warning("fixed must have exactly one colour value") continue loop_cmds.append( pkt.make_cmd_set_colour(block, zones, item_colours[0])) elif item_type == AlienFXThemeFile.KW_ACTION_TYPE_BLINK: if len(item_colours) != 1: logging.warning("blink must have exactly one colour value") continue loop_cmds.append( pkt.make_cmd_set_blink_colour(block, zones, item_colours[0])) elif item_type == AlienFXThemeFile.KW_ACTION_TYPE_MORPH: if len(item_colours) != 2: logging.warning("morph must have exactly two colour values") continue loop_cmds.append( pkt.make_cmd_set_morph_colour( block, zones, item_colours[0], item_colours[1])) else: logging.warning("unknown loop item type: {}".format(item_type)) return loop_cmds def _make_zone_cmds(self, themefile, state_name, boot=False): """ Given a theme file, return a list of zone commands. If 'boot' is True, then the colour commands created are not saved with SAVE_NEXT commands. Also, the final command is one to set the colour of all non-visible zones to black. """ zone_cmds = [] block = 1 pkt = self.cmd_packet state = self.state_map[state_name] state_items = themefile.get_state_items(state_name) for item in state_items: zone_codes = self._get_zone_codes(themefile.get_zone_names(item)) loop_items = themefile.get_loop_items(item) loop_cmds = self._make_loop_cmds( themefile, zone_codes, block, loop_items) if (loop_cmds): block += 1 for loop_cmd in loop_cmds: if not boot: zone_cmds.append(pkt.make_cmd_save_next(state)) zone_cmds.append(loop_cmd) if not boot: zone_cmds.append(pkt.make_cmd_save_next(state)) zone_cmds.append(pkt.make_cmd_loop_block_end()) if zone_cmds: if not boot: zone_cmds.append(pkt.make_cmd_save()) if boot: zone_cmds.append( pkt.make_cmd_set_colour( block, self._get_no_zone_code(), (0,0,0))) zone_cmds.append(pkt.make_cmd_loop_block_end()) return zone_cmds def _send_cmds(self, cmds): """ Send the given commands to the controller. """ for cmd in cmds: logging.debug("SENDING: {}".format(self.pkt_to_string(cmd))) self._driver.write_packet(cmd) def set_theme(self, themefile): """ Send the given theme settings to the controller. This should result in the lights changing to the theme settings immediately. """ try: self._driver.acquire() cmds_boot = [] pkt = self.cmd_packet # prepare the controller self._ping() self._reset("all-lights-on") self._wait_controller_ready() for state_name in self.state_map: cmds = [] cmds = self._make_zone_cmds(themefile, state_name) # Boot block commands are saved for sending again later. # The second time, they are sent without SAVE_NEXT commands. if (state_name == self.STATE_BOOT): cmds_boot = self._make_zone_cmds( themefile, state_name, boot=True) self._send_cmds(cmds) cmd = pkt.make_cmd_set_speed(themefile.get_speed()) self._send_cmds([cmd]) # send the boot block commands again self._send_cmds(cmds_boot) cmd = pkt.make_cmd_transmit_execute() self._send_cmds([cmd]) finally: self._driver.release()<|fim▁end|>
if zone_name != "":
<|file_name|>package.py<|end_file_name|><|fim▁begin|><|fim▁hole|>############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # 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) version 2.1, February 1999. # # 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 terms and # conditions of 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class PyBsddb3(PythonPackage): """This module provides a nearly complete wrapping of the Oracle/Sleepycat C API for the Database Environment, Database, Cursor, Log Cursor, Sequence and Transaction objects, and each of these is exposed as a Python type in the bsddb3.db module.""" homepage = "https://pypi.python.org/pypi/bsddb3/6.2.5" url = "https://pypi.io/packages/source/b/bsddb3/bsddb3-6.2.5.tar.gz" version('6.2.5', '610267c189964c905a931990e1ba438c') depends_on('python@2.6:') depends_on('py-setuptools')<|fim▁end|>
<|file_name|>string.py<|end_file_name|><|fim▁begin|>"""A collection of string constants. Public module variables: whitespace -- a string containing all ASCII whitespace ascii_lowercase -- a string containing all ASCII lowercase letters ascii_uppercase -- a string containing all ASCII uppercase letters ascii_letters -- a string containing all ASCII letters digits -- a string containing all ASCII decimal digits hexdigits -- a string containing all ASCII hexadecimal digits octdigits -- a string containing all ASCII octal digits punctuation -- a string containing all ASCII punctuation characters printable -- a string containing all ASCII characters considered printable """ __all__ = ["ascii_letters", "ascii_lowercase", "ascii_uppercase", "capwords", "digits", "hexdigits", "octdigits", "printable", "punctuation", "whitespace", "Formatter", "Template"] import _string # Some strings for ctype-style character classification whitespace = ' \t\n\r\v\f' ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz' ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' ascii_letters = ascii_lowercase + ascii_uppercase digits = '0123456789' hexdigits = digits + 'abcdef' + 'ABCDEF' octdigits = '01234567' punctuation = """!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~""" printable = digits + ascii_letters + punctuation + whitespace # Functions which aren't available as string methods. # Capitalize the words in a string, e.g. " aBc dEf " -> "Abc Def". def capwords(s, sep=None): """capwords(s [,sep]) -> string Split the argument into words using split, capitalize each word using capitalize, and join the capitalized words using join. If the optional second argument sep is absent or None, runs of whitespace characters are replaced by a single space and leading and trailing whitespace are removed, otherwise sep is used to split and join the words. """ return (sep or ' ').join(x.capitalize() for x in s.split(sep)) #################################################################### import re as _re from collections import ChainMap as _ChainMap class _TemplateMetaclass(type): pattern = r""" %(delim)s(?: (?P<escaped>%(delim)s) | # Escape sequence of two delimiters (?P<named>%(id)s) | # delimiter and a Python identifier {(?P<braced>%(id)s)} | # delimiter and a braced identifier (?P<invalid>) # Other ill-formed delimiter exprs ) """ def __init__(cls, name, bases, dct): super(_TemplateMetaclass, cls).__init__(name, bases, dct) if 'pattern' in dct: pattern = cls.pattern else: pattern = _TemplateMetaclass.pattern % { 'delim' : _re.escape(cls.delimiter), 'id' : cls.idpattern, } cls.pattern = _re.compile(pattern, cls.flags | _re.VERBOSE) class Template(metaclass=_TemplateMetaclass): """A string class for supporting $-substitutions.""" delimiter = '$' idpattern = r'[_a-z][_a-z0-9]*' flags = _re.IGNORECASE def __init__(self, template): self.template = template # Search for $$, $identifier, ${identifier}, and any bare $'s def _invalid(self, mo): i = mo.start('invalid') lines = self.template[:i].splitlines(keepends=True) if not lines: colno = 1 lineno = 1 else: colno = i - len(''.join(lines[:-1])) lineno = len(lines) raise ValueError('Invalid placeholder in string: line %d, col %d' % (lineno, colno)) def substitute(*args, **kws): if not args: raise TypeError("descriptor 'substitute' of 'Template' object " "needs an argument") self, *args = args # allow the "self" keyword be passed if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _ChainMap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): # Check the most common path first. named = mo.group('named') or mo.group('braced') if named is not None: val = mapping[named] # We use this idiom instead of str() because the latter will # fail if val is a Unicode containing non-ASCII characters. return '%s' % (val,) if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: self._invalid(mo) raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) def safe_substitute(*args, **kws): if not args: raise TypeError("descriptor 'safe_substitute' of 'Template' object " "needs an argument") self, *args = args # allow the "self" keyword be passed if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _ChainMap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): named = mo.group('named') or mo.group('braced') if named is not None: try: # We use this idiom instead of str() because the latter # will fail if val is a Unicode containing non-ASCII return '%s' % (mapping[named],) except KeyError: return mo.group() if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: return mo.group() raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) ######################################################################## # the Formatter class # see PEP 3101 for details and purpose of this class # The hard parts are reused from the C implementation. They're exposed as "_" # prefixed methods of str. # The overall parser is implemented in _string.formatter_parser. # The field name parser is implemented in _string.formatter_field_name_split class Formatter: def format(*args, **kwargs): if not args: raise TypeError("descriptor 'format' of 'Formatter' object " "needs an argument") self, *args = args # allow the "self" keyword be passed try: format_string, *args = args # allow the "format_string" keyword be passed except ValueError: if 'format_string' in kwargs: format_string = kwargs.pop('format_string') import warnings warnings.warn("Passing 'format_string' as keyword argument is " "deprecated", DeprecationWarning, stacklevel=2) else: raise TypeError("format() missing 1 required positional " "argument: 'format_string'") from None return self.vformat(format_string, args, kwargs) def vformat(self, format_string, args, kwargs): used_args = set() result, _ = self._vformat(format_string, args, kwargs, used_args, 2) self.check_unused_args(used_args, args, kwargs) return result def _vformat(self, format_string, args, kwargs, used_args, recursion_depth, auto_arg_index=0): if recursion_depth < 0: raise ValueError('Max string recursion exceeded') result = [] for literal_text, field_name, format_spec, conversion in \ self.parse(format_string): # output the literal text if literal_text: result.append(literal_text) # if there's a field, output it if field_name is not None: # this is some markup, find the object and do # the formatting # handle arg indexing when empty field_names are given. if field_name == '': if auto_arg_index is False: raise ValueError('cannot switch from manual field ' 'specification to automatic field ' 'numbering') field_name = str(auto_arg_index) auto_arg_index += 1 elif field_name.isdigit(): if auto_arg_index: raise ValueError('cannot switch from manual field ' 'specification to automatic field ' 'numbering') # disable auto arg incrementing, if it gets # used later on, then an exception will be raised auto_arg_index = False # given the field_name, find the object it references # and the argument it came from obj, arg_used = self.get_field(field_name, args, kwargs) used_args.add(arg_used) # do any conversion on the resulting object obj = self.convert_field(obj, conversion) # expand the format spec, if needed format_spec, auto_arg_index = self._vformat( format_spec, args, kwargs, used_args, recursion_depth-1, auto_arg_index=auto_arg_index) # format the object and append to the result result.append(self.format_field(obj, format_spec)) return ''.join(result), auto_arg_index def get_value(self, key, args, kwargs): if isinstance(key, int): return args[key] else: return kwargs[key] def check_unused_args(self, used_args, args, kwargs): pass def format_field(self, value, format_spec): return format(value, format_spec) def convert_field(self, value, conversion): # do any conversion on the resulting object if conversion is None: return value elif conversion == 's': return str(value) elif conversion == 'r': return repr(value) elif conversion == 'a': return ascii(value) raise ValueError("Unknown conversion specifier {0!s}".format(conversion)) # returns an iterable that contains tuples of the form: # (literal_text, field_name, format_spec, conversion) # literal_text can be zero length<|fim▁hole|> # field_name can be None, in which case there's no # object to format and output # if field_name is not None, it is looked up, formatted # with format_spec and conversion and then used def parse(self, format_string): return _string.formatter_parser(format_string) # given a field_name, find the object it references. # field_name: the field being looked up, e.g. "0.name" # or "lookup[3]" # used_args: a set of which args have been used # args, kwargs: as passed in to vformat def get_field(self, field_name, args, kwargs): first, rest = _string.formatter_field_name_split(field_name) obj = self.get_value(first, args, kwargs) # loop through the rest of the field_name, doing # getattr or getitem as needed for is_attr, i in rest: if is_attr: obj = getattr(obj, i) else: obj = obj[i] return obj, first<|fim▁end|>
<|file_name|>ipv6_loopback.rs<|end_file_name|><|fim▁begin|>use ipaddress::IPAddress; use num::bigint::BigUint; use num_traits::One; /// The loopback address is a unicast localhost address. If an /// application in a host sends packets to this address, the IPv6 stack /// will loop these packets back on the same virtual interface. /// /// Loopback addresses are expressed in the following form: /// /// ::1 /// /// or, with their appropriate prefix, /// /// ::1/128 /// /// As for the unspecified addresses, IPv6 loopbacks can be created with /// IPAddress calling their own class: /// /// ip = IPAddress::IPv6::Loopback.new /// /// ip.to_string /// /// "::1/128" /// /// or by using the wrapper: /// /// ip = IPAddress "::1" /// /// ip.to_string /// /// "::1/128" /// /// Checking if an address is loopback is easy with the IPv6/// loopback? /// method: /// /// ip.loopback? /// /// true<|fim▁hole|>/// Creates a new IPv6 unspecified address /// /// ip = IPAddress::IPv6::Loopback.new /// /// ip.to_string /// /// "::1/128" /// #[allow(dead_code)] pub fn new() -> IPAddress { return ::ipv6::from_int(BigUint::one(), 128).unwrap(); }<|fim▁end|>
/// /// The IPv6 loopback address corresponds to 127.0.0.1 in IPv4. /// ///
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>#[cfg(unix)] extern crate libc; #[cfg(unix)] pub mod unix; #[cfg(unix)] pub use unix::*;<|fim▁hole|>#[cfg(windows)] pub mod win; #[cfg(windows)] pub use win::*; #[cfg(not(any(unix, windows)))] pub mod other; #[test] fn getpid_test() { getpid(); }<|fim▁end|>
#[cfg(windows)] extern crate kernel32;
<|file_name|>app.po.ts<|end_file_name|><|fim▁begin|><|fim▁hole|> export class E2ePage { navigateToHome() { return browser.get('/'); } }<|fim▁end|>
import { browser } from 'protractor';
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>""" Shopify Trois --------------- Shopify API for Python 3<|fim▁hole|> from setuptools import setup setup( name='shopify-trois', version='1.1-dev', url='http://masom.github.io/shopify-trois', license='MIT', author='Martin Samson', author_email='pyrolian@gmail.com', maintainer='Martin Samson', maintainer_email='pyrolian@gmail.com', description='Shopify API for Python 3', long_description=__doc__, packages=[ 'shopify_trois', 'shopify_trois.models', 'shopify_trois.engines', 'shopify_trois.engines.http' ], zip_safe=False, include_package_data=True, platforms='any', install_requires=[ 'requests>=1.2.3' ], test_suite='nose.collector', tests_require=[ 'pytest', 'nose', 'mock' ], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ] )<|fim▁end|>
"""
<|file_name|>name.py<|end_file_name|><|fim▁begin|>from bottle import request from sqlalchemy import exc from libraries.database import engine as db from libraries.template import view from libraries.status import Status from libraries.authentication import login_required from libraries.forms import Name as Form from libraries.forms import Blank as BlankForm from libraries.insert import name as name_insert from libraries.select import name as name_select from libraries.delete import name as name_delete<|fim▁hole|>from libraries.csrf import csrf @view('config/profile/name.html') @login_required @csrf def name(): status = Status() form = Form(request.forms) username = open_session()['u'] if request.method == 'POST' and\ request.query['action'] == 'update': if form.validate(): try: conn = db.engine.connect() conn.execute(name_insert, name=form.name.data, username=username) conn.close() status.success = "Updated name" except exc.SQLAlchemyError as message: status.danger = message if request.method == 'POST' and\ request.query['action'] == 'delete': blank_form = BlankForm(request.forms) if blank_form.validate(): try: conn = db.engine.connect() conn.execute(name_delete, username=username) conn.close() status.success = "Deleted name" except exc.SQLAlchemyError as message: status.danger = message conn = db.engine.connect() result = conn.execute(name_select, username=username) conn.close() row = result.fetchone() form.name.data = row['name'] return dict(status=status, form=form)<|fim▁end|>
from libraries.session import open_session
<|file_name|>bin.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import sys from io import BytesIO import argparse from PIL import Image from .api import crop_resize parser = argparse.ArgumentParser( description='crop and resize an image without aspect ratio distortion.') parser.add_argument('image') parser.add_argument('-w', '-W', '--width', metavar='<width>', type=int,<|fim▁hole|>parser.add_argument('-H', '--height', metavar='<height>', type=int, help='desired height of image in pixels') parser.add_argument('-f', '--force', action='store_true', help='whether to scale up for smaller images') parser.add_argument('-d', '--display', action='store_true', default=False, help='display the new image (don\'t write to file)') parser.add_argument('-o', '--output', metavar='<file>', help='Write output to <file> instead of stdout.') def main(): parsed_args = parser.parse_args() image = Image.open(parsed_args.image) size = (parsed_args.width, parsed_args.height) new_image = crop_resize(image, size, parsed_args.force) if parsed_args.display: new_image.show() elif parsed_args.output: new_image.save(parsed_args.output) else: f = BytesIO() new_image.save(f, image.format) try: stdout = sys.stdout.buffer except AttributeError: stdout = sys.stdout stdout.write(f.getvalue())<|fim▁end|>
help='desired width of image in pixels')
<|file_name|>test_rnn.py<|end_file_name|><|fim▁begin|>import torch from torch import autograd, nn batch_size = 1 seq_len = 7 input_size = 6 hidden_size = 4 example = [3, 2, 0, 0, 4, 5, 1, 1] # input = autograd.Variable(torch.rand(seq_len, batch_size, input_size)) # print('input.size()', input.size()) embedding = nn.Embedding(input_size, hidden_size) rnn = torch.nn.RNN( input_size=hidden_size, hidden_size=hidden_size, num_layers=1, nonlinearity='tanh' ) # criterion = torch.nn. # print('rnn', rnn) input = autograd.Variable( torch.LongTensor(example[:-1]).view(seq_len, batch_size) ) target = autograd.Variable( torch.LongTensor(example[1:]).view(seq_len, batch_size) ) print('input', input) parameters = [p for p in rnn.parameters()] + [p for p in embedding.parameters()] optimizer = torch.optim.Adam(parameters) epoch = 0 while True: embedded_input = embedding(input) state = autograd.Variable(torch.zeros(1, batch_size, hidden_size))<|fim▁hole|> out, state = rnn(embedded_input, state) # print('out.size()', out.size()) # print('embedding.weight.transpose(0, 1).size()', embedding.weight.transpose(0, 1).size()) out_unembedded = out.view(-1, hidden_size) @ embedding.weight.transpose(0, 1) _, pred = out_unembedded.max(1) # out_unembedded = out_unembedded.view(seq_len, batch_size, input_size) # print('out_unembedded.size()', out_unembedded.size()) # print('target.size()', target.size()) loss = torch.nn.functional.nll_loss(out_unembedded, target.view(-1)) # print('epoch %s loss %s' % (epoch, loss.data[0])) if epoch % 500 == 0: print('epoch', epoch) print('input', input.data.view(1, -1)) print('target', target.data.view(1, -1)) print('pred', pred.data.view(1, -1)) # print('out', out.data.view(1, -1)) rnn.zero_grad() embedding.zero_grad() loss.backward() optimizer.step() # print('out.size()', out.size()) # print('state.size()', state.size()) epoch += 1<|fim▁end|>
<|file_name|>owl.py<|end_file_name|><|fim▁begin|>class OWL:<|fim▁hole|> pass<|fim▁end|>
def __init__(self):
<|file_name|>lstub.cpp<|end_file_name|><|fim▁begin|>//functions for manipulating the HBC stub by giantpune #include <string.h> #include <ogcsys.h> #include <malloc.h> #include <stdio.h> #include "lstub.h" #include "gecko.h" #include "wad/nandtitle.h" extern const u8 stub_bin[]; extern const u32 stub_bin_size; static char* determineStubTIDLocation() { u32 *stubID = (u32*) 0x80001818; //HBC stub 1.0.6 and lower, and stub.bin if (stubID[0] == 0x480004c1 && stubID[1] == 0x480004f5) return (char *) 0x800024C6; //HBC stub changed @ version 1.0.7. this file was last updated for HBC 1.0.8 else if (stubID[0] == 0x48000859 && stubID[1] == 0x4800088d) return (char *) 0x8000286A; //hexdump( stubID, 0x20 ); return NULL; } s32 Set_Stub(u64 reqID) { if (NandTitles.IndexOf(reqID) < 0) return WII_EINSTALL; char *stub = determineStubTIDLocation(); if (!stub) return -68; stub[0] = TITLE_7( reqID ); stub[1] = TITLE_6( reqID ); stub[8] = TITLE_5( reqID ); stub[9] = TITLE_4( reqID ); stub[4] = TITLE_3( reqID ); stub[5] = TITLE_2( reqID ); stub[12] = TITLE_1( reqID ); stub[13] = ((u8) (reqID)); DCFlushRange(stub, 0x10); <|fim▁hole|> s32 Set_Stub_Split(u32 type, const char* reqID) { const u32 lower = ((u32)reqID[0] << 24) | ((u32)reqID[1] << 16) | ((u32)reqID[2] << 8) | ((u32)reqID[3]); u64 reqID64 = TITLE_ID( type, lower ); return Set_Stub(reqID64); } void loadStub() { char *stubLoc = (char *) 0x80001800; memcpy(stubLoc, stub_bin, stub_bin_size); DCFlushRange(stubLoc, stub_bin_size); } u64 getStubDest() { if (!hbcStubAvailable()) return 0; char ret[8]; u64 retu = 0; char *stub = determineStubTIDLocation(); if (!stub) return 0; ret[0] = stub[0]; ret[1] = stub[1]; ret[2] = stub[8]; ret[3] = stub[9]; ret[4] = stub[4]; ret[5] = stub[5]; ret[6] = stub[12]; ret[7] = stub[13]; memcpy(&retu, ret, 8); return retu; } u8 hbcStubAvailable() { char * sig = (char *) 0x80001804; return (strncmp(sig, "STUBHAXX", 8) == 0); }<|fim▁end|>
return 1; }
<|file_name|>ampyche_setup.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3 import os import cgi import cgitb import json from pprint import pprint import setup.common as co import setup.sqlcommon as sqlc import setup.defaultpaths as dfp import setup.getinput as gi import setup.dbsetup as dbs import setup.gettags as gt import setup.createsongsjson as csj import setup.createalbumsjson as calbj import setup.createartistsjson as cartj import setup.makealphasoup as aS import setup.makesoup as ms class Setup(): def __init__(self): progpath = os.path.dirname(os.path.abspath(__file__)) p = dfp.SetupPaths() jpath = p._get_json_paths(progpath) dbpath = p._get_db_paths(progpath) other = p._get_other_paths(progpath) httpaddr = p._get_http_addr() self.progpath = progpath self.jpath = jpath self.dbpath = dbpath self.other = other self.httpaddr = httpaddr CF = co.CommonFunctions() self.CF = CF SQLC = sqlc.SqlCommon() self.SQLC = SQLC GI = gi.GetInputs() self.GI = GI def _remove_old(self): for (p, d, files) in os.walk(self.jpath['programpath'] + "/json"): for filename in files: fn = os.path.join(p, filename) if fn[:-4] == "json": os.remove(fn) for (p, d, files) in os.walk(self.dbpath['programpath'] + "/db"): for filename in files: fn = os.path.join(p, filename) if os.path.exists(fn): os.remove(fn) # for (p, d, files) in os.walk(self.dbpath['programpath'] + "/music"): # for filename in files: # fn = os.path.join(p, filename) # if os.path.exists(fn): # os.remove(fn) # def _get_input_values(self): inputs = self.GI._get_inputs() return inputs # zelda = {} # zelda['musicpath'] = "/home/charlie/Desktop/music" # zelda['catname'] = "CatalogA" # zelda['hostaddress'] = "http://192.168.1.117/ampyche" # zelda['dbname'] = "dbname" # zelda['dbuname'] = "dbusername" # zelda['dbpword'] = "dbpassword" # return zelda def run_setup(self): self._remove_old() z = self._get_input_values() cclog = self.CF._create_catalog(z, self.dbpath) ampychepath = self.httpaddr + "/" + z['catname'] print("constants setup") AA = dbs.AmpycheDBSetup() run1 = AA.run(z, self.dbpath) print("dbsetup complete") print("getting tags started") AMP = gt.AmpycheGetTags() run2 = AMP.run(self.progpath + "/music", self.dbpath, self.other, self.httpaddr, z['catname'], ampychepath) print("getTags complete") print("start of ID getting") aas = self.SQLC._get_artist_album_song_ids(self.dbpath) songs = aas[0] albums = aas[1] artists = aas[2] print("get IDS complete") CSJ = csj.InitSongsView() songs60 = songs[:50] writesongsjson = CSJ._get_init_songs_info(self.dbpath, self.jpath, songs60) print("CSJ completed") CALBJ = calbj.InitAlbumView() albums40 = albums[:30] writealbumjson = CALBJ._get_init_album_info(self.dbpath, self.jpath, albums40) print("CALBJ completed") CARTJ = cartj.InitArtistView() artists30 = artists[:30] writeartistjson = CARTJ._get_init_artist_info(self.dbpath, self.jpath, artists30) print("CARTJ completed") MAS = aS.MakeAlphaSoup() AlphaSoup = MAS._make_alpha_soup(self.dbpath, self.jpath) MS = ms.MakeSoup() makesoup = MS.run(self.dbpath, self.jpath) <|fim▁hole|> print("Content-Type: application/json\n\n") app = Setup() Ampyche = app.run_setup()<|fim▁end|>
glip = "SETUP COMPLETE" print(json.dumps(glip, sort_keys=True, indent=4))
<|file_name|>assistent_report.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from openerp import models,fields,api import datetime import time class assistent_report1(models.TransientModel): _name = "assistent.report1" def date_debut_mois(): now = datetime.date.today() # Date du jour date_debut_mois = datetime.datetime( now.year, now.month, 1 ) # Premier jour du mois return date_debut_mois.strftime('%Y-%m-%d') # Formatage site= fields.Selection([ ("1", "Gray"), ("4", "ST-Brice"), ], "Site", required=True) version = fields.Selection([ ("1", "1"), ("2", "2"), ("3", "3"), ], "Version du rapport", required=True, default="2") type_rapport= fields.Selection([ ("rapport_mois", "Liste mensuelle"), ("rapport_date_a_date", "Liste de date à date"), ("rapport_a_date", "Liste à date") ], "Modèle de rapport", required=True) date_jour = fields.Date("Date", required=False) date_mois = fields.Date("Date dans le mois", required=False) date_debut = fields.Date("Date de début", required=False) date_fin = fields.Date("Date de fin", required=False) employee = fields.Many2one('hr.employee', 'Employé', required=False, ondelete='set null', help="Sélectionnez un employé") interimaire = fields.Boolean('Intérimaire', help="Cocher pour sélectionner uniquement les intérimaires") saut_page = fields.Boolean('Saut de page', help="Cocher pour avoir un saut de page pour chaque employé") detail = fields.Boolean("Vue détaillée") _defaults = { 'date_jour': time.strftime('%Y-%m-%d'), 'date_mois': date_debut_mois(), 'date_debut': date_debut_mois(), 'date_fin': time.strftime('%Y-%m-%d'), 'type_rapport': 'rapport_mois', } def assistent_report1(self, cr, uid, ids, context=None): report_data = self.browse(cr, uid, ids[0]) report_link = "http://odoo/odoo-rh/rapport"+ str(report_data.version)+".php" url = str(report_link) + '?'+ '&type_rapport=' + str(report_data.type_rapport)+'&site=' + str(report_data.site)+ '&date_jour=' + str(report_data.date_jour)+ '&date_mois=' + str(report_data.date_mois)+'&detail='+str(report_data.detail)+'&employee='+str(report_data.employee.id)+'&interimaire='+str(report_data.interimaire)+'&saut_page='+str(report_data.saut_page)+ '&date_debut=' + str(report_data.date_debut)+ '&date_fin=' + str(report_data.date_fin) return { 'name' : 'Go to website',<|fim▁hole|> 'target' : 'current', 'url' : url }<|fim▁end|>
'res_model': 'ir.actions.act_url', 'type' : 'ir.actions.act_url',
<|file_name|>library.py<|end_file_name|><|fim▁begin|># Copyright 2015-2016 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import git import os import string def latest_commit_sha(repo, path): """That the last commit sha for a given path in repo""" log_message = repo.git.log("-1", path) commit_sha = log_message.split('\n')[0].split(' ')[1] return commit_sha def parse_manifest(manifest, repo, repo_name): # For each release for release_name, release_data in list(manifest['release_names'].items()): print('release_name: ', release_name) # For each os supported at_least_one_tag = False for os_name, os_data in list(release_data['os_names'].items()): print('os_name: ', os_name) # For each os code name supported for os_code_name, os_code_data in list(os_data['os_code_names'].items()): print('os_code_name: ', os_code_name) if os_code_data['tag_names']:<|fim▁hole|> at_least_one_tag = True for tag_name, tag_data in os_code_data['tag_names'].items(): print('tag_name: ', tag_name) tags = [] for alias_pattern in tag_data['aliases']: alias_template = string.Template(alias_pattern) alias = alias_template.substitute( release_name=release_name, os_name=os_name, os_code_name=os_code_name) tags.append(alias) commit_path = os.path.join( repo_name, release_name, os_name, os_code_name, tag_name) commit_sha = latest_commit_sha(repo, commit_path) print('tags: ', tags) tag_data['Tags'] = tags tag_data['Architectures'] = os_code_data['archs'] tag_data['GitCommit'] = commit_sha tag_data['Directory'] = commit_path if not at_least_one_tag: del manifest['release_names'][release_name] return manifest<|fim▁end|>
<|file_name|>api.py<|end_file_name|><|fim▁begin|># Copyright 2016 Mirantis Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import contextlib import json from osprofiler import _utils as utils from osprofiler.drivers.base import get_driver as profiler_get_driver from osprofiler import notifier from osprofiler import profiler from osprofiler import web from horizon.utils import settings as horizon_settings ROOT_HEADER = 'PARENT_VIEW_TRACE_ID' def init_notifier(connection_str, host="localhost"): _notifier = notifier.create( connection_str, project='horizon', service='horizon', host=host) notifier.set(_notifier) @contextlib.contextmanager def traced(request, name, info=None): if info is None: info = {} profiler_instance = profiler.get() if profiler_instance is not None: trace_id = profiler_instance.get_base_id() info['user_id'] = request.user.id with profiler.Trace(name, info=info): yield trace_id else: yield def _get_engine(): connection_str = horizon_settings.get_dict_config( 'OPENSTACK_PROFILER', 'receiver_connection_string') return profiler_get_driver(connection_str) def list_traces(): engine = _get_engine() fields = ['base_id', 'timestamp', 'info.request.path', 'info'] traces = engine.list_traces(fields) return [{'id': trace['base_id'], 'timestamp': trace['timestamp'], 'origin': trace['info']['request']['path']} for trace in traces] def get_trace(trace_id): def rec(_data, level=0): _data['level'] = level _data['is_leaf'] = not _data['children'] _data['visible'] = True _data['childrenVisible'] = True finished = _data['info']['finished'] for child in _data['children']: __, child_finished = rec(child, level + 1) # NOTE(tsufiev): in case of async requests the root request usually # finishes before the dependent requests do so, to we need to # normalize the duration of all requests by the finishing time of # the one which took longest if child_finished > finished: finished = child_finished return _data, finished engine = _get_engine() trace = engine.get_report(trace_id) data, max_finished = rec(trace) data['info']['max_finished'] = max_finished return data def update_trace_headers(keys, **kwargs): trace_headers = web.get_trace_id_headers() trace_info = utils.signed_unpack( trace_headers[web.X_TRACE_INFO], trace_headers[web.X_TRACE_HMAC], keys) trace_info.update(kwargs) p = profiler.get() trace_data = utils.signed_pack(trace_info, p.hmac_key) trace_data = [key.decode() if isinstance(key, bytes) else key for key in trace_data] return json.dumps({web.X_TRACE_INFO: trace_data[0], web.X_TRACE_HMAC: trace_data[1]}) if not horizon_settings.get_dict_config('OPENSTACK_PROFILER', 'enabled'): def trace(function): return function else: def trace(function): func_name = function.__module__ + '.' + function.__name__<|fim▁hole|><|fim▁end|>
decorator = profiler.trace(func_name) return decorator(function)
<|file_name|>p019.py<|end_file_name|><|fim▁begin|># Problem 19: Counting Sundays # https://projecteuler.net/problem=19 def is_leapyear(year): if year%4 == 0 and year%100 != 0 or year%400 == 0: return 1 else: return 0 month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] def days_of_month(m, y): return month[m-1] + (is_leapyear(y) if m == 2 else 0) def days_of_year(y): return sum(month) + is_leapyear(y) <|fim▁hole|># date 1 Jan 1900 represented as (1, 1, 1900) # 1 Jan 1900 was Monday, days is 1 # 7 Jan 1900 was Sunday, days is 7 def date_to_days(date): dy, mn, yr = date days = dy for y in range(1900, yr): days += days_of_year(y) for m in range(1, mn): days += days_of_month(m, yr) return days def is_sunday(days): return days % 7 == 0 def cs(): count = 0 for y in range(1901, 2000+1): for m in range(1, 12+1): days = date_to_days((1, m, y)) if is_sunday(days): count += 1 return count # def test(): return 'No test' def main(): return cs() if __name__ == '__main__': import sys if len(sys.argv) >= 2 and sys.argv[1] == 'test': print(test()) else: print(main())<|fim▁end|>
<|file_name|>authorizations.py<|end_file_name|><|fim▁begin|>from . import resource class AuthorizationsBase(resource.GitHubResource): path = 'authorizations' class Authorization(AuthorizationsBase): pass<|fim▁hole|>class Authorizations(AuthorizationsBase): pass<|fim▁end|>
<|file_name|>order.service.ts<|end_file_name|><|fim▁begin|>/* Importing core module */ import {Injectable} from 'angular2/core'; import {Response} from 'angular2/http'; import {Observable} from 'rxjs/Observable'; import {HttpClient} from './http-client.service';<|fim▁hole|>import {OrderDetailsModel} from '../model/order-details.model'; /* Importing configuration */ import {Configuration} from '../app.constants'; /* Class deocrator */ @Injectable() export class OrderService { private _actionUrl: string; private _isHeadersSet: boolean; constructor (private _config: Configuration, private _httpClient: HttpClient) { this._actionUrl = _config.serverUrl + 'orders/'; this._isHeadersSet = false; } /** * Make the following request to the server: [GET][/orders]: fetch all orders in the database */ getAllOrders() { return this._httpClient.get(this._actionUrl) .map(res => <OrderModel[]> res.json().order) .catch(this.handleError); } /** * Make the following request to the server: [GET][/orders/:id]: fetch all order's details */ getOrderDetails (id) { return this._httpClient.get(this._actionUrl + id) .map(res => <OrderDetailsModel> res.json().order) .catch(this.handleError); } private handleError (error: Response) { // in a real world app, we may send the error to some remote logging infrastructure // instead of just logging it to the console console.error(error); return Observable.throw(error.json().error || 'Server error'); } }<|fim▁end|>
/* Importing model */ import {OrderModel} from '../model/order.model';
<|file_name|>server.js<|end_file_name|><|fim▁begin|>/**<|fim▁hole|> */ var Server = require('annex-ws-node').Server; var http = require('http'); var stack = require('connect-stack'); var pns = require('pack-n-stack'); module.exports = function createServer(opts) { var server = http.createServer(); server.stack = []; server.handle = stack(server.stack); server.use = function(fn) { fn.handle = fn; server.stack.push(fn); return server; }; var routes = server.routes = {}; var hasPushedRouter = false; server.register = server.fn = function(modName, fnName, cb) { var mod = routes[modName] = routes[modName] || {}; var fn = mod[fnName] = mod[fnName] || []; fn.push(cb); server.emit('register:call', modName, fnName); if (hasPushedRouter) return server; server.use(router); hasPushedRouter = true; return server; }; function router(req, res, next) { var mod = routes[req.module]; if (!mod) return next(); var fn = mod[req.method]; if (!fn) return next(); // TODO support next('route') fn[0](req, res, next); } var wss = new Server({server: server, marshal: opts.marshal}); wss.listen(function(req, res) { // TODO do a domain here server.handle(req, res, function(err) { if (!res._sent) { err ? res.error(err.message) : res.error(req.module + ':' + req.method + ' not implemented'); if (err) console.error(err.stack || err.message); } }); }); return server; }<|fim▁end|>
* Module dependencies
<|file_name|>ui.rs<|end_file_name|><|fim▁begin|>//<|fim▁hole|>// This library 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; version // 2.1 of the License. // // This library 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 library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // use clap::{Arg, App}; pub fn build_ui<'a>(app: App<'a, 'a>) -> App<'a, 'a> { app .arg(Arg::with_name("devel") .long("dev") .takes_value(false) .required(false) .multiple(false) .help("Put dev configuration into the generated repo (with debugging enabled)")) .arg(Arg::with_name("nogit") .long("no-git") .takes_value(false) .required(false) .multiple(false) .help("Do not initialize git repository, even if 'git' executable is in $PATH")) .arg(Arg::with_name("path") .long("path") .takes_value(true) .required(false) .multiple(false) .help("Alternative path where to put the repository. Default: ~/.imag")) }<|fim▁end|>
// imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors //
<|file_name|>index.d.ts<|end_file_name|><|fim▁begin|>// Type definitions for chui v3.9.1 // Project: https://github.com/chocolatechipui/chocolatechip-ui // Definitions by: Robert Biggs <http://chocolatechip-ui.com> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // ChocolateChip-UI 3.9.1 /** These TypeScript delcarations for ChocolateChip-UI contain interfaces for both ChocolateChipJS and jQuery. Depending on which library you are using, you will get the type interfaces appropriate for it. */ /** * Interface for ChocolateChipJS. */ interface ChocolateChipStatic { /** * This method will concatenate strings or values as a cleaner alternative to using the '+' operator. * * @param string or number A comma separated series of strings to concatenate. * @return string */ concat(...string: string[]): string; /** * The method will iterate over an array. * * @param obj An iterable object. * @param callback A callback to execute on each loop. * @param args Any arguments you need to pass to the callback. */ forEach(obj: Array<any>, callback: Function, args?: any): any; /** * Alias for cross-platform events: pointerdown, MSPointerDown, touchstart and mousedown. */ eventStart: ChUIEventInterface; /** * Alias for cross-platform events: pointerup, MSPointerUp, touchend and mouseup. */ eventEnd: ChUIEventInterface; /** * Alias for cross-platform events: pointermove, MSPointerMove, touchmove and mousemove. */ eventMove: ChUIEventInterface; /** * Alias for cross-platform events: pointercancel, MSPointerCancel, touchcancel and mouseout. */ eventCancel: ChUIEventInterface; /** * Whether browser is Microsoft Edge or not. */ isIEEdge: boolean; /** * Whether screen is at least 960 pixels wide. */ isWideScreen: boolean; /** * Whether screen is at least 960 pixels wide and in portrait orientation. */ isWideScreenPortrait: boolean; /** * Return the version of the current browser. * * @return number Returns the current browser's version. */ browserVersion(): number; /** * Hide the navigation bar, raising up the content below it. * * @return void */ UIHideNavBar(): void; /** * If the navigation bar is hidden, show it, pushing down the content to make room. * * @return void */ UIShowNavBar(): void; /** * Determine whether navigation is in progress or not. */ isNavigating: boolean; /** * Tell ChocolateChip-UI to not modify window hash during navigation. * The default value is false. */ UIBrowserHashModification: boolean; /** * Method to tell ChocolateChip-UI to register navigation history on Window hash. */ UIEnableBrowserHashModification(): void; /** * Navigate to the article indicated by the provided destination ID. This enters the destination into the navigation history array. * * param destination An id for the article to navigate to. * @return void */ UIGoToArticle(destination: string): void; /** * Go back to the previous article from whence you came. This resets the navigation history array. * * @return void */ UIGoBack(): void; /** * Go back to the article indicated by the provided ID. This is for non-linear back navigation. This will reset the navigation history array to match the current state. */ UIGoBackToArticle(articleID: string): void; /** * Display a transparent screen over the UI. * * @param opacity The percentage of opacity for the screen. * @return void */ UIBlock(opacity?: number): void; /** * Remove the transparent screen covering the UI. * * @return void */ UIUnblock(): void; /** * Create and show a Popup with title and message. Possible options: {id: "#myPopup", title: "My Popup", * message: "Woohoo!", cancelButton: "Forget It!", contiueButton: "Whatever", callback: function() {console.log('Blah!');}, empty: false }. * * param options UIPopupOptions */ UIPopup(options?: { id?: string; title?: string; message?: string; cancelButton?: string; continueButton?: string; callback?: Function; empty?: boolean; }): void; /** * Create and show a Popover. Options: {id: "#myPopover", title: "Whatever", callback: function() {console.log('Blah!');}}. * * param options UIPopoverOptions * @return void */ UIPopover(options?: { id?: string; callback?: Function; title?: string; }): void; /** * Close any currently visible popovers. * * @return void */ UIPopoverClose(): void; /** * Create a segmented control: {id: "mySegments", className: "seggie", labels: ["one", "two","three"], selected: 1} * * param: options UICreateSegmentedOptions */ UICreateSegmented(options?: { id?: string; className?: string; labels?: string[]; selected?: number }): ChocolateChipElementArray; /** * Initialize a horiontal or vertical paging control. This uses a segmented control in the navigation bar with a class * like "segmented paging horizontal" or "segmented paging vertical". It uses a single article with multiple sections to paginate. *<|fim▁hole|> UIPaging(): void; /** * Creates a sheet. Minimum option is an id: {id : 'starTrek', listClass :'enterprise', background: 'transparent', handle: false } * * @return void */ UISheet(options: { id: string; listClass?: string; background?: string; handle?: boolean; }): void; /** * Show a sheet by passing this its ID. * * @return void */ UIShowSheet(id: string): void; /** * Hide any currently displayed sheets. * * @return void */ UIHideSheet(): void; /** * The body tag wrapped and ready to use: $.body.css('background-color','orange') */ body: ChocolateChipElementArray; /** * An array of the navigation history. Do not manipulate this. For examination only. This is used by navigation lists, etc. */ UINavigationHistory: string[]; /** * Creates and initializes a slide out menu. Possible options: {dynamic: true, callback: function() { alert("Woohoo!");}} */ UISlideout: { /** * Creates and initializes a slide out menu. Possible options: {dynamic: true, callback: function() { alert("Woohoo!");}} * * @return void */ (options?: { dynamic?: boolean; callback?: (args?: any) => any; }): any; /** * Populates a slideout menu. * * @return void */ populate(array: Object[]): void; }; /** * Reset the value of the stepper to its defaults at initialization. Pass it a reference to the stepper to reset. * * @return void */ UIResetStepper(stepper: HTMLElement[]): void; /** * Create a switch control. Possible options: { id: '#myId', name: 'fruit.mango', state: 'on', value: 'Mango', checked: 'on', style: 'traditional', callback: function() { alert('hi');}} * * @return void */ UICreateSwitch(options?: { id?: string; name?: string; state?: string; value?: string | number; checked?: string; style?: string; callback?: () => any; }): void; /** * Creates a tabbar. On iOS this is at the bottom of the screen. On Android and Windows, it is at the top. * Options: {id: 'mySpecialTabbar', tabs: 4, labels: ["Refresh", "Add", "Info", "Downloads", "Favorite"], icons: ["refresh", "add", "info", "downloads", "favorite"], selected: 2 } * * @return void */ UITabbar(options?: { id?: string; tabs: number; labels: string[]; icons?: string[]; selected?: number; }): void; /** * Create a search bar for an article. Options: { articleId: '#products', id: 'productSearch', placeholder: 'Find a product', results: 5 } * * @return void */ UISearch(options?: { articleId?: any; id?: string; placeholder?: string; results?: number; }): void; /** * Create and initialize a swipable carousel. Options: {target : '#myCarousel', panels: ['<p>stuff</p>','<p>more</p>'], loop: true, pagination: true } * * @return void */ UISetupCarousel(options: { target: any; panels: ChocolateChipElementArray; loop?: boolean; pagination?: boolean; }): void; /** * Bind the values of data-models to elements with data-controllers: <input id='myText' data-controller='input-value' type='text'></li><h3 data-model='input-value'></h3>. * You can bind a single model to its controller by providing its name as the argument: $.UIBindData('input-value'); * * @param controller A string indicating the controller whose value a model is bound to. * @return void */ UIBindData(controller?: string): void; /** * Unbind the values of data-models from their data-controllers. * If you provide a controller name as the argument, only that controller will be unbound. * * @param controller A controller to unbind. * @return void */ UIUnBindData(controller?: string): void; } /** * Interface for ChocolateChipJS HTMLElement Array. */ interface ChocolateChipElementArray { /** * Iterate over an Array object, executing a function for each matched element. * * @return void */ forEach(func: (ctx: any, idx: number) => void): void; /** * Check the current matched set of elements against a selector or element and return it * if it matches the given arguments. * * @param selector A string containing a selector expression to match elements against. * @return HTMLElement[] */ iz(selector: string): ChocolateChipElementArray; /** * Check the current matched set of elements against a selector or element and return it * if it matches the given arguments. * * @param elements One or more elements to match the current set of elements against. * @return HTMLElement[] */ iz(element: any): ChocolateChipElementArray; /** * Check the current matched set of elements against a selector or element and return it * if it does not match the given arguments. * * @param selector A string containing a selector expression to match elements against. * @return HTMLElement[] */ iznt(selector: string): ChocolateChipElementArray; /** * Check the current matched set of elements against a selector or element and return it * if it does not match the given arguments. * * @param elements One or more elements to match the current set of elements against. * @return HTMLElement[] */ iznt(element: any): ChocolateChipElementArray; /** * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. * * @param selector A string containing a selector expression to match elements against. * @return HTMLElement[] */ haz(selector: string): ChocolateChipElementArray; /** * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. * * @param contained A DOM element to match elements against. * @return HTMLElement[] */ haz(contained: HTMLElement): ChocolateChipElementArray; /** * Reduce the set of matched elements to those that have a descendant that does not match the selector or DOM element. * * @param selector A string containing a selector expression to match elements against. * @return HTMLElement[] */ haznt(selector: string): ChocolateChipElementArray; /** * Reduce the set of matched elements to those that have a descendant that does not match the selector or DOM element. * * @param contained A DOM element to match elements against. * @return HTMLElement[] */ haznt(contained: HTMLElement): ChocolateChipElementArray; /** * Return any of the matched elements that have the given class. * * @param className The class name to search for. * @return HTMLElement[] */ hazClass(className: string): ChocolateChipElementArray; /** * Return any of the matched elements that do not have the given class. * * @param className The class name to search for. * @return HTMLElement[] */ hazntClass(className: string): ChocolateChipElementArray; /** * Return any of the matched elements that have the given attribute. * * @param className The class name to search for. * @return HTMLElement[] */ hazAttr(attributeName: string): ChocolateChipElementArray; /** * Return any of the matched elements that do not have the given attribute. * * @param className The class name to search for. * @return HTMLElement[] */ hazntAttr(attributeName: string): ChocolateChipElementArray; /** * Attach a handler to an event for the elements. * * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. * @param handler A function to execute each time the event is triggered. * @param useCapture Setting the third argument to true will trigger event bubbling. The default is false. * @return ChocolateChipStatic */ bind(eventType: string | ChUIEventInterface, handler: (eventObject: Event) => any, useCapture?: boolean): ChocolateChipStatic; /** * Remove a handler for an event from the elements. * * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. * @param handler A function to execute each time the event is triggered. * @param useCapture Setting the third argument to true will trigger event bubbling. The default is false. * @return ChocolateChipStatic */ unbind(eventType: string | ChUIEventInterface, handler: (eventObject: Event) => any, useCapture?: boolean): ChocolateChipStatic; /** * Add a delegated event to listen for the provided event on the descendant elements. * * @param selector A string defining the descendant elements to listen on for the designated event. * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. * @param handler A function to execute each time the event is triggered. The keyword "this" will refer * to the element receiving the event. * @param useCapture Setting the third argument to true will trigger event bubbling. The default is false. * @return ChocolateChipStatic */ delegate(selector: any, eventType: string | ChUIEventInterface, handler: (eventObject: Event) => any, useCapture?: boolean): ChocolateChipStatic; /** * Add a delegated event to listen for the provided event on the descendant elements. * * @param selector A string defining the descendant elements are listening for the event. * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. * @param handler A function handler assigned to this event. * @param useCapture Setting the third argument to true will trigger event bubbling. The default is false. * @return ChocolateChipStatic */ undelegate(selector: any, eventType: string | ChUIEventInterface, handler: (eventObject: Event) => any, useCapture?: boolean): ChocolateChipStatic; /** * Add a handler to an event for elements. If a selector is provided as the second argument, this implements a delegated event. * * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. * @param selector A string defining the descendant elements are listening for the event. * @param handler A function handler assigned to this event. * @param useCapture Setting the third argument to true will trigger event bubbling. The default is false. * @return ChocolateChipStatic */ on( eventType: string | ChUIEventInterface, selector: any, handler?: (eventObject: Event) => any, capturePhase?: boolean): ChocolateChipStatic; /** * Remove a handler for an event from the elements. If the second argument is a selector, it tries to undelegate the event. * If no arugments are provided, it removes all events from the element(s). * * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. * @param selector A string defining the descendant elements are listening for the event. * @param handler A function handler assigned to this event. * @param useCapture Setting the third argument to true will trigger event bubbling. The default is false. * @return ChocolateChipStatic */ off( eventType?: string | ChUIEventInterface, selector?: any, handler?: (eventObject: Event) => any, capturePhase?: boolean): ChocolateChipStatic; /** * */ trigger(eventType: string | ChUIEventInterface): void; /** * Center an element to the screen. */ UICenter(): void; /** * Display a busy indicator. Posible options: {size: "100px", color: "#ff0000", position: "align-flush", duration: "2s"}. * * @param size The size as a string with length identifier: "40px". * @param color The color for the busy indicator: "#ff0000". * @param position Optional positioning, such as "align-flush". * @param duration The time for the busy indicator to display: "500ms". * @return void */ UIBusy(options?: { size?: string; color?: string; position?: string | boolean; duration?: string; }): void; /** * Close the currently displayed Popup. This is executed on the popup: $('#myPopup').UIPopupClose(). * * @return void */ UIPopupClose(): void; /** * Initialize a segmented control. Options: {selected: 2, callback: function() {console.log('Blah');}} * * @return void */ UISegmented(options?: { selected?: number; callback?: Function; }): void; /** * This method allows the user to use a segmented control to toggle a set of panels. It is executed on the segmented control. * The options id is the contain of the panels. The options callback is to execute when the user toggles a panel. * * @return void */ UIPanelToggle(panelsContainer: string, callback: () => any): void; /** * Make a list editable. This can be enabling changing the order of list items, or deleting them, or both. Options: {editLabel: "Edit", doneLabel: "Done", * deleteLabel: "Delete", callback: function() {alert('Bye bye!');}, deletable: true, movable: true}. * * @return void */ UIEditList(options?: { editLabel?: string; doneLabel?: string; deleteLabel?: string; callback?: Function; deletable?: boolean; movable?: boolean; }): void; /** * Convert a simple list into a selection list. This converts the list into a radio button group, meaning only one can be selected at any time. * You can name the radios buttons using the options name. Options: {name: "selectedNamesGroup", selected: 2, callback: function() {alert('hi');}} * * @return void */ UISelectList(options?: { name?: string; selected?: number; callback?: Function; }): void; /** * Create a stepper control by executing it on a span with the class "stepper". Possible options: {start: 0, end: 10, defaultValue: 3}. * * @return void */ UIStepper(options: { start: number; end: number; defaultValue: number; }): void; /** * Initialize any existing switch controls: $('.switch').UISwitch(); * * @return void */ UISwitch(): void; /** * Execute this on a range control to initialize it. * * @return void */ UIRange(): void; } /** * Interface for jQuery */ interface JQueryStatic { /** * This method will concatenate strings or values as a cleaner alternative to using the '+' operator. * * @param string or number A comma separated series of strings to concatenate. * @return string */ concat(...string: string[]): string; /** * The method will iterate over an array. * * @param obj An iterable object. * @param callback A callback to execute on each loop. * @param args Any arguments you need to pass to the callback. */ forEach(obj: Array<any>, callback: Function, args?: any): any; /** * Alias for cross-platform events: pointerdown, MSPointerDown, touchstart and mousedown. */ eventStart: ChUIEventInterface; /** * Alias for cross-platform events: pointerup, MSPointerUp, touchend and mouseup. */ eventEnd: ChUIEventInterface; /** * Alias for cross-platform events: pointermove, MSPointerMove, touchmove and mousemove. */ eventMove: ChUIEventInterface; /** * Alias for cross-platform events: pointercancel, MSPointerCancel, touchcancel and mouseout. */ eventCancel: ChUIEventInterface; /** * Whether device is iPhone. */ isiPhone: boolean; /** * Whether device is iPad. */ isiPad: boolean; /** * Whether device is iPod. */ isiPod: boolean; /** * Whether OS is iOS. */ isiOS: boolean; /** * Whether OS is Android */ isAndroid: boolean; /** * Whether OS is WebOS. */ isWebOS: boolean; /** * Whether OS is Blackberry. */ isBlackberry: boolean; /** * Whether OS supports touch events. */ isTouchEnabled: boolean; /** * Whether there is a network connection. */ isOnline: boolean; /** * Whether app is running in stanalone mode. */ isStandalone: boolean; /** * Whether OS is iOS 6. */ isiOS6: boolean; /** * Whether OS i iOS 7. */ isiOS7: boolean; /** * Whether OS is Windows. */ isWin: boolean; /** * Whether device is Windows Phone. */ isWinPhone: boolean; /** * Whether browser is IE10. */ isIE10: boolean; /** * Whether browser is IE11. */ isIE11: boolean; /** * Whether browser is Microsoft Edge or not. */ isIEEdge: boolean; /** * Whether browser is Webkit based. */ isWebkit: boolean; /** * Whether browser is running on mobile device. */ isMobile: boolean; /** * Whether browser is running on desktop. */ isDesktop: boolean; /** * Whether browser is Safari. */ isSafari: boolean; /** * Whether browser is Chrome. */ isChrome: boolean; /** * Is native Android browser (not mobile Chrome). */ isNativeAndroid: boolean; /** * Whether screen is at least 960 pixels wide. */ isWideScreen: boolean; /** * Whether screen is at least 960 pixels wide and in portrait orientation. */ isWideScreenPortrait: boolean; /** * Return the version of the current browser. */ browserVersion(): number; /** * Hide the navigation bar, raising up the content below it. */ UIHideNavBar(): void; /** * If the navigation bar is hidden, show it, pushing down the content to make room. */ UIShowNavBar(): void; /** * Determine whether navigation is in progress or not. */ isNavigating: boolean; /** * Tell ChocolateChip-UI to not modify window hash during navigation. * The default value is false. */ UIBrowserHashModification: boolean; /** * Method to tell ChocolateChip-UI to register navigation history on Window hash. */ UIEnableBrowserHashModification(): void; /** * Navigate to the article indicated by the provided destination ID. This enters the destination into the navigation history array. * * @param destination An id for the article to navigate to. * @return void */ UIGoToArticle(destination: string): void; /** * Go back to the previous article from whence you came. This resets the navigation history array. * * @return void */ UIGoBack(): void; /** * Go back to the article indicated by the provided ID. This is for non-linear back navigation. This will reset the navigation history array to match the current state. * * @return void */ UIGoBackToArticle(articleID: string): void; /** * Display a transparent screen over the UI. * * @param opacity The percentage of opacity for the screen. * @return void */ UIBlock(opacity?: number): void; /** * Remove the transparent screen covering the UI. * * @return void */ UIUnblock(): void; /** * Create and show a Popup with title and message. Possible options: {id: "#myPopup", title: "My Popup", * message: "Woohoo!", cancelButton: "Forget It!", contiueButton: "Whatever", callback: function() {console.log('Blah!');}, empty: false }. * * @param options UIPopupOptions * @return void */ UIPopup(options?: { id?: string; title?: string; message?: string; cancelButton?: string; continueButton?: string; callback?: Function; empty?: boolean; }): void; /** * Create and show a Popover. Options: {id: "#myPopover", title: "Whatever", callback: function() {console.log('Blah!');}}. * * @param options UIPopoverOptions * @return void */ UIPopover(options?: { id?: string; callback?: Function; title?: string; }): void; /** * Close any currently visible popovers. * * @return void */ UIPopoverClose(): void; /** * Create a segmented control: {id: "mySegments", className: "seggie", labels: ["one", "two","three"], selected: 1} * * @param: options UICreateSegmentedOptions * @return JQuery */ UICreateSegmented(options: { id?: string; className?: string; labels?: string[]; selected?: number }): JQuery; /** * Initialize a horiontal or vertical paging control. This uses a segmented control in the navigation bar with a class * like "segmented paging horizontal" or "segmented paging vertical". It uses a single article with multiple sections to paginate. * * @return void */ UIPaging(): void; /** * Creates a sheet. Minimum option is an id: {id : 'starTrek', listClass :'enterprise', background: 'transparent', handle: false } * * @return void */ UISheet(options: { id: string; listClass?: string; background?: string; handle?: boolean; }): void; /** * Show a sheet by passing this its ID. * * @return void */ UIShowSheet(id: string): void; /** * Hide any currently displayed sheets. * * @return void */ UIHideSheet(): void; /** * The body tag wrapped and ready to use: $.body.css('background-color','orange') */ body: JQuery; /** * An array of the navigation history. Do not manipulate this. For examination only. This is used by navigation lists, etc. */ UINavigationHistory: string[]; /** * Creates and initializes a slide out menu. Possible options: {dynamic: true, callback: function() { alert("Woohoo!");}} */ UISlideout: { /** * Creates and initializes a slide out menu. Possible options: {dynamic: true, callback: function() { alert("Woohoo!");}} * * @return void */ (options?: { dynamic?: boolean; callback?: (args?: any) => any; }): any; /** * Populates a slideout menu. * * @return void */ populate(array: Object[]): void; }; /** * Reset the value of the stepper to its defaults at initialization. Pass it a reference to the stepper to reset. * * @return void */ UIResetStepper(stepper: JQuery): void; /** * Create a switch control. Possible options: { id: '#myId', name: 'fruit.mango', state: 'on', value: 'Mango', checked: 'on', style: 'traditional', callback: function() { alert('hi');}} * * @return void */ UICreateSwitch(options?: { id?: string; name?: string; state?: string; value?: string | number; checked?: string; style?: string; callback?: () => any; }): void; /** * Creates a tabbar. On iOS this is at the bottom of the screen. On Android and Windows, it is at the top. * Options: {id: 'mySpecialTabbar', tabs: 4, labels: ["Refresh", "Add", "Info", "Downloads", "Favorite"], icons: ["refresh", "add", "info", "downloads", "favorite"], selected: 2 } * * @return void */ UITabbar(options?: { id?: string; tabs: number; labels: string[]; icons?: string[]; selected?: number; }): void; /** * Create a search bar for an article. Options: { articleId: '#products', id: 'productSearch', placeholder: 'Find a product', results: 5 } * * @return void */ UISearch(options?: { articleId?: any; id?: string; placeholder?: string; results?: number; }): void; /** * Create and initialize a swipable carousel. Options: {target : '#myCarousel', panels: ['<p>stuff</p>','<p>more</p>'], loop: true, pagination: true } * * @return void */ UISetupCarousel(options: { target: any; panels: JQuery; loop?: boolean; pagination?: boolean; }): void; /** * Bind the values of data-models to elements with data-controllers: <input id='myText' data-controller='input-value' type='text'></li><h3 data-model='input-value'></h3>. * You can bind a single model to its controller by providing its name as the argument: $.UIBindData('input-value'); * * @param controller A string indicating the controller whose value a model is bound to. * @return void */ UIBindData(controller?: string): void; /** * Unbind the values of data-models from their data-controllers. * If you provide a controller name as the argument, only that controller will be unbound. * * @param controller A controller to unbind. * @return void */ UIUnBindData(controller?: string): void; /** * Object used to store string templates and parsed templates. * * @param string A string defining the template. * @param string A label used to access an object's properties in the template. If none is provided it defaults to "data": [[= data.name]]. * @return void */ templates: Object; /** * This method returns a parsed template. * */ template: { /** * This method parses a string and an optoinal variable name and returns a parsed template in the form of a function. You can then pass this function data to get rendered nodes. * * @param template A string of markup to use as a template. * @param variable An option name to use in the template. If it were "myData": [[= myData.name]]. Otherwise it defaults to "data": [[= data.name]]. * @return A function. */ (template: string, variable?: string): Function; /** * A method to repeated output a template. * * @param element The target container into which the content will be inserted. * @param template A string of markup. * @param data The iterable data the template will consume. * @return void. */ repeater: (element: JQuery, template: string, data: any) => void; /** * A object that holds the reference to the controller for a repeater. * This is used to cache the data that a repeater uses. After the repeater is rendered, the reference is deleted from this object. * */ data: { repeaterName?: any; }; /** * Use this value to output an index value in a template repeater. */ index: number; }; } /** * Interface for jQuery */ interface JQuery { /** * Iterate over an Array object, executing a function for each matched element. * * @param callback A function to execute while looping over an interable. This takes to arguments: ctx: HTMLElement and idx: number. * @return JQuery */ forEach(callback: (ctx: HTMLElement, idx: number) => any): JQuery; /** * Check the current matched set of elements against a selector or element and return it * if it matches the given arguments. * * @param selector A string containing a selector expression to match elements against. * @return JQuery */ iz(selector: string): JQuery; /** * Check the current matched set of elements against a selector or element and return it * if it matches the given arguments. * * @param elements One or more elements to match the current set of elements against. * @return JQuery */ iz(element: any): JQuery; /** * Check the current matched set of elements against a selector or element and return it * if it does not match the given arguments. * * @param selector A string containing a selector expression to match elements against. * @return JQuery */ iznt(selector: string): JQuery; /** * Check the current matched set of elements against a selector or element and return it * if it does not match the given arguments. * * @param elements One or more elements to match the current set of elements against. * @return JQuery */ iznt(element: any): JQuery; /** * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. * * @param selector A string containing a selector expression to match elements against. * @return JQuery */ haz(selector: string): JQuery; /** * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. * * @param contained A DOM element to match elements against. * @return JQuery */ haz(contained: HTMLElement): JQuery; /** * Reduce the set of matched elements to those that have a descendant that does not match the selector or DOM element. * * @param selector A string containing a selector expression to match elements against. * @return JQuery */ haznt(selector: string): JQuery; /** * Reduce the set of matched elements to those that have a descendant that does not match the selector or DOM element. * * @param contained A DOM element to match elements against. * @return JQuery */ haznt(contained: HTMLElement): JQuery; /** * Return any of the matched elements that have the given class. * * @param className The class name to search for. * @return JQuery */ hazClass(className: string): JQuery; /** * Return any of the matched elements that do not have the given class. * * @param className The class name to search for. * @return JQuery */ hazntClass(className: string): JQuery; /** * Return any of the matched elements that have the given attribute. * * @param className The class name to search for. * @return JQuery */ hazAttr(attributeName: string): JQuery; /** * Return any of the matched elements that do not have the given attribute. * * @param className The class name to search for. * @return JQuery */ hazntAttr(attributeName: string): JQuery; /** * Center an element to the screen. * * @return void */ UICenter(): void; /** * Display a busy indicator. Posible options: {size: "100px", color: "#ff0000", position: "align-flush", duration: "2s"}. * * @param size The size as a string with length identifier: "40px". * @param color The color for the busy indicator: "#ff0000". * @param position Optional positioning, such as "align-flush". * @param duration The time for the busy indicator to display: "500ms". * @return void */ UIBusy(options?: { size?: string; color?: string; position?: string | boolean; duration?: string; }): void; /** * Close the currently displayed Popup. This is executed on the popup: $('#myPopup').UIPopupClose(). * * @return void */ UIPopupClose(): void; /** * Initialize a segmented control. Options: {selected: 2, callback: function() {console.log('Blah');}} * * @return void */ UISegmented(options?: { selected?: number; callback?: Function; }): void; /** * This method allows the user to use a segmented control to toggle a set of panels. It is executed on the segmented control. * The options id is the contain of the panels. The options callback is to execute when the user toggles a panel. * * @return void */ UIPanelToggle(panelsContainer: string, callback: () => any): void; /** * Make a list editable. This can be enabling changing the order of list items, or deleting them, or both. Options: {editLabel: "Edit", doneLabel: "Done", * deleteLabel: "Delete", callback: function() {alert('Bye bye!');}, deletable: true, movable: true}. * * @return void */ UIEditList(options?: { editLabel?: string; doneLabel?: string; deleteLabel?: string; callback?: Function; deletable?: boolean; movable?: boolean; }): void; /** * Convert a simple list into a selection list. This converts the list into a radio button group, meaning only one can be selected at any time. * You can name the radios buttons using the options name. Options: {name: "selectedNamesGroup", selected: 2, callback: function() {alert('hi');}} * * @return void */ UISelectList(options?: { name?: string; selected?: number; callback?: Function; }): void; /** * Create a stepper control by executing it on a span with the class "stepper". Possible options: {start: 0, end: 10, defaultValue: 3}. * * @return void */ UIStepper(options: { start: number; end: number; defaultValue: number; }): void; /** * Initialize any existing switch controls: $('.switch').UISwitch(); * * @return void */ UISwitch(): void; /** * Execute this on a range control to initialize it. * * @return void */ UIRange(): void; /** * Attach a handler to an event for the elements. * * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. */ bind(eventType: string | ChUIEventInterface, eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Attach a handler to an event for the elements. * * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. * @param handler A function to execute each time the event is triggered. * @return JQuery */ bind(eventType: string | ChUIEventInterface, handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Attach a handler to an event for the elements. * * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. * @param eventData An object containing data that will be passed to the event handler. * @param preventBubble Setting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling. The default is true. * @return JQuery */ bind(eventType: string | ChUIEventInterface, eventData: any, preventBubble: boolean): JQuery; /** * Attach a handler to an event for the elements. * * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. * @param preventBubble Setting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling. The default is true. * @return JQuery */ bind(eventType: string | ChUIEventInterface, preventBubble: boolean): JQuery; delegate(selector: any, eventType: string | ChUIEventInterface, handler: (eventObject: JQueryEventObject) => any): JQuery; delegate(selector: any, eventType: string | ChUIEventInterface, eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Remove an event handler. * * @param events One or more space-separated event types and optional namespaces, or just namespaces, such as "click", "keydown.myPlugin", or ".myPlugin". * @param selector A selector which should match the one originally passed to .on() when attaching event handlers. * @param handler A handler function previously attached for the event(s), or the special value false. * @return JQuery */ off(events: string | ChUIEventInterface, selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; /** * Remove an event handler. * * @param events One or more space-separated event types and optional namespaces, or just namespaces, such as "click", "keydown.myPlugin", or ".myPlugin". * @param handler A handler function previously attached for the event(s), or the special value false. * @return JQuery */ off(events: string | ChUIEventInterface, handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Attach an event handler function for one or more events to the selected elements. * * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). * @return JQuery */ on(events: string | ChUIEventInterface, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; /** * Attach an event handler function for one or more events to the selected elements. * * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". * @param data Data to be passed to the handler in event.data when an event is triggered. * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. * @return JQuery */ on(events: string | ChUIEventInterface, data : any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; /** * Attach an event handler function for one or more events to the selected elements. * * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. * @return JQuery */ on(events: string | ChUIEventInterface, selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; /** * Attach an event handler function for one or more events to the selected elements. * * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. * @param data Data to be passed to the handler in event.data when an event is triggered. * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. * @return JQuery */ on(events: string | ChUIEventInterface, selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * * @param events A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names. * @param handler A function to execute at the time the event is triggered. * @return JQuery */ one(events: string | ChUIEventInterface, handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * * @param events A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names. * @param data An object containing data that will be passed to the event handler. * @param handler A function to execute at the time the event is triggered. * @return JQuery */ one(events: string | ChUIEventInterface, data: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. * @return JQuery */ one(events: string | ChUIEventInterface, selector: string, handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. * @param data Data to be passed to the handler in event.data when an event is triggered. * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. * @return JQuery */ one(events: string | ChUIEventInterface, selector: string, data: any, handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Execute all handlers and behaviors attached to the matched elements for the given event type. * * @param eventType A string containing a JavaScript event type, such as click or submit. * @param extraParameters Additional parameters to pass along to the event handler. * @return JQuery */ trigger(eventType: string | ChUIEventInterface, extraParameters?: any[]|Object): JQuery; /** * Execute all handlers attached to an element for an event. * * @param eventType A string containing a JavaScript event type, such as click or submit. * @param extraParameters An array of additional parameters to pass along to the event handler. * @return Object */ triggerHandler(eventType: string | ChUIEventInterface, ...extraParameters: any[]): Object; /** * Remove a previously-attached event handler from the elements. * * @param eventType A string containing a JavaScript event type, such as click or submit. * @param handler The function that is to be no longer executed. * @return JQuery */ unbind(eventType?: string | ChUIEventInterface, handler?: (eventObject: JQueryEventObject) => any): JQuery; /** * Remove a previously-attached event handler from the elements. * * @param eventType A string containing a JavaScript event type, such as click or submit. * @param fls Unbinds the corresponding 'return false' function that was bound using .bind( eventType, false ). * @return JQuery */ unbind(eventType: string | ChUIEventInterface, fls: boolean): JQuery; /** * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. * * @param selector A selector which will be used to filter the event results. * @param eventType A string containing a JavaScript event type, such as "click" or "keydown" * @param handler A function to execute at the time the event is triggered. * @return JQuery */ undelegate(selector: string | ChUIEventInterface, eventType: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; /** * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. * * @param selector A selector which will be used to filter the event results. * @param events An object of one or more event types and previously bound functions to unbind from them. * @return JQuery */ undelegate(selector: string | ChUIEventInterface, events: Object): JQuery; } interface ChUIEventInterface { eventStart: string; eventEnd: string; eventMove: string; eventCancel: string; tap: string; singletap: string; doubletap: string; longtap: string; swipe: string; swipeleft: string; swiperight: string; swipeup: string; swipedown: string; } /** * The interface used to construct jQuery events (with $.Event). It is * defined separately instead of inline in JQueryStatic to allow * overriding the construction function with specific strings * returning specific event objects. */ interface JQueryEventConstructor { (name: string, eventProperties?: any): JQueryEventObject; new (name: string, eventProperties?: any): JQueryEventObject; } interface JQueryEventInterface { Event: JQueryEventConstructor; } /** * Interface of the JQuery extension of the W3C event object */ interface BaseJQueryEventObject extends Event { } interface JQueryEventObject extends BaseJQueryEventObject, JQueryInputEventObject, JQueryMouseEventObject, JQueryKeyEventObject { } /** * Interface of the JQuery extension of the W3C event object */ interface BaseJQueryEventObject extends Event { } interface JQueryInputEventObject extends BaseJQueryEventObject { } interface JQueryMouseEventObject extends JQueryInputEventObject { } interface JQueryKeyEventObject extends JQueryInputEventObject { } interface JQueryEventObject extends BaseJQueryEventObject, JQueryInputEventObject, JQueryMouseEventObject, JQueryKeyEventObject { }<|fim▁end|>
* @return void */
<|file_name|>build.rs<|end_file_name|><|fim▁begin|>extern crate ffigen; extern crate msbuild_util; use std::process::Command; use std::fs; use std::env; fn main() { let mut context = ffigen::Context::new(); context.set_root("../scaffold".to_string()); context.add_lang(ffigen::Lang::CSharp, &[ffigen::Config::Output(".".to_string())]); ffigen::gen(&context); //Build C# parts let config = match env::var("PROFILE").unwrap_or_else(|e| panic!("Count not get confing from env {}", e)).as_ref() { "debug" => "debug", "release" => "release", cfg => panic!("Unknown config {}", cfg) }; <|fim▁hole|> //Run cargo let mut cargo = Command::new("cargo"); cargo.current_dir("../scaffold") .arg("build"); if config == "release" { cargo.arg("--release"); } let cargo_result = cargo.output() .unwrap_or_else(|e| panic!("Unable to run cargo {}", e)); if !cargo_result.status.success() { panic!("Unable to run cargo {} {}", String::from_utf8_lossy(&cargo_result.stderr), String::from_utf8_lossy(&cargo_result.stdout)); } let target = format!("../scaffold/target/{}/{}", config, get_output_lib(&"ffi_test_scaffold")); let dest = format!("bin/x64/{}/{}", capatalize(&config.to_string()), get_output_lib(&"ffi_test_scaffold")); fs::copy(&target, &dest) .unwrap_or_else(|e| panic!("Unable to copy file from {} to {}, {}", target, dest, e)); //Make sure we know what version we should run println!("cargo:rustc-cfg=config_{}", config); } fn capatalize(content: &String) -> String { if content.len() == 0 { return "".to_string(); } content[..1].chars() .flat_map(|c| c.to_uppercase()) .chain(content[1..].chars()) .collect::<String>() } #[cfg(target_os = "windows")] fn get_output_lib(name: &str) -> String { format!("{}.dll", name) } #[cfg(not(target_os = "windows"))] fn get_output_lib(name: &str) -> String { format!("lib{}.so", name) } fn build(config: &String) { let msbuild = msbuild_util::MSBuild::new() .project("CSharp.csproj") .platform(msbuild_util::Platform::X64) .config(match config.as_ref() { "debug" => msbuild_util::Config::Debug, "release" => msbuild_util::Config::Release, cfg => panic!("Unknown config {}", cfg) }) .build(); if let Err(e) = msbuild { match e { msbuild_util::InvokeError::MSBuildNotFound => panic!("Failed to find MSBuild"), msbuild_util::InvokeError::BuildFailure(s) => panic!("Build Failed {}", s) } } }<|fim▁end|>
build(&config.to_string());
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>// Tifflin OS - Asynchronous common interface // - By John Hodge (thePowersGang) // // //! Asynchronous waiting support #[macro_use] extern crate syscalls; /// Trait for types that can be used for 'idle_loop' pub trait WaitController { fn get_count(&self) -> usize; fn populate(&self, cb: &mut FnMut(::syscalls::WaitItem)); fn handle(&mut self, events: &[::syscalls::WaitItem]); } /// Idle, handling events on each WaitController passed pub fn idle_loop(items: &mut [&mut WaitController]) { let mut objects = Vec::new(); loop { let count = items.iter().fold(0, |sum,ctrlr| sum + ctrlr.get_count()); objects.reserve( count ); for ctrlr in items.iter() { ctrlr.populate(&mut |wi| objects.push(wi)); } <|fim▁hole|> let mut ofs = 0; for ctrlr in items.iter_mut() { let num = ctrlr.get_count(); ctrlr.handle( &objects[ofs .. ofs + num] ); ofs += num; } objects.clear(); } }<|fim▁end|>
::syscalls::threads::wait(&mut objects, !0);
<|file_name|>globalHooks.js<|end_file_name|><|fim▁begin|>global.should = require('should');<|fim▁hole|><|fim▁end|>
global.Breadboard = require('../lib');
<|file_name|>consumers.py<|end_file_name|><|fim▁begin|>from asgiref.sync import async_to_sync from channels.generic.websocket import JsonWebsocketConsumer from django.conf import settings from django.utils import timezone from .models import Route class BusConsumer(JsonWebsocketConsumer): groups = ["bus"] def connect(self): self.user = self.scope["user"] headers = dict(self.scope["headers"]) remote_addr = headers[b"x-real-ip"].decode() if b"x-real-ip" in headers else self.scope["client"][0] if (not self.user.is_authenticated or self.user.is_restricted) and remote_addr not in settings.INTERNAL_IPS: self.connected = False self.close() return self.connected = True data = self._serialize(user=self.user) self.accept() self.send_json(data) def receive_json(self, content): # pylint: disable=arguments-differ if not self.connected: return if content.get("type") == "keepalive": self.send_json({"type": "keepalive-response"}) return if self.user is not None and self.user.is_authenticated and self.user.is_bus_admin: try: if self.within_time_range(content["time"]): route = Route.objects.get(id=content["id"]) route.status = content["status"] if content["time"] == "afternoon" and route.status == "a": route.space = content["space"] else: route.space = "" route.save() data = self._serialize() async_to_sync(self.channel_layer.group_send)("bus", {"type": "bus.update", "data": data}) except Exception as e: # TODO: Add logging print(e) self.send_json({"error": "An error occurred."}) else: self.send_json({"error": "User does not have permissions."}) def bus_update(self, event): if not self.connected: return self.send_json(event["data"]) def _serialize(self, user=None): all_routes = Route.objects.all() data = {} route_list = [] for route in all_routes: serialized = { "id": route.id, "bus_number": route.bus_number, "space": route.space, "route_name": route.route_name, "status": route.status, } route_list.append(serialized) if user and user in route.user_set.all(): data["userRouteId"] = route.id data["allRoutes"] = route_list return data def within_time_range(self, time): now_hour = timezone.localtime().hour<|fim▁hole|> within_afternoon = now_hour >= settings.BUS_PAGE_CHANGEOVER_HOUR and time == "afternoon" return within_morning or within_afternoon<|fim▁end|>
within_morning = now_hour < settings.BUS_PAGE_CHANGEOVER_HOUR and time == "morning"
<|file_name|>webdriver_msg.rs<|end_file_name|><|fim▁begin|>/* 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 constellation_msg::PipelineId; use ipc_channel::ipc::IpcSender; use rustc_serialize::json::{Json, ToJson}; use url::Url; #[derive(Deserialize, Serialize)] pub enum WebDriverScriptCommand { ExecuteScript(String, IpcSender<WebDriverJSResult>), ExecuteAsyncScript(String, IpcSender<WebDriverJSResult>), FindElementCSS(String, IpcSender<Result<Option<String>, ()>>), FindElementsCSS(String, IpcSender<Result<Vec<String>, ()>>), FocusElement(String, IpcSender<Result<(), ()>>), GetActiveElement(IpcSender<Option<String>>), GetElementTagName(String, IpcSender<Result<String, ()>>), GetElementText(String, IpcSender<Result<String, ()>>), GetFrameId(WebDriverFrameId, IpcSender<Result<Option<PipelineId>, ()>>), GetUrl(IpcSender<Url>), GetTitle(IpcSender<String>) } #[derive(Deserialize, Serialize)] pub enum WebDriverJSValue { Undefined, Null, Boolean(bool), Number(f64), String(String), // TODO: Object and WebElement } #[derive(Deserialize, Serialize)] pub enum WebDriverJSError { Timeout, UnknownType } pub type WebDriverJSResult = Result<WebDriverJSValue, WebDriverJSError>; #[derive(Deserialize, Serialize)]<|fim▁hole|> Short(u16), Element(String), Parent } impl ToJson for WebDriverJSValue { fn to_json(&self) -> Json { match *self { WebDriverJSValue::Undefined => Json::Null, WebDriverJSValue::Null => Json::Null, WebDriverJSValue::Boolean(ref x) => x.to_json(), WebDriverJSValue::Number(ref x) => x.to_json(), WebDriverJSValue::String(ref x) => x.to_json() } } } #[derive(Deserialize, Serialize)] pub enum LoadStatus { LoadComplete, LoadTimeout }<|fim▁end|>
pub enum WebDriverFrameId {
<|file_name|>test_add_group.py<|end_file_name|><|fim▁begin|>from model.group import Group import pytest def test_add_group(app, db, json_groups): group = json_groups with pytest.allure.step('Given a group list'): old_groups = db.get_group_list() with pytest.allure.step('When I add a group %s to the list' % group): app.group.create(group)<|fim▁hole|> assert sorted (old_groups, key=Group.id_or_max ) == sorted (new_groups, key=Group.id_or_max)<|fim▁end|>
#assert len (old_groups) + 1 == app.group.count() with pytest.allure.step('Then the new group list is equal to the old list with the added group'): new_groups = db.get_group_list() old_groups.append(group)
<|file_name|>wrap_writer.go<|end_file_name|><|fim▁begin|>// Copyright 2015 The Vanadium Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package textutil import ( "fmt" "io" "unicode" ) // WrapWriter implements an io.Writer filter that formats input text into output // lines with a given target width in runes. // // Each input rune is classified into one of three kinds: // EOL: end-of-line, consisting of \f, \n, \r, \v, U+2028 or U+2029 // Space: defined by unicode.IsSpace // Letter: everything else // // The input text is expected to consist of words, defined as sequences of // letters. Sequences of words form paragraphs, where paragraphs are separated // by either blank lines (that contain no letters), or an explicit U+2029 // ParagraphSeparator. Input lines with leading spaces are treated verbatim. // // Paragraphs are output as word-wrapped lines; line breaks only occur at word // boundaries. Output lines are usually no longer than the target width. The // exceptions are single words longer than the target width, which are output on // their own line, and verbatim lines, which may be arbitrarily longer or // shorter than the width. // // Output lines never contain trailing spaces. Only verbatim output lines may // contain leading spaces. Spaces separating input words are output verbatim, // unless it would result in a line with leading or trailing spaces. // // EOL runes within the input text are never written to the output; the output // line terminator and paragraph separator may be configured, and some EOL may // be output as a single space ' ' to maintain word separation. // // The algorithm greedily fills each output line with as many words as it can, // assuming that all Unicode code points have the same width. Invalid UTF-8 is // silently transformed to the replacement character U+FFFD and treated as a // single rune. // // Flush must be called after the last call to Write; the input is buffered. // // Implementation note: line breaking is a complicated topic. This approach // attempts to be simple and useful; a full implementation conforming to // Unicode Standard Annex #14 would be complicated, and is not implemented. // Languages that don't use spaces to separate words (e.g. CJK) won't work // well under the current approach. // // http://www.unicode.org/reports/tr14 [Unicode Line Breaking Algorithm] // http://www.unicode.org/versions/Unicode4.0.0/ch05.pdf [5.8 Newline Guidelines] type WrapWriter struct { // State configured by the user. w io.Writer runeDecoder RuneChunkDecoder width runePos lineTerm []byte paragraphSep string indents []string forceVerbatim bool // The buffer contains a single output line. lineBuf byteRuneBuffer // Keep track of the previous state and rune. prevState state prevRune rune // Keep track of blank input lines. inputLineHasLetter bool // lineBuf positions where the line starts (after separators and indents), a // new word has started and the last word has ended. lineStart bytePos newWordStart bytePos lastWordEnd bytePos // Keep track of paragraph terminations and line indices, so we can output the // paragraph separator and indents correctly. terminateParagraph bool paragraphLineIndex int wroteFirstLine bool } type state int<|fim▁hole|> stateSkipSpace // Skip spaces in input line. ) // NewWrapWriter returns a new WrapWriter with the given target width in runes, // producing output on the underlying writer w. The dec and enc are used to // respectively decode runes from Write calls, and encode runes to w. func NewWrapWriter(w io.Writer, width int, dec RuneChunkDecoder, enc RuneEncoder) *WrapWriter { ret := &WrapWriter{ w: w, runeDecoder: dec, width: runePos(width), lineTerm: []byte("\n"), paragraphSep: "\n", prevState: stateWordWrap, prevRune: LineSeparator, lineBuf: byteRuneBuffer{enc: enc}, } ret.resetLine() return ret } // NewUTF8WrapWriter returns a new WrapWriter filter that implements io.Writer, // and decodes and encodes runes in UTF-8. func NewUTF8WrapWriter(w io.Writer, width int) *WrapWriter { return NewWrapWriter(w, width, &UTF8ChunkDecoder{}, UTF8Encoder{}) } // Width returns the target width in runes. If width < 0 the width is // unlimited; each paragraph is output as a single line. func (w *WrapWriter) Width() int { return int(w.width) } // SetLineTerminator sets the line terminator for subsequent Write calls. Every // output line is terminated with term; EOL runes from the input are never // written to the output. A new WrapWriter instance uses "\n" as the default // line terminator. // // Calls Flush internally, and returns any Flush error. func (w *WrapWriter) SetLineTerminator(term string) error { if err := w.Flush(); err != nil { return err } w.lineTerm = []byte(term) w.resetLine() return nil } // SetParagraphSeparator sets the paragraph separator for subsequent Write // calls. Every consecutive pair of non-empty paragraphs is separated with sep; // EOL runes from the input are never written to the output. A new WrapWriter // instance uses "\n" as the default paragraph separator. // // Calls Flush internally, and returns any Flush error. func (w *WrapWriter) SetParagraphSeparator(sep string) error { if err := w.Flush(); err != nil { return err } w.paragraphSep = sep w.resetLine() return nil } // SetIndents sets the indentation for subsequent Write calls. Multiple indents // may be set, corresponding to the indent to use for the corresponding // paragraph line. E.g. SetIndents("AA", "BBB", C") means the first line in // each paragraph is indented with "AA", the second line in each paragraph is // indented with "BBB", and all subsequent lines in each paragraph are indented // with "C". // // SetIndents() is equivalent to SetIndents(""), SetIndents("", ""), etc. // // A new WrapWriter instance has no indents by default. // // Calls Flush internally, and returns any Flush error. func (w *WrapWriter) SetIndents(indents ...string) error { if err := w.Flush(); err != nil { return err } // Copy indents in case the user passed the slice via SetIndents(p...), and // canonicalize the all empty case to nil. allEmpty := true w.indents = make([]string, len(indents)) for ix, indent := range indents { w.indents[ix] = indent if indent != "" { allEmpty = false } } if allEmpty { w.indents = nil } w.resetLine() return nil } // ForceVerbatim forces w to stay in verbatim mode if v is true, or lets w // perform its regular line writing algorithm if v is false. This is useful if // there is a sequence of lines that should be written verbatim, even if the // lines don't start with spaces. // // Calls Flush internally, and returns any Flush error. func (w *WrapWriter) ForceVerbatim(v bool) error { w.forceVerbatim = v return w.Flush() } // Write implements io.Writer by buffering data into the WrapWriter w. Actual // writes to the underlying writer may occur, and may include data buffered in // either this Write call or previous Write calls. // // Flush must be called after the last call to Write. func (w *WrapWriter) Write(data []byte) (int, error) { return WriteRuneChunk(w.runeDecoder, w.addRune, data) } // Flush flushes any remaining buffered text, and resets the paragraph line // count back to 0, so that indents will be applied starting from the first // line. It does not imply a paragraph separator; repeated calls to Flush with // no intervening calls to other methods is equivalent to a single Flush. // // Flush must be called after the last call to Write, and may be called an // arbitrary number of times before the last Write. func (w *WrapWriter) Flush() error { if err := FlushRuneChunk(w.runeDecoder, w.addRune); err != nil { return err } // Add U+2028 to force the last line (if any) to be written. if err := w.addRune(LineSeparator); err != nil { return err } // Reset the paragraph line count. w.paragraphLineIndex = 0 w.resetLine() return nil } // addRune is called every time w.runeDecoder decodes a full rune. func (w *WrapWriter) addRune(r rune) error { state, lineBreak := w.nextState(r, w.updateRune(r)) if lineBreak { if err := w.writeLine(); err != nil { return err } } w.bufferRune(r, state, lineBreak) w.prevState = state w.prevRune = r return nil } // We classify each incoming rune into three kinds for easier handling. type kind int const ( kindEOL kind = iota kindSpace kindLetter ) func runeKind(r rune) kind { switch r { case '\f', '\n', '\r', '\v', LineSeparator, ParagraphSeparator: return kindEOL } if unicode.IsSpace(r) { return kindSpace } return kindLetter } func (w *WrapWriter) updateRune(r rune) bool { forceLineBreak := false switch kind := runeKind(r); kind { case kindEOL: // Update lastWordEnd if the last word just ended. if w.newWordStart != -1 { w.newWordStart = -1 w.lastWordEnd = w.lineBuf.ByteLen() } switch { case w.prevRune == '\r' && r == '\n': // Treat "\r\n" as a single EOL; we've already handled the logic for '\r', // so there's nothing to do when we see '\n'. case r == LineSeparator: // Treat U+2028 as a pure line break; it's never a paragraph break. forceLineBreak = true case r == ParagraphSeparator || !w.inputLineHasLetter: // The paragraph has just been terminated if we see an explicit U+2029, or // if we see a blank line, which may contain spaces. forceLineBreak = true w.terminateParagraph = true } w.inputLineHasLetter = false case kindSpace: // Update lastWordEnd if the last word just ended. if w.newWordStart != -1 { w.newWordStart = -1 w.lastWordEnd = w.lineBuf.ByteLen() } case kindLetter: // Update newWordStart if a new word just started. if w.newWordStart == -1 { w.newWordStart = w.lineBuf.ByteLen() } w.inputLineHasLetter = true w.terminateParagraph = false default: panic(fmt.Errorf("textutil: updateRune unhandled kind %d", kind)) } return forceLineBreak } // nextState returns the next state and whether we should break the line. // // Here's a handy table that describes all the scenarios in which we will line // break input text, grouped by the reason for the break. The current position // is the last non-* rune in each pattern, which is where we decide to break. // // w.prevState Next state Buffer reset // ----------- ---------- ------------ // ===== Force line break (U+2028 / U+2029, blank line) ===== // a..*|*** * wordWrap empty // a._.|*** * wordWrap empty // a+**|*** * wordWrap empty // // ===== verbatim: wait for any EOL ===== // _*.*|*** verbatim wordWrap empty // // ===== wordWrap: switch to verbatim ===== // a._*|*** wordWrap verbatim empty // // ===== wordWrap: line is too wide ===== // abc.|*** wordWrap wordWrap empty // abcd|.** wordWrap wordWrap empty // abcd|e.* wordWrap wordWrap empty // a_cd|.** wordWrap wordWrap empty // // abc_|*** wordWrap skipSpace empty // abcd|_** wordWrap skipSpace empty // abcd|e_* wordWrap skipSpace empty // a_cd|_** wordWrap skipSpace empty // // a_cd|e** wordWrap start newWordStart // // LEGEND // abcde Letter // . End-of-line // + End-of-line (only U+2028 / U+2029) // _ Space // * Any rune (letter, line-end or space) // | Visual indication of width=4, has no width itself. // // Note that Flush calls behave exactly as if an explicit U+2028 line separator // were added to the end of all buffered data. func (w *WrapWriter) nextState(r rune, forceLineBreak bool) (state, bool) { kind := runeKind(r) if w.forceVerbatim { return stateVerbatim, forceLineBreak || kind == kindEOL } if forceLineBreak { return stateWordWrap, true } // Handle non word-wrap states, which are easy. switch w.prevState { case stateVerbatim: if kind == kindEOL { return stateWordWrap, true } return stateVerbatim, false case stateSkipSpace: if kind == kindSpace { return stateSkipSpace, false } return stateWordWrap, false } // Handle stateWordWrap, which is more complicated. // Switch to the verbatim state when we see a space right after an EOL. if runeKind(w.prevRune) == kindEOL && kind == kindSpace { return stateVerbatim, true } // Break on EOL or space when the line is too wide. See above table. if w.width >= 0 && w.width <= w.lineBuf.RuneLen()+1 { switch kind { case kindEOL: return stateWordWrap, true case kindSpace: return stateSkipSpace, true } // case kindLetter falls through } // Handle the newWordStart case in the above table. if w.width >= 0 && w.width < w.lineBuf.RuneLen()+1 && w.newWordStart != w.lineStart { return stateWordWrap, true } // Stay in the wordWrap state and don't break the line. return stateWordWrap, false } func (w *WrapWriter) writeLine() error { if w.lastWordEnd == -1 { // Don't write blank lines, but we must reset the line in case the paragraph // has just been terminated. w.resetLine() return nil } // Write the line (without trailing spaces) followed by the line terminator. line := w.lineBuf.Bytes()[:w.lastWordEnd] if _, err := w.w.Write(line); err != nil { return err } if _, err := w.w.Write(w.lineTerm); err != nil { return err } // Reset the line buffer. w.wroteFirstLine = true w.paragraphLineIndex++ if w.newWordStart != -1 { // If we have an unterminated new word, we must be in the newWordStart case // in the table above. Handle the special buffer reset here. newWord := string(w.lineBuf.Bytes()[w.newWordStart:]) w.resetLine() w.newWordStart = w.lineBuf.ByteLen() w.lineBuf.WriteString(newWord) } else { w.resetLine() } return nil } func (w *WrapWriter) resetLine() { w.lineBuf.Reset() w.newWordStart = -1 w.lastWordEnd = -1 // Write the paragraph separator if the previous paragraph has terminated. // This consumes no runes from the line width. if w.wroteFirstLine && w.terminateParagraph { w.lineBuf.WriteString0Runes(w.paragraphSep) w.paragraphLineIndex = 0 } // Add indent; a non-empty indent consumes runes from the line width. var indent string switch { case w.paragraphLineIndex < len(w.indents): indent = w.indents[w.paragraphLineIndex] case len(w.indents) > 0: indent = w.indents[len(w.indents)-1] } w.lineBuf.WriteString(indent) w.lineStart = w.lineBuf.ByteLen() } func (w *WrapWriter) bufferRune(r rune, state state, lineBreak bool) { // Never add leading spaces to the buffer in the wordWrap state. wordWrapNoLeadingSpaces := state == stateWordWrap && !lineBreak switch kind := runeKind(r); kind { case kindEOL: // When we're word-wrapping and we see a letter followed by EOL, we convert // the EOL into a single space in the buffer, to break the previous word // from the next word. if wordWrapNoLeadingSpaces && runeKind(w.prevRune) == kindLetter { w.lineBuf.WriteRune(' ') } case kindSpace: if wordWrapNoLeadingSpaces || state == stateVerbatim { w.lineBuf.WriteRune(r) } case kindLetter: w.lineBuf.WriteRune(r) default: panic(fmt.Errorf("textutil: bufferRune unhandled kind %d", kind)) } }<|fim▁end|>
const ( stateWordWrap state = iota // Perform word-wrapping [start state] stateVerbatim // Verbatim output-line, no word-wrapping
<|file_name|>lint-ctypes-73249-2.rs<|end_file_name|><|fim▁begin|>#![feature(type_alias_impl_trait)] #![deny(improper_ctypes)] pub trait Baz {} impl Baz for () {} type Qux = impl Baz; fn assign() -> Qux {}<|fim▁hole|> impl Foo for () { type Assoc = Qux; } #[repr(transparent)] pub struct A<T: Foo> { x: &'static <T as Foo>::Assoc, } extern "C" { pub fn lint_me() -> A<()>; //~ ERROR: uses type `impl Baz` } fn main() {}<|fim▁end|>
pub trait Foo { type Assoc: 'static; }
<|file_name|>flow-require-manager.js<|end_file_name|><|fim▁begin|>'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _glob = require('glob'); var _glob2 = _interopRequireDefault(_glob); var _lodash = require('lodash'); var _lodash2 = _interopRequireDefault(_lodash); var _path = require('path'); <|fim▁hole|> var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var FlowRequireManager = function () { function FlowRequireManager(settings) { _classCallCheck(this, FlowRequireManager); this.settings = settings || {}; this.items = {}; } _createClass(FlowRequireManager, [{ key: 'log', value: function log(level, message) { if (this.settings.logger) { this.settings.logger.log(level, message); } } }, { key: 'getAbsolutePath', value: function getAbsolutePath(relative) { return _path2.default.normalize(_path2.default.join(process.cwd(), relative)); } }, { key: 'addItem', value: function addItem(item) { this.log('info', 'Adding item ' + item.name); this.items[item.name] = item; } }, { key: 'removeItem', value: function removeItem(name) { this.log('info', 'Removing item ' + name); delete this.items[name]; } }, { key: 'getItem', value: function getItem(name) { return this.items[name]; } }, { key: 'addFolder', value: function addFolder(folder, cb) { (0, _glob2.default)(folder + '/' + this.settings.pattern, {}, function (err, files) { if (err) { return cb(err); } for (var i = 0; i < files.length; i++) { var extension = _path2.default.extname(files[i]); var content = void 0; var absolutePath = this.getAbsolutePath(files[i]); if (extension === '.json' || extension === '.js') { content = require(absolutePath); } else { content = _fs2.default.readFileSync(absolutePath, 'utf8'); } if (content) { if (!_lodash2.default.isArray(content)) { var name = content.name; if (_lodash2.default.isFunction(content)) { content = { method: content }; } else if (_lodash2.default.isString(content)) { content = { text: content }; } if (!name) { name = _path2.default.basename(files[i], extension).toLowerCase(); } content.name = name; content = [content]; } for (var j = 0; j < content.length; j++) { this.addItem(content[j]); } } else { this.log('warning', 'Content not found for file ' + files[i]); } } return cb(); }.bind(this)); } }]); return FlowRequireManager; }(); exports.default = FlowRequireManager;<|fim▁end|>
var _path2 = _interopRequireDefault(_path);
<|file_name|>reducer.js<|end_file_name|><|fim▁begin|>import { RELOAD_WEBVIEW, WEBVIEW_ERROR } from '../../middlewares/Webviews/types'; import { ADD_ACCOUNT, REMOVE_ACCOUNT, TOGGLE_SIDEBAR, TOGGLE_SIDEBAR_ITEM_POSITION, UPDATE_SETTINGS, UPDATE_UNREAD_EMAILS } from './types'; const initialState = { accounts: [], settings: { darkTheme: false, hideSidebar: false, useProtonMailBeta: false, }, webviewStatuses: {}, }; export default (state = initialState, action) => { switch (action.type) { case ADD_ACCOUNT: return { ...state, accounts: [ ...state.accounts, action.account, ], }; case REMOVE_ACCOUNT: return { ...state, accounts: state.accounts.filter(a => a.username !== action.username), }; case TOGGLE_SIDEBAR: return { ...state, settings: { ...state.settings, hideSidebar: !state.settings.hideSidebar, } }; case TOGGLE_SIDEBAR_ITEM_POSITION: { const accounts = [...state.accounts]; accounts.splice(action.to, 0, ...accounts.splice(action.from, 1)); return { ...state, accounts }; } case UPDATE_SETTINGS: return { ...state, settings: { ...state.settings, [action.key]: action.value, }, }; case RELOAD_WEBVIEW: return { ...state, webviewStatuses: { ...state.webviewStatuses, [action.name]: {}, }, }; case WEBVIEW_ERROR: return { ...state, webviewStatuses: { ...state.webviewStatuses, [action.name]: { error: action.error,<|fim▁hole|> }, }, }; case UPDATE_UNREAD_EMAILS: return { ...state, accounts: state.accounts .map(a => a.username === action.username ? ({ ...a, unreadEmails: action.unreadEmails }) : a) }; } return state; };<|fim▁end|>
<|file_name|>starter_first.py<|end_file_name|><|fim▁begin|>import urllib import twython def Crowd_twitter(query): consumer_key = '*****'; consumer_secret = '*****'; access_token = '******'; access_token_secret = '******'; client_args = {'proxies': {'https': 'http://10.93.0.37:3333'}} t = twython.Twython(app_key=consumer_key, app_secret=consumer_secret, oauth_token=access_token, oauth_token_secret=access_token_secret, client_args = client_args) # query=raw_input("What do you want to search for?"); # query.replace(" ","+"); output = t.search(q=query, result_type='popular', count=10) #purposely restricted to 10 users to protect from Spamming the Twitter server which could cause blacklisting of our server #print output; aggregater = [] for i in range(10): aggregater.append(output[u'statuses'][i][u'text']); happy = open("positive-words.txt",'r') sad = open("negative-words.txt",'r') ha = happy.readlines() sa = sad.readlines() happy.close() sad.close() for i in range(len(ha)): ha[i]=ha[i].rstrip() for i in range(len(sa)): sa[i]=sa[i].rstrip() #Put basic sentiment analysis on tweet posi = 0; negi = 0; for i in range(10): for j in range(len(ha)): if(ha[j] in aggregater[i]): posi += 1; for j in range(len(sa)): if(sa[j] in aggregater[i]): negi += 1; #print "<!DOCTYPE html>\n<html>\n<title>Crowd likes!</title>" if posi > negi: return "<h1>CROWD LOVES IT!!:-)</h1>" elif posi<negi: return "<h1>CROWD DOESN'T LIKE IT!! :-( </h1>" else: return "<h1>CROWD CAN'T DECIDE :-| !!</h1>" def buildwebpage(product_fk,product_cr,product_am,product_eb,search_query): # return images,links,names,prices print "<!DOCTYPE html>\n<html>"; print "\n<h1><em><ul>WELCOME TO DEALERSITE - ONE STOP FOR ALL YOUR SHOPPING</ul></em></h1>\n<body>" print "<h1>THIS IS WHAT THE CROWD THINKS OF "+search_query+":</h1>" print Crowd_twitter(search_query) print "\n<h1>AMAZON</h1>"; for i in range(3): print "\n<h2>"+product_am[2][i]+"</h2>" print "<img border=\"0\" src=\""+product_am[0][i]+"\" alt=\"Amazon\">" print "<a href=\""+product_am[1][i]+"\">CLICK THIS TO TAKE YOU TO AMAZONS PAGE TO BUY THE PRODUCT</a>" print "\n<p>PRICE : Rs."+product_am[3][i]+"</p>"; print "\n<h1>EBAY</h1>"; for i in range(3): print "\n<h2>"+product_eb[2][i]+"</h2>" print "<img border=\"0\" src=\""+product_eb[0][i]+"\" alt=\"EBay\">" print "<a href=\""+product_eb[1][i]+"\">CLICK THIS TO TAKE YOU TO EBAYS PAGE TO BUY THE PRODUCT</a>" print "\n<p>PRICE : Rs."+product_eb[3][i]+"</p>"; print "\n<h1>FLIPKART</h1>"; for i in range(3): print "\n<h2>"+product_fk[2][i]+"</h2>" print "<img border=\"0\" src=\""+product_fk[0][i]+"\" alt=\"Flipkart\">" print "<a href=\""+product_fk[1][i]+"\">CLICK THIS TO TAKE YOU TO FLIPKARTS PAGE TO BUY THE PRODUCT</a>" print "\n<p>PRICE : Rs."+product_fk[3][i]+"</p>"; print "\n<h1>CROMA RETAIL</h1>"; for i in range(3): print "\n<h2>"+product_cr[2][i]+"</h2>" print "<img border=\"0\" src=\""+product_cr[0][i]+"\" alt=\"CROMA\">" print "<a href=\""+product_cr[1][i]+"\">CLICK THIS TO TAKE YOU TO CROMA PAGE TO BUY THE PRODUCT</a>" print "\n<p>PRICE : "+product_cr[3][i]+"</p>"; print "<a href=\"/comparison.html\"><em><b>CLICK HERE FOR A COMPARISON OF DIFFERENT BRANDS</b></em></a>" # print "<a href=\"/crowd.html\">CLICK HERE FOR WHAT THE CROWD THINKS OF THE PRODUCT</a>" print "</body>\n</html>" def link_fk_actu(product_image): Flipkart_query = "http://www.flipkart.com/all-categories/pr?p%5B%5D=sort%3Drelevance&sid=search.flipkart.com&q="; # print "\n\n\n\n\nLINK FK ACTUAL"; # print product_image; names = []; for i in range(3): ind = product_image[i].index("data-pid=")+len("data-pid=\""); indend = product_image[i].index("data-tracking-products",ind) - 2; names.append(Flipkart_query + product_image[i][ind:indend]); return names; def price_fk(product_image): # print "\n\n\n\n\nPRICE FK"; # print product_image; names = []; for i in range(3): indend = product_image[i].index(";;"); ind = product_image[i].rfind(";",0,indend-1); names.append(product_image[i][ind+1:indend]); return names; def name_fk(product_image): # print "\n\n\n\n\nNAME FK"; # print product_image; names = []; for i in range(3): ind = product_image[i].index("alt")+len("alt=\""); names.append(product_image[i][ind:].split()[0]); # product_image[i][ind:indend]); return names; def link_fk(product_link): # print "\n\n\n\n\nLINK FK"; # print product_link; beg_string = "www.flipkart.com"; links = []; for i in range(3): ind = product_link[i].index("a href=")+len("a href=\""); indend = product_link[i].index("class") - 2; links.append(beg_string+product_link[i][ind:indend]); return links; def image_fk(product_image): img = []; counter = 0; for i in range(len(product_image)): # print product_image[i]; try: ind = product_image[i].index("data-src")+len("data-src=\""); ind_end1 = 10000; ind_end2 = 10000; try: ind_end1 = product_image[i].index("\"",ind); except ValueError: ind_end2 = product_image[i].index("\'",ind); if ind_end2 < ind_end1: ind_end = ind_end2; else: ind_end = ind_end1; img.append(product_image[i][ind:ind_end]); ++counter; except ValueError: ind = product_image[i].index("src=")+len("src=\""); ind_end1 = 10000; ind_end2 = 10000; try: ind_end1 = product_image[i].index("\"",ind); except ValueError: ind_end2 = product_image[i].index("\'",ind); if ind_end2 < ind_end1: ind_end = ind_end2; else: ind_end = ind_end1; img.append(product_image[i][ind:ind_end]); ++counter; if counter == 3: break; return img[:3]; def process_fk(fk_lines): product_image = []; product_name = []; product_otherone = []; flag = 0; counter = 0; prev_line = ""; linenum = 0; for l in fk_lines: # print l; # if "<div class=\'product" in l: # flag = 1; linenum += 1; if "<div class='product" in l: product_name.append(l); flag = 1; # if flag == 0 and "<img src=" in l: # flag =1; # continue; if flag == 1 and "<img src=" in l: product_image.append(l); product_otherone.append(prev_line); ++counter; if(counter==12): break; flag = 0; prev_line = l; product_image = product_image[1:11]; product_name = product_name[1:11]; product_otherone = product_otherone[0:10]; if(len(product_name)>=10): teer = link_fk_actu(product_name); else: teer = link_fk(product_otherone); return image_fk(product_image),teer,name_fk(product_image),price_fk(product_name); ##################################################################################################### def process_am(am_lines): # print am_lines; links = []; images = []; names = []; prices = []; flag = 0; counter = 0; #urllib has a very strange behaviour when retrieving webpages - The server hands out slightly difficult code to parse. flag = 0; for l in am_lines: # print 1; try: if ("<div id=\"srProductTitle" in l) and ("<a href=\"" in l) and ("src=\"" in l) and ("<br clear=\"all\" />" in l): # print l; # break; ind =l.index("<a href=\"")+len("<a href=\""); # print ind; indend = l.index("\"",ind+1); links.append(l[ind:indend]); # i += 1; ind =l.index("src=\"")+len("src=\""); indend = l.index("\"",ind); images.append(l[ind:indend]); # i+=1; ind =l.index("<br clear=\"all\" />")+len("<br clear=\"all\" />"); indend = l.index("</a",ind); names.append(l[ind:indend]); flag = 1; # print links,images,names; # for j in range(10): #generally keep going and stop when you find the necessary key word # i += 1; if ("<div class=\"newPrice\">" in l) or ("<div class=\"usedPrice\">" in l): if flag == 1: # print flag; indend =l.index("</span></span></div>"); ind = l.rfind("</span>",0,indend) + len("</span>"); prices.append(l[ind:indend]); # flag = 1; counter +=1; flag = 0; except ValueError: continue; # break; # if flag ==1: # break; if counter == 3: break; return images,links,names,prices; ########################################################################################################### def process_cr(cr_lines): links = []; images = []; names = []; prices = []; flag = 0; counter = 0; #urllib has a very strange behaviour when retrieving webpages - The server hands out slightly difficult code to parse. flag = 0; base = "http://www.cromaretail.com" for l in cr_lines: # print l; try: if ("<article><a title=" in l) and ("href" in l) and ("<img src=\"" in l): # print l; ind =l.index("<article><a title=")+len("<article><a title=\""); indend = l.index("\"",ind+1); names.append(l[ind:indend]); ind =l.index("href=\"")+len("href=\""); indend = l.index("\"",ind+1); links.append(base+"/"+l[ind:indend]); ind =l.index("<img src=\"")+len("<img src=\""); indend = l.index("\"",ind+1); images.append(base+l[ind:indend]); flag =1; if ("</span>" in l) and flag ==1: ind =l.index("</span>")+len("</span>"); indend = l.index("<",ind+1); prices.append(l[ind:indend]); counter += 1; flag =0; except ValueError: continue; if counter == 3: break; return images,links,names,prices; ####################################################################################################################### def process_eb(eb_lines): links = []; images = []; names = []; prices = []; flag = 0; counter = 0; #urllib has a very strange behaviour when retrieving webpages - The server hands out slightly difficult code to parse. for i in range(len(eb_lines)): # print l; l = eb_lines[i]; try: if (" class=\"lv-1st\"></a>" in l): Link = eb_lines[i+12]; Image = eb_lines[i+14]; Name = eb_lines[i+14]; Price = eb_lines[i+45]; # print Link,Image,Name,Price,"\n\n\n=======================\n\n\n"; ind =Link.index("<a href=\"")+len("<a href=\""); indend = Link.index("\"",ind+1); links.append(Link[ind:indend]); ind =Image.index("src=")+len("src=\""); indend = Image.index("class",ind+1); images.append(Image[ind:indend-2]); ind =Name.index("alt=")+len("alt=\""); indend = Name.index(" />",ind+1); names.append(Name[ind:indend-1]); ind =Price.index("</b>")+len("</b>"); indend = Price.index("<",ind+1); prices.append(Price[ind:indend]); counter += 1; i += 50; except ValueError: continue; if counter == 3: # print images,"\n\n\n=======================\n\n\n",links,"\n\n\n=======================\n\n\n",names,"\n\n\n=======================\n\n\n",prices; return images,links,names,prices; # break; if __name__=="__main__": proxy = 'http://10.93.0.37:3333';<|fim▁hole|> search_query = search_query.replace(" ","+"); Flipkart_query = "http://www.flipkart.com/all-categories/pr?p%5B%5D=sort%3Drelevance&sid=search.flipkart.com&q="+search_query; Amazon_query = "http://www.amazon.in/s/ref=nb_sb_noss_1?url=search-alias%3Daps&field-keywords="+search_query+"&rh=i%3Aaps%2Ck%3A"+search_query; Croma_query = "http://www.cromaretail.com/productsearch.aspx?txtSearch="+search_query+"&x=-808&y=-85"; Ebay_query = "http://www.ebay.in/sch/i.html?_trksid=p2050601.m570.l1313.TR0.TRC0.X"+search_query+"&_nkw="+search_query+"&_sacat=0&_from=R40"; Flipkart = urllib.urlopen(Flipkart_query, proxies={'http': proxy}) Amazon = urllib.urlopen(Amazon_query, proxies={'http': proxy}) Croma = urllib.urlopen(Croma_query, proxies={'http': proxy}) Ebay = urllib.urlopen(Ebay_query, proxies={'http': proxy}) fk_lines = Flipkart.readlines(); am_lines = Amazon.readlines(); cr_lines = Croma.readlines(); eb_lines = Ebay.readlines(); product_fk = process_fk(fk_lines); product_am = process_am(am_lines); product_cr = process_cr(cr_lines); product_eb = process_eb(eb_lines); buildwebpage(product_fk,product_cr,product_am,product_eb,search_query); # Crowd_twitter();<|fim▁end|>
search_query = raw_input("Enter the name to compare : ");
<|file_name|>boss_death_knight_darkreaver.cpp<|end_file_name|><|fim▁begin|>/* * Copyright (C) 2008-2010 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 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 General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* ScriptData SDName: Boss_Death_knight_darkreaver SD%Complete: 100 SDComment: SDCategory: Scholomance EndScriptData */ #include "ScriptPCH.h" class boss_death_knight_darkreaver : public CreatureScript { public: boss_death_knight_darkreaver() : CreatureScript("boss_death_knight_darkreaver") { } CreatureAI* GetAI(Creature* pCreature) const { return new boss_death_knight_darkreaverAI (pCreature); } struct boss_death_knight_darkreaverAI : public ScriptedAI { boss_death_knight_darkreaverAI(Creature *c) : ScriptedAI(c) {} void Reset() { } void DamageTaken(Unit * /*done_by*/, uint32 &damage) { if (me->GetHealth() <= damage) DoCast(me, 23261, true); //Summon Darkreaver's Fallen Charger } void EnterCombat(Unit * /*who*/) { } }; }; void AddSC_boss_death_knight_darkreaver()<|fim▁hole|><|fim▁end|>
{ new boss_death_knight_darkreaver(); }
<|file_name|>jediepcserver.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python """ Jedi EPC server. Copyright (C) 2012 Takafumi Arakaki Author: Takafumi Arakaki <aka.tkf at gmail.com> This file is NOT part of GNU Emacs. Jedi EPC server is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Jedi EPC server is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Jedi EPC server. If not, see <http://www.gnu.org/licenses/>. """ import argparse import glob import itertools import logging import logging.handlers import os import re import site import sys from collections import namedtuple import jedi import jedi.api import epc import epc.server import sexpdata logger = logging.getLogger('jediepcserver') parser = argparse.ArgumentParser( formatter_class=argparse.RawTextHelpFormatter, description=__doc__) parser.add_argument( '--address', default='localhost') parser.add_argument( '--port', default=0, type=int) parser.add_argument( '--port-file', '-f', default='-', type=argparse.FileType('wt'), help='file to write port on. default is stdout.') parser.add_argument( '--sys-path', '-p', default=[], action='append', help='paths to be inserted at the top of `sys.path`.') parser.add_argument( '--sys-path-append', default=[], action='append', help='paths to be appended at the end of `sys.path`.') parser.add_argument( '--virtual-env', '-v', default=[], action='append', help='paths to be used as if VIRTUAL_ENV is set to it.') parser.add_argument( '--log', help='Save server log to this file.') parser.add_argument( '--log-level', choices=['CRITICAL', 'ERROR', 'WARN', 'INFO', 'DEBUG'], help='Logging level for log file.') parser.add_argument( '--log-rotate-max-size', default=0, type=int, help='Rotate log file after it reaches this size', ) parser.add_argument( '--log-rotate-max-count', default=3, type=int, help='Max number of log rotations before removal', ) parser.add_argument( '--log-traceback', action='store_true', default=False, help='Include traceback in logging output.') parser.add_argument( '--pdb', dest='debugger', const='pdb', action='store_const', help='start pdb when error occurs.') parser.add_argument( '--ipdb', dest='debugger', const='ipdb', action='store_const', help='start ipdb when error occurs.') PY3 = (sys.version_info[0] >= 3) NEED_ENCODE = not PY3 LogSettings = namedtuple( 'LogSettings', [ 'log_file', 'log_level', 'log_rotate_max_size', 'log_rotate_max_count', ], ) try: jedi.create_environment except AttributeError: jedi_create_environment = None else: _cached_jedi_environments = {} def jedi_create_environment(venv, safe=False): """Cache jedi environments to avoid startup cost.""" try: return _cached_jedi_environments[venv] except KeyError: logger.info('Creating jedi environment: %s', venv) if venv is None: jedienv = jedi.api.environment.get_default_environment() else: jedienv = jedi.create_environment(venv, safe=safe) _cached_jedi_environments[venv] = jedienv return jedienv def get_venv_sys_path(venv): if jedi_create_environment is not None: return jedi_create_environment(venv).get_sys_path() from jedi.evaluate.sys_path import get_venv_path return get_venv_path(venv) class JediEPCHandler(object): def __init__(self, sys_path=(), virtual_envs=(), sys_path_append=()): self.script_kwargs = self._get_script_path_kwargs( sys_path=sys_path, virtual_envs=virtual_envs, sys_path_append=sys_path_append, ) def get_sys_path(self): environment = self.script_kwargs.get('environment') if environment is not None: return environment.get_sys_path() sys_path = self.script_kwargs.get('sys_path') if sys_path is not None: return sys_path return sys.path @classmethod def _get_script_path_kwargs(cls, sys_path, virtual_envs, sys_path_append): result = {} if jedi_create_environment: # Need to specify some environment explicitly to workaround # https://github.com/davidhalter/jedi/issues/1242. Otherwise jedi # will create a lot of child processes. if virtual_envs: primary_env, virtual_envs = virtual_envs[0], virtual_envs[1:] primary_env = path_expand_vars_and_user(primary_env) else: primary_env = None try: result['environment'] = jedi_create_environment(primary_env) except Exception: logger.warning( 'Cannot create environment for %r', primary_env, exc_info=1 ) if primary_env is not None: result['environment'] = jedi_create_environment(None) if not sys_path and not virtual_envs and not sys_path_append: # No additional path customizations. return result # Either multiple environments or custom sys_path extensions are # specified, or jedi version doesn't support environments. final_sys_path = [] final_sys_path.extend(path_expand_vars_and_user(p) for p in sys_path) for p in virtual_envs: final_sys_path.extend(get_venv_sys_path(path_expand_vars_and_user(p))) final_sys_path.extend( path_expand_vars_and_user(p) for p in sys_path_append ) dupes = set() def not_seen_yet(val):<|fim▁hole|> if val in dupes: return False dupes.add(val) return True result['sys_path'] = [p for p in final_sys_path if not_seen_yet(p)] return result def jedi_script(self, source, line, column, source_path): if NEED_ENCODE: source = source.encode('utf-8') source_path = source_path and source_path.encode('utf-8') return jedi.Script( source, line, column, source_path or '', **self.script_kwargs ) def complete(self, *args): def _wrap_completion_result(comp): try: docstr = comp.docstring() except Exception: logger.warning( "Cannot get docstring for completion %s", comp, exc_info=1 ) docstr = "" return dict( word=comp.name, doc=docstr, description=candidates_description(comp), symbol=candidate_symbol(comp), ) return [ _wrap_completion_result(comp) for comp in self.jedi_script(*args).completions() ] def get_in_function_call(self, *args): sig = self.jedi_script(*args).call_signatures() call_def = sig[0] if sig else None if not call_def: return [] return dict( # p.description should do the job. But jedi-vim use replace. # So follow what jedi-vim does... params=[PARAM_PREFIX_RE.sub('', p.description).replace('\n', '') for p in call_def.params], index=call_def.index, call_name=call_def.name, ) def _goto(self, method, *args): """ Helper function for `goto_assignments` and `usages`. :arg method: `jedi.Script.goto_assignments` or `jedi.Script.usages` :arg args: Arguments to `jedi_script` """ # `definitions` is a list. Each element is an instances of # `jedi.api_classes.BaseOutput` subclass, i.e., # `jedi.api_classes.RelatedName` or `jedi.api_classes.Definition`. definitions = method(self.jedi_script(*args)) return [dict( column=d.column, line_nr=d.line, module_path=d.module_path if d.module_path != '__builtin__' else [], module_name=d.module_name, description=d.description, ) for d in definitions] def goto(self, *args): return self._goto(jedi.Script.goto_assignments, *args) def related_names(self, *args): return self._goto(jedi.Script.usages, *args) def get_definition(self, *args): definitions = self.jedi_script(*args).goto_definitions() return [definition_to_dict(d) for d in definitions] def defined_names(self, *args): # XXX: there's a bug in Jedi that returns returns definitions from inside # classes or functions even though all_scopes=False is set by # default. Hence some additional filtering is in order. # # See https://github.com/davidhalter/jedi/issues/1202 top_level_names = [ defn for defn in jedi.api.names(*args) if defn.parent().type == 'module' ] return list(map(get_names_recursively, top_level_names)) def get_jedi_version(self): return [dict( name=module.__name__, file=getattr(module, '__file__', []), version=get_module_version(module) or [], ) for module in [sys, jedi, epc, sexpdata]] def candidate_symbol(comp): """ Return a character representing completion type. :type comp: jedi.api.Completion :arg comp: A completion object returned by `jedi.Script.completions`. """ try: return comp.type[0].lower() except (AttributeError, TypeError): return '?' def candidates_description(comp): """ Return `comp.description` in an appropriate format. * Avoid return a string 'None'. * Strip off all newlines. This is required for using `comp.description` as candidate summary. """ desc = comp.description return _WHITESPACES_RE.sub(' ', desc) if desc and desc != 'None' else '' _WHITESPACES_RE = re.compile(r'\s+') PARAM_PREFIX_RE = re.compile(r'^param\s+') """RE to strip unwanted "param " prefix returned by param.description.""" def definition_to_dict(d): return dict( doc=d.docstring(), description=d.description, desc_with_module=d.desc_with_module, line_nr=d.line, column=d.column, module_path=d.module_path, name=getattr(d, 'name', []), full_name=getattr(d, 'full_name', []), type=getattr(d, 'type', []), ) def get_names_recursively(definition, parent=None): """ Fetch interesting defined names in sub-scopes under `definition`. :type names: jedi.api_classes.Definition """ d = definition_to_dict(definition) try: d['local_name'] = parent['local_name'] + '.' + d['name'] except (AttributeError, TypeError): d['local_name'] = d['name'] if definition.type == 'class': ds = definition.defined_names() return [d] + [get_names_recursively(c, d) for c in ds] else: return [d] def get_module_version(module): notfound = object() for key in ['__version__', 'version']: version = getattr(module, key, notfound) if version is not notfound: return version try: from pkg_resources import get_distribution, DistributionNotFound try: return get_distribution(module.__name__).version except DistributionNotFound: pass except ImportError: pass def path_expand_vars_and_user(p): return os.path.expandvars(os.path.expanduser(p)) def configure_logging(log_settings): """ :type log_settings: LogSettings """ if not log_settings.log_file: return fmter = logging.Formatter('%(asctime)s:' + logging.BASIC_FORMAT) if log_settings.log_rotate_max_size > 0: handler = logging.handlers.RotatingFileHandler( filename=log_settings.log_file, mode='w', maxBytes=log_settings.log_rotate_max_size, backupCount=log_settings.log_rotate_max_count, ) else: handler = logging.FileHandler(filename=log_settings.log_file, mode='w') handler.setFormatter(fmter) if log_settings.log_level: logging.root.setLevel(log_settings.log_level.upper()) logging.root.addHandler(handler) def jedi_epc_server( address='localhost', port=0, port_file=sys.stdout, sys_path=[], virtual_env=[], sys_path_append=[], debugger=None, log_traceback=None, ): """Start EPC server. :type log_settings: LogSettings """ logger.debug( 'jedi_epc_server: sys_path=%r virtual_env=%r sys_path_append=%r', sys_path, virtual_env, sys_path_append, ) if not virtual_env and os.getenv('VIRTUAL_ENV'): logger.debug( 'Taking virtual env from VIRTUAL_ENV: %r', os.environ['VIRTUAL_ENV'], ) virtual_env = [os.environ['VIRTUAL_ENV']] handler = JediEPCHandler( sys_path=sys_path, virtual_envs=virtual_env, sys_path_append=sys_path_append, ) logger.debug( 'Starting Jedi EPC server with the following sys.path: %r', handler.get_sys_path(), ) server = epc.server.EPCServer((address, port)) server.register_function(handler.complete) server.register_function(handler.get_in_function_call) server.register_function(handler.goto) server.register_function(handler.related_names) server.register_function(handler.get_definition) server.register_function(handler.defined_names) server.register_function(handler.get_jedi_version) @server.register_function def toggle_log_traceback(): server.log_traceback = not server.log_traceback return server.log_traceback port_file.write(str(server.server_address[1])) # needed for Emacs client port_file.write("\n") port_file.flush() if port_file is not sys.stdout: port_file.close() # This is not supported Python-EPC API, but I am using this for # backward compatibility for Python-EPC < 0.0.4. In the future, # it should be passed to the constructor. server.log_traceback = bool(log_traceback) if debugger: server.set_debugger(debugger) handler = logging.StreamHandler() fmter = logging.Formatter('%(asctime)s:' + logging.BASIC_FORMAT) handler.setFormatter(fmter) handler.setLevel(logging.DEBUG) server.logger.addHandler(handler) server.logger.setLevel(logging.DEBUG) return server # def add_virtualenv_path(venv): # """Add virtualenv's site-packages to `sys.path`.""" # venv = os.path.abspath(venv) # paths = glob.glob(os.path.join( # venv, 'lib', 'python*', 'site-packages')) # if not paths: # raise ValueError('Invalid venv: no site-packages found: %s' % venv) # for path in paths: # site.addsitedir(path) def main(args=None): ns = parser.parse_args(args) ns_vars = vars(ns).copy() log_settings = LogSettings( log_file=ns_vars.pop('log'), log_level=ns_vars.pop('log_level'), log_rotate_max_size=ns_vars.pop('log_rotate_max_size'), log_rotate_max_count=ns_vars.pop('log_rotate_max_count'), ) configure_logging(log_settings) server = jedi_epc_server(**ns_vars) server.serve_forever() server.logger.info('exit') if __name__ == '__main__': main()<|fim▁end|>
<|file_name|>TetrahedronIntersection.cpp<|end_file_name|><|fim▁begin|>// ***************************************************************************** // <ProjectName> ENigMA </ProjectName> // <Description> Extended Numerical Multiphysics Analysis </Description> // <HeadURL> $HeadURL$ </HeadURL> // <LastChangedDate> $LastChangedDate$ </LastChangedDate> // <LastChangedRevision> $LastChangedRevision$ </LastChangedRevision> // <Author> Billy Araujo </Author> // ***************************************************************************** #include "ui_TetrahedronIntersection.h" #include "TetrahedronIntersection.h" #include <vtkEventQtSlotConnect.h> #include <vtkDataObjectToTable.h> #include <vtkQtTableView.h> #include <vtkRenderer.h> #include <vtkRenderWindow.h> #include <vtkRendererCollection.h> #include <vtkPolyDataMapper.h> #include <vtkPoints.h> #include <vtkPointData.h> #include <vtkTriangle.h> #include <vtkPolyData.h> #include <vtkUnstructuredGrid.h> #include <vtkDataSetMapper.h> #include <vtkCellArray.h> #include <vtkProperty.h> #include <vtkAxesActor.h> #include <vtkTransform.h> #include <vtkVertexGlyphFilter.h> #include "vtkSmartPointer.h" #define VTK_CREATE(type, name) vtkSmartPointer<type> name = vtkSmartPointer<type>::New() // Constructor TetrahedronIntersection::TetrahedronIntersection() { this->ui = new Ui_TetrahedronIntersection; this->ui->setupUi(this); // Qt Table View this->m_tableView = vtkSmartPointer<vtkQtTableView>::New(); // Place the table view in the designer form this->ui->tableFrame->layout()->addWidget(this->m_tableView->GetWidget()); // Mesh VTK_CREATE(vtkDataSetMapper, meshMapper); meshMapper->ImmediateModeRenderingOn(); this->m_meshActor = vtkSmartPointer<vtkActor>::New(); this->m_meshActor->SetMapper(meshMapper); m_meshActor->GetProperty()->SetRepresentationToSurface(); m_meshActor->GetProperty()->LightingOn(); // Point VTK_CREATE(vtkPolyDataMapper, pointMapper); pointMapper->ImmediateModeRenderingOn(); this->m_pointActor = vtkSmartPointer<vtkActor>::New(); this->m_pointActor->SetMapper(pointMapper); m_pointActor->GetProperty()->SetRepresentationToSurface(); m_pointActor->GetProperty()->LightingOn(); m_pointActor->GetProperty()->SetPointSize(5); // Tetrahedron VTK_CREATE(vtkDataSetMapper, tetrahedronMapper); tetrahedronMapper->ImmediateModeRenderingOn(); this->m_tetrahedronActor = vtkSmartPointer<vtkActor>::New(); this->m_tetrahedronActor->SetMapper(tetrahedronMapper); m_tetrahedronActor->GetProperty()->SetRepresentationToSurface(); m_tetrahedronActor->GetProperty()->LightingOn(); // Axes this->m_axesActor = vtkSmartPointer<vtkAxesActor>::New(); // VTK Renderer VTK_CREATE(vtkRenderer, ren); // Add Actor to renderer ren->AddActor(m_axesActor); ren->AddActor(m_meshActor); ren->AddActor(m_pointActor); ren->AddActor(m_tetrahedronActor); // VTK/Qt wedded this->ui->qvtkWidget->GetRenderWindow()->AddRenderer(ren); // Just a bit of Qt interest: Culling off the // point data and handing it to a vtkQtTableView //VTK_CREATE(vtkDataObjectToTable, toTable); //toTable->SetInputConnection(elevation->GetOutputPort()); //toTable->SetFieldType(vtkDataObjectToTable::POINT_DATA); // Here we take the end of the VTK pipeline and give it to a Qt View //this->m_tableView->SetRepresentationFromInputConnection(toTable->GetOutputPort()); // Set up action signals and slots connect(this->ui->actionOpenFile, SIGNAL(triggered()), this, SLOT(slotOpenFile())); connect(this->ui->actionExit, SIGNAL(triggered()), this, SLOT(slotExit())); m_connections = vtkEventQtSlotConnect::New(); this->m_connections->Connect(this->ui->qvtkWidget->GetRenderWindow()->GetInteractor(), vtkCommand::KeyPressEvent, this, SLOT(slotKeyPressed(vtkObject*, unsigned long, void*, void*)), 0, 1.0); // Create a PolyData buildMesh(); drawMesh(); drawPoint(); drawTetrahedron(); }; TetrahedronIntersection::~TetrahedronIntersection() { // The smart pointers should clean up for up } void TetrahedronIntersection::slotKeyPressed(vtkObject *, unsigned long, void *, void *) { vtkRenderWindowInteractor *rwi = this->ui->qvtkWidget->GetRenderWindow()->GetInteractor(); std::string key = rwi->GetKeySym(); // Output the key that was pressed //std::cout << "Pressed " << key << std::endl; if (key == "Right") { m_point.z() += 0.01; drawPoint(); drawTetrahedron(); this->ui->qvtkWidget->GetRenderWindow()->Render(); } else if (key == "Left") { m_point.z() -= 0.01; drawPoint(); drawTetrahedron(); this->ui->qvtkWidget->GetRenderWindow()->Render(); } else if (key == "r" || key == "R") { drawMesh(); drawPoint(); this->ui->qvtkWidget->GetRenderWindow()->Render(); } else if (key == "w" || key == "W") { vtkRenderer* ren = this->ui->qvtkWidget->GetRenderWindow()->GetRenderers()->GetFirstRenderer(); vtkActor* actor = ren->GetActors()->GetLastActor(); actor->GetProperty()->SetRepresentationToWireframe(); actor->GetProperty()->LightingOff(); this->ui->qvtkWidget->GetRenderWindow()->Render(); } else if (key == "s" || key == "S") { vtkRenderer* ren = this->ui->qvtkWidget->GetRenderWindow()->GetRenderers()->GetFirstRenderer(); vtkActor* actor = ren->GetActors()->GetLastActor(); actor->GetProperty()->SetRepresentationToSurface(); actor->GetProperty()->LightingOn(); this->ui->qvtkWidget->GetRenderWindow()->Render(); } } // Action to be taken upon file open void TetrahedronIntersection::slotOpenFile() { } void TetrahedronIntersection::slotExit() { qApp->exit(); } void TetrahedronIntersection::buildMesh() { std::vector<CMshNode<double> > sNodes; CMshNode<double> aNode1; CMshNode<double> aNode2; CMshNode<double> aNode3; CMshNode<double> aNode4; CMshNode<double> aNode5; CMshNode<double> aNode6; m_point << 0, 0, 0; aNode1 << 1.0, 0.875, 0.125; aNode2 << 0.875, 1.0, 0.125; aNode3 << 1.0, 1.0, 0.125; aNode4 << 1.0, 0.875, 0.25; aNode5 << 0.875, 1.0, 0.25; aNode6 << 1.0, 1.0, 0.25; sNodes.push_back(aNode1); sNodes.push_back(aNode2); sNodes.push_back(aNode3); sNodes.push_back(aNode4); sNodes.push_back(aNode5); sNodes.push_back(aNode6); for (unsigned int i = 0; i < sNodes.size(); ++i) { m_mesh.addNode(i + 1, sNodes[i]); m_point += sNodes[i]; } m_point /= sNodes.size(); CMshElement<double> anElement1(ET_TRIANGLE); CMshElement<double> anElement2(ET_TRIANGLE); CMshElement<double> anElement3(ET_TRIANGLE); CMshElement<double> anElement4(ET_TRIANGLE); CMshElement<double> anElement5(ET_TRIANGLE); CMshElement<double> anElement6(ET_TRIANGLE); CMshElement<double> anElement7(ET_TRIANGLE); CMshElement<double> anElement8(ET_TRIANGLE); // 1 - 2 5 3 anElement1.addNodeId(2); anElement1.addNodeId(5); anElement1.addNodeId(3); m_mesh.addElement(1, anElement1); // 2 - 1 3 6 anElement2.addNodeId(1); anElement2.addNodeId(3); anElement2.addNodeId(6); m_mesh.addElement(2, anElement2); // 3 - 3 5 6 anElement3.addNodeId(3); anElement3.addNodeId(5); anElement3.addNodeId(6); m_mesh.addElement(3, anElement3); // 4 - 1 6 4 anElement4.addNodeId(1); anElement4.addNodeId(6); anElement4.addNodeId(4); m_mesh.addElement(4, anElement4); // 5 - 6 5 4 anElement5.addNodeId(6); anElement5.addNodeId(5); anElement5.addNodeId(4); m_mesh.addElement(5, anElement5); // 6 - 3 1 2 anElement6.addNodeId(3); anElement6.addNodeId(1); anElement6.addNodeId(2); m_mesh.addElement(6, anElement6); // 7 - 4 5 2 anElement7.addNodeId(4); anElement7.addNodeId(5); anElement7.addNodeId(2); m_mesh.addElement(7, anElement7); // 8 - 1 4 2 anElement8.addNodeId(1); anElement8.addNodeId(4); anElement8.addNodeId(2); m_mesh.addElement(8, anElement8); } void TetrahedronIntersection::drawMesh() { VTK_CREATE(vtkPoints, points); for (Integer i = 0; i < m_mesh.nbNodes(); ++i) { Integer aNodeId = m_mesh.nodeId(i); CMshNode<double> aNode = m_mesh.node(aNodeId); points->InsertNextPoint(aNode.x(), aNode.y(), aNode.z()); } VTK_CREATE(vtkUnstructuredGrid, unstructuredGrid); unstructuredGrid->SetPoints(points); for (Integer i = 0; i < m_mesh.nbElements(); ++i) { Integer anElementId = m_mesh.elementId(i); CMshElement<double> anElement = m_mesh.element(anElementId); if (anElement.elementType() == ET_TRIANGLE) { vtkIdType ptIds[] = {static_cast<vtkIdType> (m_mesh.nodeIndex(anElement.nodeId(0))), static_cast<vtkIdType> (m_mesh.nodeIndex(anElement.nodeId(1))), static_cast<vtkIdType> (m_mesh.nodeIndex(anElement.nodeId(2)))}; unstructuredGrid->InsertNextCell(VTK_TRIANGLE, 3, ptIds); } } vtkMapper* mapper = m_meshActor->GetMapper(); (reinterpret_cast<vtkDataSetMapper* >(mapper))->SetInputData(unstructuredGrid); } void TetrahedronIntersection::drawPoint() { VTK_CREATE(vtkPoints, points); points->InsertNextPoint(m_point.x(), m_point.y(), m_point.z()); VTK_CREATE(vtkPolyData, pointsPolydata); pointsPolydata->SetPoints(points); VTK_CREATE(vtkVertexGlyphFilter, vertexFilter); vertexFilter->SetInputData(pointsPolydata); vertexFilter->Update(); // Setup colors unsigned char yellow[3] = {255, 255, 0}; VTK_CREATE(vtkUnsignedCharArray, colors); colors->SetNumberOfComponents(3); colors->SetName ("Colors"); colors->InsertNextTypedTuple(yellow); VTK_CREATE(vtkPolyData, polydata); polydata->ShallowCopy(vertexFilter->GetOutput()); polydata->GetPointData()->SetScalars(colors); vtkMapper* mapper = m_pointActor->GetMapper(); (reinterpret_cast<vtkPolyDataMapper* >(mapper))->SetInputData(polydata); } void TetrahedronIntersection::drawTetrahedron() { CGeoTetrahedron<double> aTetrahedron; for (unsigned int i = 0; i < 3; ++i) { unsigned int aNodeId = m_mesh.nodeId(i); CMshNode<double> aNode = m_mesh.node(aNodeId); CGeoCoordinate<double> aVertex = aNode; aTetrahedron.addVertex(aVertex); } CGeoCoordinate<double> aVertex = m_point; aTetrahedron.addVertex(aVertex); // Setup colors unsigned char activeColor[3]; unsigned char red[3] = {255, 0, 0}; unsigned char green[3] = {0, 255, 0}; activeColor[0] = green[0]; activeColor[1] = green[1]; activeColor[2] = green[2]; bool bOK = true; double tol = 1E-5; for (Integer i = 3; i < m_mesh.nbNodes(); ++i) { unsigned int aNodeId = m_mesh.nodeId(i); CMshNode<double> aNode = m_mesh.node(aNodeId); CGeoCoordinate<double> aPoint = aNode; if (aTetrahedron.contains(aPoint, tol)) { bOK = false; break; } } CGeoTriangle<double> aTriangle1; aTriangle1.addVertex(aTetrahedron.vertex(0)); aTriangle1.addVertex(aTetrahedron.vertex(1)); aTriangle1.addVertex(aTetrahedron.vertex(3)); CGeoTriangle<double> aTriangle2; aTriangle2.addVertex(aTetrahedron.vertex(1)); aTriangle2.addVertex(aTetrahedron.vertex(2)); aTriangle2.addVertex(aTetrahedron.vertex(3)); CGeoTriangle<double> aTriangle3; aTriangle3.addVertex(aTetrahedron.vertex(2)); <|fim▁hole|> aTriangle3.addVertex(aTetrahedron.vertex(3)); for (Integer i = 3; i < m_mesh.nbElements(); ++i) { Integer anElementId = m_mesh.elementId(i); CMshElement<double> anElement = m_mesh.element(anElementId); if (anElement.elementType() == ET_TRIANGLE) { CGeoTriangle<double> aTriangle; for (Integer j = 0; j < anElement.nbNodeIds(); ++j) { CGeoCoordinate<double> aVertex; aVertex = m_mesh.node(anElement.nodeId(j)); aTriangle.addVertex(aVertex); } CGeoIntersectionType anIntType; if (aTriangle.intersects(aTriangle1, anIntType, tol)) { if (anIntType == IT_INTERNAL) { bOK = false; break; } } if (aTriangle.intersects(aTriangle2, anIntType, tol)) { if (anIntType == IT_INTERNAL) { bOK = false; break; } } if (aTriangle.intersects(aTriangle3, anIntType, tol)) { if (anIntType == IT_INTERNAL) { bOK = false; break; } } } } if (!bOK) { activeColor[0] = red[0]; activeColor[1] = red[1]; activeColor[2] = red[2]; } if (bOK) std::cout << "Tetra: OK!" << std::endl; else std::cout << "Tetra: Not OK!" << std::endl; VTK_CREATE(vtkUnsignedCharArray, colors); colors->SetNumberOfComponents(3); colors->SetName("Colors"); VTK_CREATE(vtkPoints, points); for (unsigned int i = 0; i < 4; ++i) { CGeoCoordinate<double> aVertex = aTetrahedron.vertex(i); points->InsertNextPoint(aVertex.x(), aVertex.y(), aVertex.z()); colors->InsertNextTypedTuple(activeColor); } VTK_CREATE(vtkUnstructuredGrid, unstructuredGrid); unstructuredGrid->SetPoints(points); vtkIdType ptIds[] = {0, 1, 2, 3}; unstructuredGrid->InsertNextCell(VTK_TETRA, 4, ptIds); unstructuredGrid->GetPointData()->SetScalars(colors); vtkMapper* mapper = m_tetrahedronActor->GetMapper(); (reinterpret_cast<vtkDataSetMapper* >(mapper))->SetInputData(unstructuredGrid); }<|fim▁end|>
aTriangle3.addVertex(aTetrahedron.vertex(0));
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.db import models from django.contrib.auth.models import User # Create your models here. class Greeting(models.Model): when = models.DateTimeField('date created', auto_now_add=True) class Material(models.Model): name = models.CharField(max_length=200) price = models.FloatField(blank=True, null=True) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) def __unicode__(self): return self.name def __str__(self): return self.name class Bunch(models.Model): user = models.ForeignKey(User) material = models.ForeignKey(Material) created = models.DateTimeField(auto_now_add=True)<|fim▁hole|> contact = models.CharField(max_length=255)<|fim▁end|>
modified = models.DateTimeField(auto_now=True) image = models.ImageField(upload_to="bunches") pounds = models.FloatField(blank=True, null=True)
<|file_name|>app.po.ts<|end_file_name|><|fim▁begin|>import { browser, element, by } from 'protractor'; export class NgMaterialSeed2Page { navigateTo() { return browser.get('/'); } getParagraphText() {<|fim▁hole|> return element(by.css('.header-headline h1')).getText(); } }<|fim▁end|>
<|file_name|>lru_cache_unittest.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import unittest from webkitpy.common import lru_cache class LRUCacheTest(unittest.TestCase): def setUp(self): self.lru = lru_cache.LRUCache(3) self.lru['key_1'] = 'item_1' self.lru['key_2'] = 'item_2' self.lru['key_3'] = 'item_3' self.lru2 = lru_cache.LRUCache(1) self.lru2['key_1'] = 'item_1' def test_items(self): self.assertEqual(set(self.lru.items()), set([('key_1', 'item_1'), ('key_3', 'item_3'), ('key_2', 'item_2')])) def test_put(self): self.lru['key_4'] = 'item_4' self.assertEqual(set(self.lru.items()), set([('key_4', 'item_4'), ('key_3', 'item_3'), ('key_2', 'item_2')])) def test_update(self): self.lru['key_1'] self.lru['key_5'] = 'item_5' self.assertEqual(set(self.lru.items()), set([('key_1', 'item_1'), ('key_3', 'item_3'), ('key_5', 'item_5')])) def test_keys(self): self.assertEqual(set(self.lru.keys()), set(['key_1', 'key_2', 'key_3'])) def test_delete(self): del self.lru['key_1'] self.assertFalse('key_1' in self.lru) def test_contain(self): self.assertTrue('key_1' in self.lru) self.assertFalse('key_4' in self.lru) def test_values(self): self.assertEqual(set(self.lru.values()), set(['item_1', 'item_2', 'item_3'])) <|fim▁hole|> def test_size_one_pop(self): self.lru2['key_2'] = 'item_2' self.assertEqual(self.lru2.keys(), ['key_2']) def test_size_one_delete(self): del self.lru2['key_1'] self.assertFalse('key_1' in self.lru2) def test_pop_error(self): self.assertRaises(KeyError, self.lru2.__getitem__, 'key_2') del self.lru2['key_1'] self.assertRaises(KeyError, self.lru2.__getitem__, 'key_2') def test_get_middle_item(self): self.lru['key_2'] self.lru['key_4'] = 'item_4' self.lru['key_5'] = 'item_5' self.assertEqual(set(self.lru.keys()), set(['key_2', 'key_4', 'key_5'])) def test_set_again(self): self.lru['key_1'] = 'item_4' self.assertEqual(set(self.lru.items()), set([('key_1', 'item_4'), ('key_3', 'item_3'), ('key_2', 'item_2')])) if __name__ == "__main__": unittest.main()<|fim▁end|>
def test_len(self): self.assertEqual(len(self.lru), 3)
<|file_name|>webpack.test.js<|end_file_name|><|fim▁begin|>/** * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const path = require('path'); const webpack = require('webpack'); module.exports = { devtool: 'source-map', module: { rules: [ { test: /\.tsx?$/, exclude: /node_modules/, use: 'ts-loader' }, { test: /\.[tj]sx?$/, use: 'source-map-loader', enforce: 'pre' }, { test: /\.tsx?$/, use: { loader: 'istanbul-instrumenter-loader', options: { esModules: true } }, enforce: 'post', include: path.resolve(process.cwd(), 'src') } ] }, resolve: {<|fim▁hole|>};<|fim▁end|>
modules: ['node_modules', path.resolve(__dirname, '../../node_modules')], extensions: ['.js', '.ts'] }
<|file_name|>index.d.ts<|end_file_name|><|fim▁begin|>import type AjvCore from "../core"; import type { AnyValidateFunction } from "../types"; export default function standaloneCode(ajv: AjvCore, refsOrFunc?: {<|fim▁hole|><|fim▁end|>
[K in string]?: string; } | AnyValidateFunction): string;
<|file_name|>CounterActionTypes.js<|end_file_name|><|fim▁begin|><|fim▁hole|>export const INCREMENT_COUNTER = 'INCREMENT_COUNTER' export const DECREMENT_COUNTER = 'DECREMENT_COUNTER'<|fim▁end|>
<|file_name|>change_request.py<|end_file_name|><|fim▁begin|># Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document <|fim▁hole|>class ChangeRequest(Document): pass<|fim▁end|>
<|file_name|>FeaturedCollectionsRails.test.tsx<|end_file_name|><|fim▁begin|>import { CollectionHubFixture } from "Apps/__tests__/Fixtures/Collections" import { useTracking } from "Artsy/Analytics/useTracking" import { ArrowButton } from "Components/Carousel" import { mount } from "enzyme" import "jest-styled-components" import React from "react" import {<|fim▁hole|>} from "../index" jest.mock("Artsy/Analytics/useTracking") jest.mock("found", () => ({ Link: ({ children, ...props }) => <div {...props}>{children}</div>, RouterContext: jest.requireActual("found").RouterContext, })) describe("FeaturedCollectionsRails", () => { let props const trackEvent = jest.fn() beforeEach(() => { props = { collectionGroup: CollectionHubFixture.linkedCollections[1], } ;(useTracking as jest.Mock).mockImplementation(() => { return { trackEvent, } }) }) const memberData = () => { return { description: "<p>From SpongeBob SquarePants to Snoopy, many beloved childhood cartoons have made an impact on the history of art.</p>", price_guidance: 60, slug: "art-inspired-by-cartoons", thumbnail: "http://files.artsy.net/images/cartoons_thumbnail.png", title: "Art Inspired by Cartoons", } } it("Renders expected fields", () => { const component = mount(<FeaturedCollectionsRails {...props} />) expect(component.text()).toMatch("Featured Collections") expect(component.text()).toMatch("Art Inspired by Cartoons") expect(component.text()).toMatch("Street Art: Celebrity Portraits") expect(component.text()).toMatch("Street Art: Superheroes and Villains") }) describe("Tracking", () => { it("Tracks arrow click", () => { props.collectionGroup.members = [ memberData(), memberData(), memberData(), memberData(), memberData(), ] const component = mount(<FeaturedCollectionsRails {...props} />) component .find(ArrowButton) .at(1) .simulate("click") expect(trackEvent).toBeCalledWith({ action_type: "Click", context_page: "Collection", context_module: "FeaturedCollectionsRail", context_page_owner_type: "Collection", type: "Button", subject: "clicked next button", }) }) }) }) describe("FeaturedCollectionEntity", () => { let props const trackEvent = jest.fn() const memberDataWithoutPriceGuidance = () => { return { description: "<p>From SpongeBob SquarePants to Snoopy, many beloved childhood cartoons have made an impact on the history of art.</p>", price_guidance: null, slug: "art-inspired-by-cartoons", thumbnail: "http://files.artsy.net/images/cartoons_thumbnail.png", title: "Art Inspired by Cartoons", } } beforeEach(() => { props = { collectionGroup: CollectionHubFixture.linkedCollections[1], } ;(useTracking as jest.Mock).mockImplementation(() => { return { trackEvent, } }) }) it("Renders expected fields for FeaturedCollectionEntity", () => { const component = mount(<FeaturedCollectionsRails {...props} />) const firstEntity = component.find(FeaturedCollectionEntity).at(0) expect(firstEntity.text()).toMatch("From SpongeBob SquarePants to Snoopy") expect(firstEntity.text()).toMatch("From $60") const featuredImage = component.find(FeaturedImage).at(0) expect(featuredImage.getElement().props.src).toContain( "cartoons_thumbnail.png&width=500&height=500&quality=80" ) }) it("Does not renders price guidance for FeaturedCollectionEntity when it is null", () => { props.collectionGroup.members = [memberDataWithoutPriceGuidance()] const component = mount(<FeaturedCollectionsRails {...props} />) const firstEntity = component.find(FeaturedCollectionEntity).at(0) expect(firstEntity.text()).not.toContain("From $") }) it("Tracks collection entity click", () => { const { members } = props.collectionGroup const component = mount( <FeaturedCollectionEntity member={members[0]} itemNumber={0} /> ) component .find(StyledLink) .at(0) .simulate("click") expect(trackEvent).toBeCalledWith({ action_type: "Click", context_page: "Collection", context_module: "FeaturedCollectionsRail", context_page_owner_type: "Collection", type: "thumbnail", destination_path: "undefined/collection/art-inspired-by-cartoons", item_number: 0, }) }) })<|fim▁end|>
FeaturedCollectionEntity, FeaturedCollectionsRails, FeaturedImage, StyledLink,
<|file_name|>FileZillaEngine.cpp<|end_file_name|><|fim▁begin|>// FileZillaEngine.cpp: Implementierung der Klasse CFileZillaEngine. // ////////////////////////////////////////////////////////////////////// #include <filezilla.h> #include "ControlSocket.h" #include "directorycache.h" #include "engineprivate.h" CFileZillaEngine::CFileZillaEngine(CFileZillaEngineContext& engine_context) : impl_(new CFileZillaEnginePrivate(engine_context, *this)) { } CFileZillaEngine::~CFileZillaEngine() { delete impl_; } <|fim▁hole|>{ return impl_->Init(pEventHandler); } int CFileZillaEngine::Execute(const CCommand &command) { return impl_->Execute(command); } std::unique_ptr<CNotification> CFileZillaEngine::GetNextNotification() { return impl_->GetNextNotification(); } bool CFileZillaEngine::SetAsyncRequestReply(std::unique_ptr<CAsyncRequestNotification> && pNotification) { return impl_->SetAsyncRequestReply(std::move(pNotification)); } bool CFileZillaEngine::IsPendingAsyncRequestReply(std::unique_ptr<CAsyncRequestNotification> const& pNotification) { return impl_->IsPendingAsyncRequestReply(pNotification); } bool CFileZillaEngine::IsActive(enum CFileZillaEngine::_direction direction) { return CFileZillaEnginePrivate::IsActive(direction); } CTransferStatus CFileZillaEngine::GetTransferStatus(bool &changed) { return impl_->GetTransferStatus(changed); } int CFileZillaEngine::CacheLookup(const CServerPath& path, CDirectoryListing& listing) { return impl_->CacheLookup(path, listing); } int CFileZillaEngine::Cancel() { return impl_->Cancel(); } bool CFileZillaEngine::IsBusy() const { return impl_->IsBusy(); } bool CFileZillaEngine::IsConnected() const { return impl_->IsConnected(); }<|fim▁end|>
int CFileZillaEngine::Init(wxEvtHandler *pEventHandler)
<|file_name|>mysql_time_test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python from absl import app from absl.testing import absltest from grr_response_server.databases import db_time_test from grr_response_server.databases import mysql_test from grr.test_lib import test_lib class MysqlClientsTest(db_time_test.DatabaseTimeTestMixin, mysql_test.MysqlTestBase, absltest.TestCase): pass<|fim▁hole|>if __name__ == "__main__": app.run(test_lib.main)<|fim▁end|>
<|file_name|>007_add_ipv6_to_fixed_ips.py<|end_file_name|><|fim▁begin|># Copyright 2011 OpenStack LLC # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from sqlalchemy import Column, Integer, MetaData, String, Table meta = MetaData() # Table stub-definitions # Just for the ForeignKey and column creation to succeed, these are not the # actual definitions of instances or services. # fixed_ips = Table( "fixed_ips", meta, Column( "id", Integer(), primary_key=True, nullable=False)) # # New Tables # # None # # Tables to alter # # None # # Columns to add to existing tables # fixed_ips_addressV6 = Column( "addressV6", String( length=255, convert_unicode=False, assert_unicode=None, unicode_error=None, _warn_on_bytestring=False)) fixed_ips_netmaskV6 = Column( "netmaskV6", String( length=3, convert_unicode=False, assert_unicode=None, unicode_error=None, _warn_on_bytestring=False)) fixed_ips_gatewayV6 = Column( "gatewayV6", String( length=255, convert_unicode=False, assert_unicode=None, unicode_error=None, _warn_on_bytestring=False))<|fim▁hole|> # bind migrate_engine to your metadata meta.bind = migrate_engine # Add columns to existing tables fixed_ips.create_column(fixed_ips_addressV6) fixed_ips.create_column(fixed_ips_netmaskV6) fixed_ips.create_column(fixed_ips_gatewayV6)<|fim▁end|>
def upgrade(migrate_engine): # Upgrade operations go here. Don't create your own engine;
<|file_name|>api_fields.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import unicode_literals from udata.api import api, fields, base_reference from udata.core.badges.api import badge_fields from udata.core.dataset.api_fields import dataset_ref_fields from udata.core.organization.api_fields import org_ref_fields from udata.core.user.api_fields import user_ref_fields from .models import REUSE_TYPES, IMAGE_SIZES BIGGEST_IMAGE_SIZE = IMAGE_SIZES[0] reuse_fields = api.model('Reuse', { 'id': fields.String(description='The reuse identifier', readonly=True), 'title': fields.String(description='The reuse title', required=True), 'slug': fields.String( description='The reuse permalink string', readonly=True), 'type': fields.String( description='The reuse type', required=True, enum=REUSE_TYPES.keys()), 'url': fields.String( description='The reuse remote URL (website)', required=True), 'description': fields.Markdown( description='The reuse description in Markdown', required=True), 'tags': fields.List( fields.String, description='Some keywords to help in search'), 'badges': fields.List(fields.Nested(badge_fields), description='The reuse badges', readonly=True), 'featured': fields.Boolean( description='Is the reuse featured', readonly=True), 'private': fields.Boolean( description='Is the reuse private to the owner or the organization'), 'image': fields.ImageField(description='The reuse thumbnail thumbnail (cropped) URL'), 'image_thumbnail': fields.ImageField(attribute='image', size=BIGGEST_IMAGE_SIZE, description='The reuse thumbnail thumbnail URL. This is the square ' '({0}x{0}) and cropped version.'.format(BIGGEST_IMAGE_SIZE)), 'created_at': fields.ISODateTime( description='The reuse creation date', readonly=True), 'last_modified': fields.ISODateTime( description='The reuse last modification date', readonly=True), 'deleted': fields.ISODateTime( description='The organization identifier', readonly=True), 'datasets': fields.List( fields.Nested(dataset_ref_fields), description='The reused datasets'), 'organization': fields.Nested( org_ref_fields, allow_null=True, description='The publishing organization', readonly=True), 'owner': fields.Nested( user_ref_fields, description='The owner user', readonly=True, allow_null=True), 'metrics': fields.Raw(description='The reuse metrics', readonly=True), 'uri': fields.UrlFor( 'api.reuse', lambda o: {'reuse': o}, description='The reuse API URI', readonly=True), 'page': fields.UrlFor( 'reuses.show', lambda o: {'reuse': o}, description='The reuse page URL', readonly=True), }) reuse_page_fields = api.model('ReusePage', fields.pager(reuse_fields)) reuse_suggestion_fields = api.model('ReuseSuggestion', { 'id': fields.String(description='The reuse identifier', readonly=True), 'title': fields.String(description='The reuse title', readonly=True),<|fim▁hole|> 'reuses.show_redirect', lambda o: {'reuse': o['slug']}, description='The reuse page URL', readonly=True), 'score': fields.Float( description='The internal match score', readonly=True), }) reuse_ref_fields = api.inherit('ReuseReference', base_reference, { 'title': fields.String(description='The reuse title', readonly=True), 'image': fields.ImageField(description='The reuse thumbnail thumbnail (cropped) URL'), 'image_thumbnail': fields.ImageField(attribute='image', size=BIGGEST_IMAGE_SIZE, description='The reuse thumbnail thumbnail URL. This is the square ' '({0}x{0}) and cropped version.'.format(BIGGEST_IMAGE_SIZE)), 'uri': fields.UrlFor( 'api.reuse', lambda o: {'reuse': o}, description='The reuse API URI', readonly=True), 'page': fields.UrlFor( 'reuses.show', lambda o: {'reuse': o}, description='The reuse page URL', readonly=True), }) reuse_type_fields = api.model('ReuseType', { 'id': fields.String(description='The reuse type identifier'), 'label': fields.String(description='The reuse type display name') })<|fim▁end|>
'slug': fields.String( description='The reuse permalink string', readonly=True), 'image_url': fields.String(description='The reuse thumbnail URL'), 'page': fields.UrlFor(
<|file_name|>libwlanplugin.ts<|end_file_name|><|fim▁begin|><!DOCTYPE TS><TS> <defaultcodec>iso8859-1</defaultcodec> <context> <name>WLAN</name> <message> <source>Wireless Configuration</source> <translation>Configuration &quot;sans fils&quot;</translation> </message> <message> <source>General</source> <translation>Général</translation> </message> <message> <source>Mode</source> <translation>Mode</translation> </message><|fim▁hole|> <message> <source>MAC</source> <translation>MAC</translation> </message> <message> <source>Specify &amp;Access Point</source> <translation>Spécifier le point d&apos;&amp;accès</translation> </message> <message> <source>Specify &amp;Channel</source> <translation>Spécifier le &amp;canal</translation> </message> <message> <source>Auto</source> <translation>Auto</translation> </message> <message> <source>Managed</source> <translation>Géré</translation> </message> <message> <source>Ad-Hoc</source> <translation>Ad-Hoc</translation> </message> <message> <source>any</source> <translation>any</translation> </message> <message> <source>Encryption</source> <translation>Cryptage</translation> </message> <message> <source>&amp;Enable Encryption</source> <translation>Activ&amp;er le cryptage</translation> </message> <message> <source>&amp;Key Setting</source> <translation>Paramètres des &amp;clés</translation> </message> <message> <source>Key &amp;1</source> <translation>Clé &amp;1</translation> </message> <message> <source>Key &amp;2</source> <translation>Clé &amp;2</translation> </message> <message> <source>Key &amp;3</source> <translation>Clé &amp;3</translation> </message> <message> <source>Key &amp;4</source> <translation>Clé &amp;4</translation> </message> <message> <source>Non-encrypted Packets</source> <translation>Paquets non cryptés</translation> </message> <message> <source>&amp;Accept</source> <translation>&amp;Accepter</translation> </message> <message> <source>&amp;Reject</source> <translation>&amp;Rejeter</translation> </message> </context> <context> <name>WlanInfo</name> <message> <source>Interface Information</source> <translation>Information sur l&apos;interface</translation> </message> <message> <source>802.11b</source> <translation>802.11b</translation> </message> <message> <source>Channel</source> <translation>Canal</translation> </message> <message> <source>Mode</source> <translation>Mode</translation> </message> <message> <source>ESSID</source> <translation>ESSID</translation> </message> <message> <source>Station</source> <translation>Station</translation> </message> <message> <source>AP</source> <translation>AP</translation> </message> <message> <source>Rate</source> <translation>Taux</translation> </message> <message> <source>Quality</source> <translation>Qualité</translation> </message> <message> <source>Noise</source> <translation>Bruit</translation> </message> <message> <source>Signal</source> <translation>Signal</translation> </message> </context> </TS><|fim▁end|>
<message> <source>ESS-ID</source> <translation>ESS-ID</translation> </message>
<|file_name|>extfsTest.js<|end_file_name|><|fim▁begin|>var expect = require('expect.js'); var path = require('path'); var fs = require('../extfs'); describe('extfs', function () { var rootPath = path.join(__dirname, '../'); it('should return all directories', function (done) { fs.getDirs(rootPath, function (err, dirs) { expect(dirs).to.be.an(Array); expect(dirs.length).to.be.greaterThan(0); done(); }); }); it('should return all directories sync', function () { var dirs = fs.getDirsSync(rootPath); expect(dirs).to.be.an(Array); expect(dirs.length > 0).to.be.ok(); }); it('should check if a file is empty', function (done) { var notEmptyFile = path.join(__dirname, '../README.md'); var emptyFile = './AN EMPTY FILE'; fs.isEmpty(notEmptyFile, function (empty) { expect(empty).to.be(false); fs.isEmpty(emptyFile, function (empty) { expect(empty).to.be(true); done(); }); }); }); it('should check if a file is empty sync', function () { var notEmptyFile = path.join(__dirname, '../README.md'); var emptyFile = './AN EMPTY FILE'; var empty = fs.isEmptySync(notEmptyFile); expect(empty).to.be(false); empty = fs.isEmptySync(emptyFile); expect(empty).to.be(true); }); it('should check if a directory is empty', function (done) { var notEmptyDir = __dirname; var emptyDir = './AN EMPTY DIR'; fs.isEmpty(notEmptyDir, function (empty) { expect(empty).to.be(false); fs.isEmpty(emptyDir, function (empty) { expect(empty).to.be(true); done(); }) }); }); it('should check if a directory is empty sync', function () { var notEmptyDir = __dirname; var emptyDir = './AN EMPTY DIR'; expect(fs.isEmptySync(notEmptyDir)).to.be(false); expect(fs.isEmptySync(emptyDir)).to.be(true); }); describe('remove directories', function () {<|fim▁hole|> var tmpPath = path.join(rootPath, 'tmp'); var folders = [ 'folder1', 'folder2', 'folder3' ]; var files = [ '1.txt', '2.txt', '3.txt' ]; folders = folders.map(function (folder) { return path.join(tmpPath, folder); }); /** * Create 3 folders with 3 files each */ beforeEach(function () { if (!fs.existsSync(tmpPath)) { fs.mkdirSync(tmpPath, '0755'); } folders.forEach(function (folder) { if (!fs.existsSync(folder)) { fs.mkdirSync(folder, '0755'); } files.forEach(function (file) { fs.writeFile(path.join(folder, file), 'file content'); }); }); }); it('should remove a non empty directory', function (done) { fs.remove(tmpPath, function (err) { expect(err).to.be(null); expect(fs.existsSync(tmpPath)).to.be(false); done(); }); }); it('should remove a non empty directory synchronously', function () { fs.removeSync(tmpPath); expect(fs.existsSync(tmpPath)).to.be(false); }); it('should remove an array of directories', function (done) { fs.remove(folders, function (err) { expect(err).to.be(null); expect(fs.existsSync(folders[0])).to.be(false); expect(fs.existsSync(folders[1])).to.be(false); expect(fs.existsSync(folders[2])).to.be(false); expect(fs.existsSync(tmpPath)).to.be(true); done(); }); }); it('should remove an array of directories synchronously', function () { fs.removeSync(folders); expect(fs.existsSync(folders[0])).to.be(false); expect(fs.existsSync(folders[1])).to.be(false); expect(fs.existsSync(folders[2])).to.be(false); expect(fs.existsSync(tmpPath)).to.be(true); }); }); it('should extends to fs', function () { expect(fs.readdir).to.be.a(Function); }); });<|fim▁end|>
<|file_name|>test_Read.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python """test_Read.py to test the Read class. Requires: python 2 (https://www.python.org/downloads/) nose 1.3 (https://nose.readthedocs.org/en/latest/) Joy-El R.B. Talbot Copyright (c) 2014 The MIT License (MIT) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from nose.tools import raises from Read import Read from MetageneError import MetageneError ##TODO: test set_sam_tag method ##TODO: test set_chromosome_sizes cigar_string = {} bad_cigar_string = {} bitwise_flag = {} bad_bitwise_flag = {} good_input = {} bad_input = {} chromosome_conversion = {"1": "chr1", "2": "chr2"} def setup(): """Create fixtures""" # define cigar strings; value: ((args for build_positions), expected_result) cigar_string['full_match'] = ((1, "10M", "*"), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) cigar_string['insertion'] = ((1, "5M4I5M", "*"), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) cigar_string['deletion'] = ((1, "5M4D5M", "*"), [1, 2, 3, 4, 5, 10, 11, 12, 13, 14]) cigar_string['gapped_match'] = ((1, "5M3N5M", "*"), [1, 2, 3, 4, 5, 9, 10, 11, 12, 13]) cigar_string['softclipped_match'] = ((4, "3S5M", "*"), [4, 5, 6, 7, 8]) cigar_string['hardclipped_match'] = ((4, "3H5M3H", "*"), [4, 5, 6, 7, 8]) cigar_string['padded_match'] = ((1, "3P5M", "*"), [4, 5, 6, 7, 8]) cigar_string['mismatch'] = ((1, "5=1X3=", "*"), [1, 2, 3, 4, 5, 6, 7, 8, 9]) cigar_string['no_cigar_match'] = ((1, "*", "aaaaa"), [1, 2, 3, 4, 5]) bad_cigar_string['unknown_length'] = ((1, "*", "*"), "raise MetageneError") bad_cigar_string['illegal_cigar'] = ((1, "5M4B", "*"), "raise MetageneError") bad_cigar_string['misordered_cigar'] = ((1, "M5N4M5", "*"), "raise MetageneError") # define bitwise flags; value: ((args for parse_sam_bitwise_flag), expected_result(count?, reverse_complemented?)) bitwise_flag['unmapped'] = ((int("0b000000000100", 2),), (False, False)) bitwise_flag['unmapped_withflags'] = ((int("0b100111011101", 2),), (False, True)) bitwise_flag['plus_strand'] = ((int("0b000000000000", 2),), (True, False)) bitwise_flag['minus_strand'] = ((int("0b000000010000", 2),), (True, True)) bitwise_flag['multiple_segments'] = ((int("0b000000000001", 2),), (True, False)) # try various default and user-changed boolean flags bitwise_flag['count_secondary_alignment'] = ((int("0b000100000000", 2),), (True, False)) bitwise_flag['skip_secondary_alignment'] = ( (int("0b000100000000", 2), False, False, False, True, False, False), (False, False)) bitwise_flag['skip_failed_quality_control'] = ((int("0b001000000000", 2),), (False, False)) bitwise_flag['count_failed_quality_control'] = ( (int("0b001000000000", 2), True, True, False, True, False, False), (True, False)) bitwise_flag['skip_PCR_optical_duplicate'] = ((int("0b010000000000", 2),), (False, False)) bitwise_flag['count_PCR_optical_duplicate'] = ( (int("0b010000000000", 2), True, False, True, True, False, False), (True, False)) bitwise_flag['count_supplementary_alignment'] = ((int("0b100000000000", 2),), (True, False)) bitwise_flag['skip_supplementary_alignment'] = ( (int("0b100000000000", 2), True, False, False, False, False, False), (False, False)) bitwise_flag['count_only_start_success'] = ( (int("0b000001000001", 2), True, False, False, True, True, False), (True, False)) bitwise_flag['count_only_start_fail'] = ( (int("0b000000000001", 2), True, False, False, True, True, False), (False, False)) bitwise_flag['count_only_end_success'] = ( (int("0b000010000001", 2), True, False, False, True, False, True), (True, False)) bitwise_flag['count_only_end_fail'] = ( (int("0b000000000001", 2), True, False, False, True, False, True), (False, False)) bad_bitwise_flag['count_only_both'] = ( (int("0b000011000001", 2), True, False, False, True, True, True), ("Raise MetageneError",)) # define good and bad samline inputs good_input['no_tags'] = (0, "chr1", 200, "10M", 10, 1, 1, "+") good_input['plus_strand_match'] = (0, "chr1", 200, "10M", 10, 2, 4, "+") good_input['minus_strand_match'] = (16, "chr1", 200, "10M", 10, 2, 4, "-") good_input['no_match'] = (4, "*", 0, "*", 10, 1, 1, ".") sample = ["NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4"] Read.process_set_sam_tag(sample, count_tag=True, tag_regex='NA:i:(\d+)') Read.process_set_sam_tag(sample, count_tag=True, tag_regex='NH:i:(\d+)') def test_build_positions(): for test in cigar_string: yield (check_build_positions, test, cigar_string[test]) def check_build_positions(test, (values, expected)): position_array = Read.build_positions(*values) test_description = "\nTest: \t{}\n".format(test) test_description += "Expected:\t{}\n".format(expected) test_description += "Position:\t{}\n".format(position_array) assert position_array == expected, "{}Error: \tDid not create the expected position array.".format( test_description) def test_catch_bad_cigar_input(): for test in bad_cigar_string: yield (check_catch_bad_cigar_input, test, bad_cigar_string[test]) @raises(MetageneError) def check_catch_bad_cigar_input(test, (values, expected)): print Read.build_positions(*values) def test_parse_sam_bitwise_flag(): for test in bitwise_flag: yield (check_parse_sam_bitwise_flag, test, bitwise_flag[test]) def check_parse_sam_bitwise_flag(test, (values, expected)): bitwise_result = Read.parse_sam_bitwise_flag(*values) test_description = "\nTest: \t{}\n".format(test) test_description += "Expected:\t{}\n".format(expected) test_description += "Position:\t{}\n".format(bitwise_result) assert bitwise_result == expected, "{}Error: \tDid not parse bitwise flag as expected.".format(test_description) def test_catch_bad_bitwise_input(): for test in bad_bitwise_flag:<|fim▁hole|>@raises(MetageneError) def check_catch_bad_bitwise_input(test, (values, expected)): print Read.parse_sam_bitwise_flag(*values) def build_samline(bitcode, chromosome, start, cigar, length, abundance, mappings): """Return a SAM format line""" string = "a" * length return "read\t{}\t{}\t{}\t255\t{}\t*\t0\t0\t{}\t{}\tNH:i:{}\tNA:i:{}".format( bitcode, chromosome, start, cigar, string, string, mappings, abundance) def test_create_read(): for test in good_input: yield (check_create_read, test, good_input[test]) def check_create_read(test, values): # create expected result if int(values[0]) == 4: expected = "Non-aligning read" else: start = int(values[2]) end = int(values[2]) + int(values[4]) - 1 if values[7] == "-": start = end end = int(values[2]) expected = "Read at {0}:{1}-{2} on {3} strand; counts for {4:2.3f}:".format( values[1], # chromosome start, end, values[7], # strand float(values[5]) / float(values[6])) # abundance / mappings # build input to test samline = build_samline(*values[0:-1]) # exclude final value (created, read) = Read.create_from_sam(samline, chromosome_conversion.values(), count_method='all') output = str(read).split("\t")[0] # create description in case test fails test_description = "\nTest: \t{}\n".format(test) test_description += "Abundance:\t{}\n".format(Read.has_sam_tag["NA"]) test_description += "Mappings:\t{}\n".format(Read.has_sam_tag["NH"]) test_description += "Sam Line:\t{}\n".format(samline) test_description += "Expected:\t{}\n".format(expected) test_description += "Position:\t{}\n".format(output) assert output == expected, "{}Error: \tDid not create expected read.".format(test_description) def test_catch_bad_input(): for test in bad_input: yield (check_catch_bad_input, test, bad_input[test]) @raises(MetageneError) def check_catch_bad_input(test, samline): print Read(sam_line)<|fim▁end|>
yield (check_catch_bad_bitwise_input, test, bad_bitwise_flag[test])
<|file_name|>run.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # This file is part of VoltDB. # Copyright (C) 2008-2016 VoltDB Inc. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to<|fim▁hole|># The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. from subprocess import * def run(procs, threadsPerProc, workload): results = [] totalThroughput = 0.0 output = Popen(['./throughput', str(procs), str(threadsPerProc), workload], stdout=PIPE).communicate()[0] lines = output.split('\n') for line in lines: if line.startswith('RESULT: '): print line line = line.split(' ')[1] parts = line.split(',') results += [float(parts[2])] for r in results: totalThroughput += r print "--" print "PER THREAD AVG: " + str(totalThroughput / (procs * threadsPerProc)) print "PER PROC AVG: " + str(totalThroughput / procs) print "TOTAL THROUGHPUT: " + str(totalThroughput) print "--" run(1, 1, 'r') run(1, 2, 'r') run(1, 3, 'r') run(1, 4, 'r')<|fim▁end|>
# the following conditions: #
<|file_name|>test_logistic_dist.cpp<|end_file_name|><|fim▁begin|>// Copyright 2008 Gautam Sewani // Copyright 2013 Paul A. Bristow // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt // or copy at http://www.boost.org/LICENSE_1_0.txt) #ifdef _MSC_VER # pragma warning (disable : 4127) // conditional expression is constant. # pragma warning (disable : 4512) // assignment operator could not be generated. #endif #include <boost/config.hpp> #ifndef BOOST_NO_EXCEPTIONS #define BOOST_MATH_UNDERFLOW_ERROR_POLICY throw_on_error #define BOOST_MATH_OVERFLOW_ERROR_POLICY throw_on_error #endif #include <boost/math/tools/test.hpp> #include <boost/math/concepts/real_concept.hpp> // for real_concept #include <boost/math/distributions/logistic.hpp> using boost::math::logistic_distribution; #define BOOST_TEST_MAIN #include <boost/test/unit_test.hpp> // Boost.Test #include <boost/test/floating_point_comparison.hpp> #include "test_out_of_range.hpp" #include <iostream> using std::cout; using std::endl; using std::setprecision; template <class RealType> void test_spot(RealType location, RealType scale, RealType x, RealType p, RealType q, RealType tolerance) { BOOST_CHECK_CLOSE( ::boost::math::cdf( logistic_distribution<RealType>(location,scale), x), p, tolerance); // % BOOST_CHECK_CLOSE( ::boost::math::cdf( complement(logistic_distribution<RealType>(location,scale), x)), q, tolerance); // % if(p < 0.999) { BOOST_CHECK_CLOSE( ::boost::math::quantile( logistic_distribution<RealType>(location,scale), p), x, tolerance); // % } if(q < 0.999) { BOOST_CHECK_CLOSE( ::boost::math::quantile( complement(logistic_distribution<RealType>(location,scale), q)), x, 2 * tolerance); // % } } template <class RealType> void test_spots(RealType T) { // Basic sanity checks. // 50 eps as a percentage, up to a maximum of double precision // Test data taken from Mathematica 6 RealType tolerance = (std::max)( static_cast<RealType>(1e-33L), boost::math::tools::epsilon<RealType>()); cout<<"Absolute tolerance:"<<tolerance<<endl; tolerance *= 50 * 100; // # pragma warning(disable: 4100) // unreferenced formal parameter. // prevent his spurious warning. if (T != 0) { cout << "Expect parameter T == 0!" << endl; } cout << "Tolerance for type " << typeid(T).name() << " is " << tolerance << " %" << endl; test_spot( static_cast<RealType>(1), // location static_cast<RealType>(0.5L), // scale static_cast<RealType>(0.1L), // x static_cast<RealType>(0.141851064900487789594278108470953L), // p static_cast<RealType>(0.858148935099512210405721891529047L), //q tolerance); test_spot( static_cast<RealType>(5), // location static_cast<RealType>(2), // scale static_cast<RealType>(3.123123123L),//x static_cast<RealType>(0.281215878622547904873088053477813L), // p static_cast<RealType>(0.718784121377452095126911946522187L), //q tolerance); test_spot( static_cast<RealType>(1.2345L), // location static_cast<RealType>(0.12345L), // scale static_cast<RealType>(3.123123123L),//x static_cast<RealType>(0.999999773084685079723328282229357L), // p static_cast<RealType>(2.26915314920276671717770643005212e-7L), //q tolerance); //High probability test_spot( static_cast<RealType>(1), // location static_cast<RealType>(0.5L), // scale static_cast<RealType>(10), // x static_cast<RealType>(0.99999998477002048723965105559179L), // p static_cast<RealType>(1.5229979512760348944408208801237e-8L), //q tolerance); //negative x test_spot( static_cast<RealType>(5), // location static_cast<RealType>(2), // scale static_cast<RealType>(-0.1L), // scale static_cast<RealType>(0.0724264853615177178439235061476928L), // p static_cast<RealType>(0.927573514638482282156076493852307L), //q tolerance); <|fim▁hole|> static_cast<RealType>(-20), // x static_cast<RealType>(3.72663928418656138608800947863869e-6L), // p static_cast<RealType>(0.999996273360715813438613911990521L), //q tolerance); // Test value to check cancellation error in straight/complemented quantile. // The subtraction in the formula location-scale*log term introduces catastrophic // cancellation error if location and scale*log term are close. // For these values, the tests fail at tolerance, but work at 100*tolerance. test_spot( static_cast<RealType>(-1.2345L), // location static_cast<RealType>(1.4555L), // scale static_cast<RealType>(-0.00125796420642514024493852425918807L),// x static_cast<RealType>(0.7L), // p static_cast<RealType>(0.3L), //q 80*tolerance); test_spot( static_cast<RealType>(1.2345L), // location static_cast<RealType>(0.12345L), // scale static_cast<RealType>(0.0012345L), // x static_cast<RealType>(0.0000458541039469413343331170952855318L), // p static_cast<RealType>(0.999954145896053058665666882904714L), //q 80*tolerance); test_spot( static_cast<RealType>(5L), // location static_cast<RealType>(2L), // scale static_cast<RealType>(0.0012345L), // x static_cast<RealType>(0.0759014628704232983512906076564256L), // p static_cast<RealType>(0.924098537129576701648709392343574L), //q 80*tolerance); //negative location test_spot( static_cast<RealType>(-123.123123L), // location static_cast<RealType>(2.123L), // scale static_cast<RealType>(3), // x static_cast<RealType>(0.999999999999999999999999984171276L), // p static_cast<RealType>(1.58287236765203121622150720373972e-26L), //q tolerance); //PDF Testing BOOST_CHECK_CLOSE( ::boost::math::pdf( logistic_distribution<RealType>(5,2), static_cast<RealType>(0.125L) ),//x static_cast<RealType>(0.0369500730133475464584898192104821L), // probability tolerance); // % BOOST_CHECK_CLOSE( ::boost::math::pdf( logistic_distribution<RealType>(static_cast<RealType>(1.2345L), static_cast<RealType>(0.12345L)), static_cast<RealType>(0.0012345L) ),//x static_cast<RealType>(0.000371421639109700748742498671686243L), // probability tolerance); // % BOOST_CHECK_CLOSE( ::boost::math::pdf( logistic_distribution<RealType>(2,1), static_cast<RealType>(2L) ),//x static_cast<RealType>(0.25L), // probability tolerance); // % //Extreme value testing if(std::numeric_limits<RealType>::has_infinity) { BOOST_CHECK_EQUAL(pdf(logistic_distribution<RealType>(), +std::numeric_limits<RealType>::infinity()), 0); // x = + infinity, pdf = 0 BOOST_CHECK_EQUAL(pdf(logistic_distribution<RealType>(), -std::numeric_limits<RealType>::infinity()), 0); // x = - infinity, pdf = 0 BOOST_CHECK_EQUAL(cdf(logistic_distribution<RealType>(), +std::numeric_limits<RealType>::infinity()), 1); // x = + infinity, cdf = 1 BOOST_CHECK_EQUAL(cdf(logistic_distribution<RealType>(), -std::numeric_limits<RealType>::infinity()), 0); // x = - infinity, cdf = 0 BOOST_CHECK_EQUAL(cdf(complement(logistic_distribution<RealType>(), +std::numeric_limits<RealType>::infinity())), 0); // x = + infinity, c cdf = 0 BOOST_CHECK_EQUAL(cdf(complement(logistic_distribution<RealType>(), -std::numeric_limits<RealType>::infinity())), 1); // x = - infinity, c cdf = 1 } BOOST_MATH_CHECK_THROW(quantile(logistic_distribution<RealType>(), static_cast<RealType>(1)), std::overflow_error); // x = + infinity, cdf = 1 BOOST_MATH_CHECK_THROW(quantile(logistic_distribution<RealType>(), static_cast<RealType>(0)), std::overflow_error); // x = - infinity, cdf = 0 BOOST_MATH_CHECK_THROW(quantile(complement(logistic_distribution<RealType>(), static_cast<RealType>(1))), std::overflow_error); // x = - infinity, cdf = 0 BOOST_MATH_CHECK_THROW(quantile(complement(logistic_distribution<RealType>(), static_cast<RealType>(0))), std::overflow_error); // x = + infinity, cdf = 1 BOOST_CHECK_EQUAL(cdf(logistic_distribution<RealType>(), +boost::math::tools::max_value<RealType>()), 1); // x = + infinity, cdf = 1 BOOST_CHECK_EQUAL(cdf(logistic_distribution<RealType>(), -boost::math::tools::max_value<RealType>()), 0); // x = - infinity, cdf = 0 BOOST_CHECK_EQUAL(cdf(complement(logistic_distribution<RealType>(), +boost::math::tools::max_value<RealType>())), 0); // x = + infinity, c cdf = 0 BOOST_CHECK_EQUAL(cdf(complement(logistic_distribution<RealType>(), -boost::math::tools::max_value<RealType>())), 1); // x = - infinity, c cdf = 1 BOOST_CHECK_EQUAL(pdf(logistic_distribution<RealType>(), +boost::math::tools::max_value<RealType>()), 0); // x = + infinity, pdf = 0 BOOST_CHECK_EQUAL(pdf(logistic_distribution<RealType>(), -boost::math::tools::max_value<RealType>()), 0); // x = - infinity, pdf = 0 // // Things that are errors: // 1. Domain errors for scale and location. // 2. x being NAN. // 3. Probabilies being outside (0,1). check_out_of_range<logistic_distribution<RealType> >(0, 1); if(std::numeric_limits<RealType>::has_infinity) { RealType inf = std::numeric_limits<RealType>::infinity(); BOOST_CHECK_EQUAL(pdf(logistic_distribution<RealType>(0, 1), inf), 0); BOOST_CHECK_EQUAL(pdf(logistic_distribution<RealType>(0, 1), -inf), 0); BOOST_CHECK_EQUAL(cdf(logistic_distribution<RealType>(0, 1), inf), 1); BOOST_CHECK_EQUAL(cdf(logistic_distribution<RealType>(0, 1), -inf), 0); BOOST_CHECK_EQUAL(cdf(complement(logistic_distribution<RealType>(0, 1), inf)), 0); BOOST_CHECK_EQUAL(cdf(complement(logistic_distribution<RealType>(0, 1), -inf)), 1); } // location/scale can't be infinity. if(std::numeric_limits<RealType>::has_infinity) { #ifndef BOOST_NO_EXCEPTIONS BOOST_MATH_CHECK_THROW( logistic_distribution<RealType> dist(std::numeric_limits<RealType>::infinity(), 0.5), std::domain_error); BOOST_MATH_CHECK_THROW( logistic_distribution<RealType> dist(0.5, std::numeric_limits<RealType>::infinity()), std::domain_error); #else BOOST_MATH_CHECK_THROW( logistic_distribution<RealType>(std::numeric_limits<RealType>::infinity(), 0.5), std::domain_error); BOOST_MATH_CHECK_THROW( logistic_distribution<RealType>(0.5, std::numeric_limits<RealType>::infinity()), std::domain_error); #endif } // scale can't be negative or 0. #ifndef BOOST_NO_EXCEPTIONS BOOST_MATH_CHECK_THROW( logistic_distribution<RealType> dist(0.5, -0.5), std::domain_error); BOOST_MATH_CHECK_THROW( logistic_distribution<RealType> dist(0.5, 0), std::domain_error); #else BOOST_MATH_CHECK_THROW( logistic_distribution<RealType>(0.5, -0.5), std::domain_error); BOOST_MATH_CHECK_THROW( logistic_distribution<RealType>(0.5, 0), std::domain_error); #endif logistic_distribution<RealType> dist(0.5, 0.5); // x can't be NaN, p can't be NaN. if (std::numeric_limits<RealType>::has_quiet_NaN) { // No longer allow x to be NaN, then these tests should throw. BOOST_MATH_CHECK_THROW(pdf(dist, +std::numeric_limits<RealType>::quiet_NaN()), std::domain_error); // x = NaN BOOST_MATH_CHECK_THROW(cdf(dist, +std::numeric_limits<RealType>::quiet_NaN()), std::domain_error); // x = NaN BOOST_MATH_CHECK_THROW(cdf(complement(dist, +std::numeric_limits<RealType>::quiet_NaN())), std::domain_error); // x = + infinity BOOST_MATH_CHECK_THROW(quantile(dist, +std::numeric_limits<RealType>::quiet_NaN()), std::domain_error); // p = + infinity BOOST_MATH_CHECK_THROW(quantile(complement(dist, +std::numeric_limits<RealType>::quiet_NaN())), std::domain_error); // p = + infinity } if (std::numeric_limits<RealType>::has_infinity) { // Added test for Trac https://svn.boost.org/trac/boost/ticket/9126#comment:1 logistic_distribution<RealType> dist(0., 0.5); BOOST_CHECK_EQUAL(pdf(dist, +std::numeric_limits<RealType>::infinity()), static_cast<RealType>(0) ); // x = infinity } // p can't be outside (0,1). BOOST_MATH_CHECK_THROW(quantile(dist, static_cast<RealType>(1.1)), std::domain_error); BOOST_MATH_CHECK_THROW(quantile(dist, static_cast<RealType>(-0.1)), std::domain_error); BOOST_MATH_CHECK_THROW(quantile(dist, static_cast<RealType>(1)), std::overflow_error); BOOST_MATH_CHECK_THROW(quantile(dist, static_cast<RealType>(0)), std::overflow_error); BOOST_MATH_CHECK_THROW(quantile(complement(dist, static_cast<RealType>(1.1))), std::domain_error); BOOST_MATH_CHECK_THROW(quantile(complement(dist, static_cast<RealType>(-0.1))), std::domain_error); BOOST_MATH_CHECK_THROW(quantile(complement(dist, static_cast<RealType>(1))), std::overflow_error); BOOST_MATH_CHECK_THROW(quantile(complement(dist, static_cast<RealType>(0))), std::overflow_error); // Tests for mean,mode,median,variance,skewness,kurtosis. //mean BOOST_CHECK_CLOSE( ::boost::math::mean( logistic_distribution<RealType>(2,1) ),//x static_cast<RealType>(2), // probability tolerance); // % //median BOOST_CHECK_CLOSE( ::boost::math::median( logistic_distribution<RealType>(2,1) ),//x static_cast<RealType>(2), // probability tolerance); //mode BOOST_CHECK_CLOSE( ::boost::math::mode( logistic_distribution<RealType>(2,1) ),//x static_cast<RealType>(2), // probability tolerance); //variance BOOST_CHECK_CLOSE( ::boost::math::variance( logistic_distribution<RealType>(2,1) ),//x static_cast<RealType>(3.28986813369645287294483033329205L), // probability tolerance); //skewness BOOST_CHECK_CLOSE( ::boost::math::skewness( logistic_distribution<RealType>(2,1) ),//x static_cast<RealType>(0), // probability tolerance); BOOST_CHECK_CLOSE( ::boost::math::kurtosis_excess( logistic_distribution<RealType>(2,1) ),//x static_cast<RealType>(1.2L), // probability tolerance); } // template <class RealType>void test_spots(RealType) BOOST_AUTO_TEST_CASE( test_main ) { // Check that can generate logistic distribution using the two convenience methods: boost::math::logistic mycexp1(1.); // Using typedef logistic_distribution<> myexp2(1.); // Using default RealType double. // Basic sanity-check spot values. // (Parameter value, arbitrarily zero, only communicates the floating point type). test_spots(0.0F); // Test float. OK at decdigits = 0 tolerance = 0.0001 % test_spots(0.0); // Test double. OK at decdigits 7, tolerance = 1e07 % #ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS test_spots(0.0L); // Test long double. #if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x582)) test_spots(boost::math::concepts::real_concept(0.)); // Test real concept. #endif #else std::cout << "<note>The long double tests have been disabled on this platform " "either because the long double overloads of the usual math functions are " "not available at all, or because they are too inaccurate for these tests " "to pass.</note>" << std::endl; #endif } // BOOST_AUTO_TEST_CASE( test_main )<|fim▁end|>
test_spot( static_cast<RealType>(5), // location static_cast<RealType>(2), // scale
<|file_name|>XMLname.py<|end_file_name|><|fim▁begin|>import re from six import text_type """Translate strings to and from SOAP 1.2 XML name encoding Implements rules for mapping application defined name to XML names specified by the w3 SOAP working group for SOAP version 1.2 in Appendix A of "SOAP Version 1.2 Part 2: Adjuncts", W3C Working Draft 17, December 2001, <http://www.w3.org/TR/soap12-part2/#namemap> Also see <http://www.w3.org/2000/xp/Group/xmlp-issues>. Author: Gregory R. Warnes <Gregory.R.Warnes@Pfizer.com> Date:: 2002-04-25 Version 0.9.0 """ ident = "$Id$" def _NCNameChar(x): return x.isalpha() or x.isdigit() or x == "." or x == '-' or x == "_" def _NCNameStartChar(x): return x.isalpha() or x == "_" def _toUnicodeHex(x): hexval = hex(ord(x[0]))[2:] hexlen = len(hexval) # Make hexval have either 4 or 8 digits by prepending 0's if (hexlen == 1): hexval = "000" + hexval elif (hexlen == 2): hexval = "00" + hexval elif (hexlen == 3): hexval = "0" + hexval elif (hexlen == 4): hexval = "" + hexval elif (hexlen == 5): hexval = "000" + hexval elif (hexlen == 6): hexval = "00" + hexval elif (hexlen == 7): hexval = "0" + hexval elif (hexlen == 8): hexval = "" + hexval else: raise Exception("Illegal Value returned from hex(ord(x))") return "_x" + hexval + "_" def _fromUnicodeHex(x): return eval(r'u"\u' + x[2:-1] + '"') def toXMLname(string): """Convert string to a XML name.""" if string.find(':') != -1: (prefix, localname) = string.split(':', 1) else: prefix = None localname = string T = text_type(localname) N = len(localname) X = [] for i in range(N): if i < N - 1 and T[i] == u'_' and T[i + 1] == u'x': X.append(u'_x005F_') elif i == 0 and N >= 3 and \ (T[0] == u'x' or T[0] == u'X') and \ (T[1] == u'm' or T[1] == u'M') and \ (T[2] == u'l' or T[2] == u'L'): X.append(u'_xFFFF_' + T[0])<|fim▁hole|> if prefix: return "%s:%s" % (prefix, u''.join(X)) return u''.join(X) def fromXMLname(string): """Convert XML name to unicode string.""" retval = re.sub(r'_xFFFF_', '', string) def fun(matchobj): return _fromUnicodeHex(matchobj.group(0)) retval = re.sub(r'_x[0-9A-Fa-f]{4}_', fun, retval) return retval<|fim▁end|>
elif (not _NCNameChar(T[i])) or (i == 0 and not _NCNameStartChar(T[i])): X.append(_toUnicodeHex(T[i])) else: X.append(T[i])
<|file_name|>holdingpen.py<|end_file_name|><|fim▁begin|>import os import subprocess import re import glob import numpy as np from astropy.io import fits from astropy.time import Time from astropy.table import Table import desiutil.log import desisurvey.config import desisurvey.plan import desisurvey.tiles from desisurvey.utils import yesno logger = desiutil.log.get_logger() def make_tileid_list(fadir): fafiles = glob.glob(os.path.join(fadir, '**/*.fits*'), recursive=True) rgx = re.compile(r'.*fiberassign-(\d+)\.fits(\.gz)?') existing_tileids = [] existing_fafiles = [] for fn in fafiles: match = rgx.match(fn) if match: existing_tileids.append(int(match.group(1))) existing_fafiles.append(fn) return np.array(existing_tileids), np.array(existing_fafiles) def tileid_to_clean(faholddir, fadir, mtldone): """Identify invalidated fiberassign files for deletion. Scans faholddir for fiberassign files. Compares the MTLTIMES with the times in the mtldone file. If a fiberassign file was designed before an overlapping tile which later had MTL updates, that fiberassign file is "invalid" and should be deleted. Parameters ---------- faholddir : str directory name of fiberassign holding pen fadir : str directory name of svn-controlled fiber assign directory. mtldone : array numpy array of finished tile MTL updates. Must contain at least TIMESTAMP and TILEID fields. """ import dateutil.parser cfg = desisurvey.config.Configuration() tiles = desisurvey.tiles.get_tiles() plan = desisurvey.plan.Planner(restore=cfg.tiles_file()) existing = tiles.tileID[plan.tile_status != 'unobs'] m = (plan.tile_status == 'unobs') & (plan.tile_priority <= 0) existing_tileids, existing_fafiles = make_tileid_list(faholddir) intiles = np.isin(existing_tileids, tiles.tileID) existing_tileids = existing_tileids[intiles] existing_fafiles = existing_fafiles[intiles] existing = existing[np.isin(existing, existing_tileids)] logger.info('Reading in MTLTIME header from %d fiberassign files...' % len(existing_fafiles)) mtltime = [fits.getheader(fn).get('MTLTIME', 'None') for fn in existing_fafiles] m = np.array([mtltime0 is not None for mtltime0 in mtltime], dtype='bool') if np.any(~m): logger.warning('MTLTIME not found for tiles {}!'.format( ' '.join([x for x in existing_fafiles[~m]]))) if np.sum(m) == 0: return np.zeros(0, dtype='i4') existing_tileids = existing_tileids[m] existing_fafiles = existing_fafiles[m] mtltime = np.array(mtltime)[m] mtltime = Time([dateutil.parser.parse(mtltime0) for mtltime0 in mtltime]).mjd # we have the mtl times for all existing fa files. # we want the largest MTL time of any overlapping tile which has # status != 'unobs' tilemtltime = np.zeros(tiles.ntiles, dtype='f8') - 1 index, mask = tiles.index(existing_tileids, return_mask=True) if np.sum(~mask) > 0: logger.info('Ignoring {} TILEID not in the tile file'.format( np.sum(~mask))) index = index[mask] existing_tileids = existing_tileids[mask] mtltime = mtltime[mask] tilemtltime[index] = mtltime # this has the MTL design time of all of the tiles. # we also need the MTL done time of all the tiles. index, mask = tiles.index(mtldone['TILEID'], return_mask=True) mtldonetime = [dateutil.parser.parse(mtltime0) for mtltime0 in mtldone['TIMESTAMP']] mtldonetime = Time(mtldonetime).mjd tilemtldonetime = np.zeros(tiles.ntiles, dtype='f8') tilemtldonetime[index[mask]] = mtldonetime[mask] maxoverlappingtilemtldonetime = np.zeros(tiles.ntiles, dtype='f8') for i, neighbors in enumerate(tiles.overlapping): if len(neighbors) == 0: continue maxoverlappingtilemtldonetime[i] = np.max(tilemtldonetime[neighbors]) expired = ((maxoverlappingtilemtldonetime > tilemtltime) & (plan.tile_status == 'unobs') & (tilemtltime > -1)) for tileid in existing: tileidpadstr = '%06d' % tileid fafn = os.path.join(fadir, tileidpadstr[:3], 'fiberassign-%s.fits.gz' % tileidpadstr) if not os.path.exists(fafn): logger.error('Tile {} is not unobs, '.format(fafn) + 'but does not exist in SVN?!') return tiles.tileID[expired] def remove_tiles_from_dir(dirname, tileid): for tileid0 in tileid: for ext in ['fits.gz', 'png', 'log']: expidstr= '{:06d}'.format(tileid0) os.remove(os.path.join( dirname, expidstr[:3], 'fiberassign-{}.{}'.format(expidstr, ext))) def missing_tileid(fadir, faholddir): """Return missing TILEID and superfluous TILEID. The fiberassign holding pen should include all TILEID for available, unobserved tiles. It should include no TILEID for unavailable or observed tiles. This function computes the list of TILEID that should exist, but do not, as well as the list of TILEID that should not exist, but do. Parameters ---------- fadir : str directory name of fiberassign directory faholddir : str directory name of fiberassign holding pen Returns<|fim▁hole|> ------- missingtiles, extratiles missingtiles : array array of TILEID for tiles that do not exist, but should. These need to be designed and added to the holding pen. extratiles : array array of TILEID for tiles that exist, but should not. These need to be deleted from the holding pen. """ cfg = desisurvey.config.Configuration() tiles = desisurvey.tiles.get_tiles() plan = desisurvey.plan.Planner(restore=cfg.tiles_file()) tileid, fafn = make_tileid_list(faholddir) shouldexist = tiles.tileID[(plan.tile_status == 'unobs') & (plan.tile_priority > 0)] missingtiles = set(shouldexist) - set(tileid) shouldnotexist = tiles.tileID[(plan.tile_status != 'unobs') | (plan.tile_priority <= 0)] doesexist = np.isin(tileid, shouldnotexist) count = 0 for tileid0 in tileid[doesexist]: expidstr = '{:06d}'.format(tileid0) if not os.path.exists(os.path.join( fadir, expidstr[:3], 'fiberassign-{}.fits.gz'.format(expidstr))): logger.error('TILEID %d should be checked into svn and is not!' % tileid0) else: count += 1 if count > 0: logger.info('Confirmed %d files in SVN also in holding pen.' % count) logger.info('TILEID: ' + ' '.join( [str(x) for x in np.sort(tileid[doesexist])])) return (np.sort(np.array([x for x in missingtiles])), np.sort(tileid[doesexist])) def get_untracked_fnames(svn): fnames = [] res = subprocess.run(['svn', 'status', svn], capture_output=True) output = res.stdout.decode('utf8') for line in output.split('\n'): if len(line) == 0: continue modtype = line[0] if modtype != '?': print('unrecognized line: "{}", ignoring.'.format(line)) continue # new file. We need to check it in or delete it. fname = line[8:] fnames.append(fname) return fnames def maintain_svn(svn, untrackedonly=True, verbose=False): cfg = desisurvey.config.Configuration() tiles = desisurvey.tiles.get_tiles() plan = desisurvey.plan.Planner(restore=cfg.tiles_file()) if untrackedonly: fnames = get_untracked_fnames(svn) rgxdir = re.compile(svn + '/' + r'\d\d\d$') for fname in fnames: # if it's a new directory, go ahead and add it # so that we can see its contents. matchdir = rgxdir.match(fname.strip()) if matchdir: subprocess.run(['svn', 'add', fname, '--depth=empty']) print('svn-adding new directory %s' % fname) fnames = get_untracked_fnames(svn) else: import glob fnames = glob.glob(os.path.join(svn, '**/*'), recursive=True) rgx = re.compile(svn + '/' + r'\d\d\d/fiberassign-(\d+)\.(fits|fits\.gz|png|log)') todelete = [] tocommit = [] mintileid = np.min(tiles.tileID) maxtileid = np.max(tiles.tileID) for fname in fnames: match = rgx.match(fname) if not match: if verbose: logger.warn('unrecognized filename: "{}", ' 'ignoring.'.format(fname)) continue tileid = int(match.group(1)) idx, mask = tiles.index(tileid, return_mask=True) if not mask: if verbose and (tileid >= mintileid) and (tileid <= maxtileid): logger.warn('unrecognized TILEID {}, ignoring.'.format(tileid)) continue if plan.tile_status[idx] == 'unobs': todelete.append(fname) else: tocommit.append(fname) if not untrackedonly: tocommit = [] return todelete, tocommit def execute_svn_maintenance(todelete, tocommit, echo=False, svnrm=False): if echo: cmd = ['echo', 'svn'] else: cmd = ['svn'] for fname in todelete: if svnrm: subprocess.run(cmd + ['rm', fname]) else: if not echo: os.remove(fname) else: print('removing ', fname) for fname in tocommit: subprocess.run(cmd + ['add', fname]) def maintain_holding_pen_and_svn(fbadir, faholddir, mtldonefn): todelete, tocommit = maintain_svn(fbadir) if len(todelete) + len(tocommit) > 0: logger.info(('To delete from %s:\n' % fbadir) + '\n'.join([os.path.basename(x) for x in todelete])) logger.info(('To commit to %s:\n' % fbadir) + '\n'.join([os.path.basename(x) for x in tocommit])) qstr = ('Preparing to perform svn fiberassign maintenance, ' 'deleting {} and committing {} files. Continue?'.format( len(todelete), len(tocommit))) okay = yesno(qstr) if okay: execute_svn_maintenance(todelete, tocommit, echo=True) okay = yesno('The following commands will be executed. ' 'Still okay?') if okay: execute_svn_maintenance(todelete, tocommit) okay = yesno('Commit to svn?') if okay: subprocess.run(['svn', 'ci', fbadir, '-m "Adding newly observed tiles."']) if mtldonefn is not None: invalid = tileid_to_clean(faholddir, fbadir, Table.read(mtldonefn)) if len(invalid) > 0: okay = yesno(('Deleting {} out-of-date fiberassign files from ' + 'holding pen. Continue?').format(len(invalid))) if okay: remove_tiles_from_dir(faholddir, invalid) missing, extra = missing_tileid(fbadir, faholddir) if len(extra) > 0: okay = yesno(('Deleting {} fiberassign files in SVN from the ' 'holding pen. Continue?').format(len(extra))) if okay: remove_tiles_from_dir(faholddir, extra) if len(missing) < 100: logger.info('Need to design the following tiles here! ' + ' '.join([str(x) for x in missing])) else: logger.info('Need to design many (%d) tiles here!' % len(missing))<|fim▁end|>
<|file_name|>deprecation.py<|end_file_name|><|fim▁begin|># Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tensor utility functions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import functools import inspect import re from tensorflow.python.platform import tf_logging as logging from tensorflow.python.util import decorator_utils def _add_deprecated_function_notice_to_docstring(doc, date, instructions): """Adds a deprecation notice to a docstring for deprecated functions.""" return decorator_utils.add_notice_to_docstring( doc, instructions, 'DEPRECATED FUNCTION', '(deprecated)', [ 'THIS FUNCTION IS DEPRECATED. It will be removed after %s.' % date, 'Instructions for updating:']) def _add_deprecated_arg_notice_to_docstring(doc, date, instructions): """Adds a deprecation notice to a docstring for deprecated arguments.""" return decorator_utils.add_notice_to_docstring( doc, instructions, 'DEPRECATED FUNCTION ARGUMENTS', '(deprecated arguments)', [ 'SOME ARGUMENTS ARE DEPRECATED. ' 'They will be removed after %s.' % date, 'Instructions for updating:']) def _validate_deprecation_args(date, instructions): if not date: raise ValueError('Tell us what date this will be deprecated!') if not re.match(r'20\d\d-[01]\d-[0123]\d', date): raise ValueError('Date must be YYYY-MM-DD.') if not instructions: raise ValueError('Don\'t deprecate things without conversion instructions!') def _call_location(level=2): """Returns call location given level up from current call.""" stack = inspect.stack() # Check that stack has enough elements. if len(stack) > level: location = stack[level] return '%s:%d in %s.' % (location[1], location[2], location[3]) return '<unknown>' def deprecated(date, instructions): """Decorator for marking functions or methods deprecated. This decorator logs a deprecation warning whenever the decorated function is called. It has the following format: <function> (from <module>) is deprecated and will be removed after <date>. Instructions for updating: <instructions> <function> will include the class name if it is a method. It also edits the docstring of the function: ' (deprecated)' is appended to the first line of the docstring and a deprecation notice is prepended to the rest of the docstring. Args: date: String. The date the function is scheduled to be removed. Must be ISO 8601 (YYYY-MM-DD). instructions: String. Instructions on how to update code using the deprecated function. Returns: Decorated function or method. Raises: ValueError: If date is not in ISO 8601 format, or instructions are empty. """ _validate_deprecation_args(date, instructions) def deprecated_wrapper(func): """Deprecation wrapper.""" decorator_utils.validate_callable(func, 'deprecated') @functools.wraps(func) def new_func(*args, **kwargs): logging.warning( 'From %s: %s (from %s) is deprecated and will be removed ' 'after %s.\n' 'Instructions for updating:\n%s', _call_location(), decorator_utils.get_qualified_name(func), func.__module__, date, instructions) return func(*args, **kwargs) new_func.__doc__ = _add_deprecated_function_notice_to_docstring( func.__doc__, date, instructions) return new_func return deprecated_wrapper DeprecatedArgSpec = collections.namedtuple( 'DeprecatedArgSpec', ['position', 'has_ok_value', 'ok_value']) def deprecated_args(date, instructions, *deprecated_arg_names_or_tuples): """Decorator for marking specific function arguments as deprecated. This decorator logs a deprecation warning whenever the decorated function is called with the deprecated argument. It has the following format: Calling <function> (from <module>) with <arg> is deprecated and will be removed after <date>. Instructions for updating: <instructions> <function> will include the class name if it is a method. It also edits the docstring of the function: ' (deprecated arguments)' is appended to the first line of the docstring and a deprecation notice is prepended to the rest of the docstring. Args: date: String. The date the function is scheduled to be removed. Must be ISO 8601 (YYYY-MM-DD). instructions: String. Instructions on how to update code using the deprecated function. *deprecated_arg_names_or_tuples: String. or 2-Tuple(String, [ok_vals]). The string is the deprecated argument name. Optionally, an ok-value may be provided. If the user provided argument equals this value, the warning is suppressed. Returns: Decorated function or method. Raises: ValueError: If date is not in ISO 8601 format, instructions are empty, the deprecated arguments are not present in the function signature, or the second element of a deprecated_tuple is not a list. """ _validate_deprecation_args(date, instructions) if not deprecated_arg_names_or_tuples: raise ValueError('Specify which argument is deprecated.') def _get_arg_names_to_ok_vals():<|fim▁hole|> d[name_or_tuple[0]] = DeprecatedArgSpec(-1, True, name_or_tuple[1]) else: d[name_or_tuple] = DeprecatedArgSpec(-1, False, None) return d def _get_deprecated_positional_arguments(names_to_ok_vals, arg_spec): """Builds a dictionary from deprecated arguments to thier spec. Returned dict is keyed by argument name. Each value is a DeprecatedArgSpec with the following fields: position: The zero-based argument position of the argument within the signature. None if the argument isn't found in the signature. ok_values: Values of this argument for which warning will be suppressed. Args: names_to_ok_vals: dict from string arg_name to a list of values, possibly empty, which should not elicit a warning. arg_spec: Output from inspect.getargspec on the called function. Returns: Dictionary from arg_name to DeprecatedArgSpec. """ arg_name_to_pos = dict( (name, pos) for (pos, name) in enumerate(arg_spec.args)) deprecated_positional_args = {} for arg_name, spec in iter(names_to_ok_vals.items()): if arg_name in arg_name_to_pos: pos = arg_name_to_pos[arg_name] deprecated_positional_args[arg_name] = DeprecatedArgSpec( pos, spec.has_ok_value, spec.ok_value) return deprecated_positional_args def deprecated_wrapper(func): """Deprecation decorator.""" decorator_utils.validate_callable(func, 'deprecated_args') deprecated_arg_names = _get_arg_names_to_ok_vals() arg_spec = inspect.getargspec(func) deprecated_positions = _get_deprecated_positional_arguments( deprecated_arg_names, arg_spec) is_varargs_deprecated = arg_spec.varargs in deprecated_arg_names is_kwargs_deprecated = arg_spec.keywords in deprecated_arg_names if (len(deprecated_positions) + is_varargs_deprecated + is_kwargs_deprecated != len(deprecated_arg_names_or_tuples)): known_args = arg_spec.args + [arg_spec.varargs, arg_spec.keywords] missing_args = [arg_name for arg_name in deprecated_arg_names if arg_name not in known_args] raise ValueError('The following deprecated arguments are not present ' 'in the function signature: %s. ' 'Found next arguments: %s.' % (missing_args, known_args)) @functools.wraps(func) def new_func(*args, **kwargs): """Deprecation wrapper.""" invalid_args = [] named_args = inspect.getcallargs(func, *args, **kwargs) for arg_name, spec in iter(deprecated_positions.items()): if (spec.position < len(args) and not (spec.has_ok_value and named_args[arg_name] == spec.ok_value)): invalid_args.append(arg_name) if is_varargs_deprecated and len(args) > len(arg_spec.args): invalid_args.append(arg_spec.varargs) if is_kwargs_deprecated and kwargs: invalid_args.append(arg_spec.keywords) for arg_name in deprecated_arg_names: if (arg_name in kwargs and not (deprecated_positions[arg_name].has_ok_value and (named_args[arg_name] == deprecated_positions[arg_name].ok_value))): invalid_args.append(arg_name) for arg_name in invalid_args: logging.warning( 'From %s: calling %s (from %s) with %s is deprecated and will ' 'be removed after %s.\nInstructions for updating:\n%s', _call_location(), decorator_utils.get_qualified_name(func), func.__module__, arg_name, date, instructions) return func(*args, **kwargs) new_func.__doc__ = _add_deprecated_arg_notice_to_docstring( func.__doc__, date, instructions) return new_func return deprecated_wrapper def deprecated_arg_values(date, instructions, **deprecated_kwargs): """Decorator for marking specific function argument values as deprecated. This decorator logs a deprecation warning whenever the decorated function is called with the deprecated argument values. It has the following format: Calling <function> (from <module>) with <arg>=<value> is deprecated and will be removed after <date>. Instructions for updating: <instructions> <function> will include the class name if it is a method. It also edits the docstring of the function: ' (deprecated arguments)' is appended to the first line of the docstring and a deprecation notice is prepended to the rest of the docstring. Args: date: String. The date the function is scheduled to be removed. Must be ISO 8601 (YYYY-MM-DD). instructions: String. Instructions on how to update code using the deprecated function. **deprecated_kwargs: The deprecated argument values. Returns: Decorated function or method. Raises: ValueError: If date is not in ISO 8601 format, or instructions are empty. """ _validate_deprecation_args(date, instructions) if not deprecated_kwargs: raise ValueError('Specify which argument values are deprecated.') def deprecated_wrapper(func): """Deprecation decorator.""" decorator_utils.validate_callable(func, 'deprecated_arg_values') @functools.wraps(func) def new_func(*args, **kwargs): """Deprecation wrapper.""" named_args = inspect.getcallargs(func, *args, **kwargs) for arg_name, arg_value in deprecated_kwargs.items(): if arg_name in named_args and named_args[arg_name] == arg_value: logging.warning( 'From %s: calling %s (from %s) with %s=%s is deprecated and will ' 'be removed after %s.\nInstructions for updating:\n%s', _call_location(), decorator_utils.get_qualified_name(func), func.__module__, arg_name, arg_value, date, instructions) return func(*args, **kwargs) new_func.__doc__ = _add_deprecated_arg_notice_to_docstring( func.__doc__, date, instructions) return new_func return deprecated_wrapper<|fim▁end|>
"""Returns a dict mapping arg_name to DeprecatedArgSpec w/o position.""" d = {} for name_or_tuple in deprecated_arg_names_or_tuples: if isinstance(name_or_tuple, tuple):
<|file_name|>mode-xml.js<|end_file_name|><|fim▁begin|>/* ***** BEGIN LICENSE BLOCK ***** * Distributed under the BSD license: * * Copyright (c) 2010, Ajax.org B.V. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Ajax.org B.V. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/xml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/xml_highlight_rules', 'ace/mode/behaviour/xml', 'ace/mode/folding/xml'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var XmlHighlightRules = require("./xml_highlight_rules").XmlHighlightRules; var XmlBehaviour = require("./behaviour/xml").XmlBehaviour; var XmlFoldMode = require("./folding/xml").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new XmlHighlightRules().getRules()); this.$behaviour = new XmlBehaviour(); this.foldingRules = new XmlFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.getNextLineIndent = function(state, line, tab) { return this.$getIndent(line); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/xml_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/xml_util', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var xmlUtil = require("./xml_util"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var XmlHighlightRules = function() { this.$rules = { start : [{ token : "text", regex : "<\\!\\[CDATA\\[", next : "cdata" }, { token : "xml-pe", regex : "<\\?.*?\\?>" }, { token : "comment", merge : true, regex : "<\\!--", next : "comment" }, { token : "xml-pe", regex : "<\\!.*?>" }, { token : "meta.tag", // opening tag regex : "<\\/?", next : "tag" }, { token : "text", regex : "\\s+" }, { token : "constant.character.entity", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }, { token : "text", regex : "[^<]+" }], cdata : [{ token : "text", regex : "\\]\\]>", next : "start" }, { token : "text", regex : "\\s+" }, { token : "text", regex : "(?:[^\\]]|\\](?!\\]>))+" }], comment : [{ token : "comment", regex : ".*?-->", next : "start" }, { token : "comment", merge : true, regex : ".+" }] }; xmlUtil.tag(this.$rules, "tag", "start"); }; oop.inherits(XmlHighlightRules, TextHighlightRules); exports.XmlHighlightRules = XmlHighlightRules; }); define('ace/mode/xml_util', ['require', 'exports', 'module' ], function(require, exports, module) { function string(state) { return [{ token : "string", regex : '".*?"' }, { token : "string", // multi line string start merge : true, regex : '["].*', next : state + "_qqstring" }, { token : "string", regex : "'.*?'" }, { token : "string", // multi line string start merge : true, regex : "['].*", next : state + "_qstring" }]; } function multiLineString(quote, state) { return [{ token : "string", merge : true, regex : ".*?" + quote, next : state }, { token : "string", merge : true, regex : '.+' }]; } exports.tag = function(states, name, nextState, tagMap) { states[name] = [{ token : "text", regex : "\\s+" }, { token : !tagMap ? "meta.tag.tag-name" : function(value) { if (tagMap[value]) return "meta.tag.tag-name." + tagMap[value]; else return "meta.tag.tag-name"; }, merge : true, regex : "[-_a-zA-Z0-9:]+", next : name + "_embed_attribute_list" }, { token: "empty", regex: "", next : name + "_embed_attribute_list" }]; states[name + "_qstring"] = multiLineString("'", name + "_embed_attribute_list"); states[name + "_qqstring"] = multiLineString("\"", name + "_embed_attribute_list"); states[name + "_embed_attribute_list"] = [{ token : "meta.tag", merge : true, regex : "\/?>", next : nextState }, { token : "keyword.operator", regex : "=" }, { token : "entity.other.attribute-name", regex : "[-_a-zA-Z0-9:]+" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "text", regex : "\\s+" }].concat(string(name)); }; }); define('ace/mode/behaviour/xml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour', 'ace/mode/behaviour/cstyle', 'ace/token_iterator'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = require("./cstyle").CstyleBehaviour; var TokenIterator = require("../../token_iterator").TokenIterator; function hasType(token, type) { var hasType = true; var typeList = token.type.split('.'); var needleList = type.split('.'); needleList.forEach(function(needle){ if (typeList.indexOf(needle) == -1) { hasType = false; return false; } }); return hasType; } var XmlBehaviour = function () { this.inherit(CstyleBehaviour, ["string_dquotes"]); // Get string behaviour this.add("autoclosing", "insertion", function (state, action, editor, session, text) { if (text == '>') { var position = editor.getCursorPosition(); var iterator = new TokenIterator(session, position.row, position.column); var token = iterator.getCurrentToken(); var atCursor = false; if (!token || !hasType(token, 'meta.tag') && !(hasType(token, 'text') && token.value.match('/'))){ do { token = iterator.stepBackward(); } while (token && (hasType(token, 'string') || hasType(token, 'keyword.operator') || hasType(token, 'entity.attribute-name') || hasType(token, 'text'))); } else { atCursor = true; } if (!token || !hasType(token, 'meta.tag-name') || iterator.stepBackward().value.match('/')) { return } var tag = token.value; if (atCursor){ var tag = tag.substring(0, position.column - token.start); } return { text: '>' + '</' + tag + '>', selection: [1, 1] } } }); this.add('autoindent', 'insertion', function (state, action, editor, session, text) { if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChars = line.substring(cursor.column, cursor.column + 2); if (rightChars == '</') { var indent = this.$getIndent(session.doc.getLine(cursor.row)) + session.getTabString(); var next_indent = this.$getIndent(session.doc.getLine(cursor.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] } } } }); } oop.inherits(XmlBehaviour, Behaviour); exports.XmlBehaviour = XmlBehaviour; }); define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour', 'ace/token_iterator', 'ace/lib/lang'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var TokenIterator = require("../../token_iterator").TokenIterator; var lang = require("../../lib/lang"); var SAFE_INSERT_IN_TOKENS = ["text", "paren.rparen", "punctuation.operator"]; var SAFE_INSERT_BEFORE_TOKENS = ["text", "paren.rparen", "punctuation.operator", "comment"]; var autoInsertedBrackets = 0; var autoInsertedRow = -1; var autoInsertedLineEnd = ""; var maybeInsertedBrackets = 0; var maybeInsertedRow = -1; var maybeInsertedLineStart = ""; var maybeInsertedLineEnd = ""; var CstyleBehaviour = function () { CstyleBehaviour.isSaneInsertion = function(editor, session) { var cursor = editor.getCursorPosition(); var iterator = new TokenIterator(session, cursor.row, cursor.column); if (!this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) { var iterator2 = new TokenIterator(session, cursor.row, cursor.column + 1); if (!this.$matchTokenType(iterator2.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) return false; } iterator.stepForward(); return iterator.getCurrentTokenRow() !== cursor.row || this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_BEFORE_TOKENS); }; CstyleBehaviour.$matchTokenType = function(token, types) { return types.indexOf(token.type || token) > -1; }; CstyleBehaviour.recordAutoInsert = function(editor, session, bracket) { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); if (!this.isAutoInsertedClosing(cursor, line, autoInsertedLineEnd[0])) autoInsertedBrackets = 0; autoInsertedRow = cursor.row; autoInsertedLineEnd = bracket + line.substr(cursor.column); autoInsertedBrackets++; }; CstyleBehaviour.recordMaybeInsert = function(editor, session, bracket) { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); if (!this.isMaybeInsertedClosing(cursor, line)) maybeInsertedBrackets = 0; maybeInsertedRow = cursor.row; maybeInsertedLineStart = line.substr(0, cursor.column) + bracket; maybeInsertedLineEnd = line.substr(cursor.column); maybeInsertedBrackets++; }; CstyleBehaviour.isAutoInsertedClosing = function(cursor, line, bracket) { return autoInsertedBrackets > 0 && cursor.row === autoInsertedRow && bracket === autoInsertedLineEnd[0] && line.substr(cursor.column) === autoInsertedLineEnd; }; CstyleBehaviour.isMaybeInsertedClosing = function(cursor, line) { return maybeInsertedBrackets > 0 && cursor.row === maybeInsertedRow && line.substr(cursor.column) === maybeInsertedLineEnd && line.substr(0, cursor.column) == maybeInsertedLineStart; }; CstyleBehaviour.popAutoInsertedClosing = function() { autoInsertedLineEnd = autoInsertedLineEnd.substr(1); autoInsertedBrackets--; }; CstyleBehaviour.clearMaybeInsertedClosing = function() { maybeInsertedBrackets = 0; maybeInsertedRow = -1; }; this.add("braces", "insertion", function (state, action, editor, session, text) { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); if (text == '{') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && selected !== "{" && editor.getWrapBehavioursEnabled()) { return { text: '{' + selected + '}', selection: false }; } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { if (/[\]\}\)]/.test(line[cursor.column])) { CstyleBehaviour.recordAutoInsert(editor, session, "}"); return { text: '{}', selection: [1, 1] }; } else { CstyleBehaviour.recordMaybeInsert(editor, session, "{"); return { text: '{', selection: [1, 1] }; } } } else if (text == '}') { var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { CstyleBehaviour.popAutoInsertedClosing(); return { text: '', selection: [1, 1] }; } } } else if (text == "\n" || text == "\r\n") { var closing = ""; if (CstyleBehaviour.isMaybeInsertedClosing(cursor, line)) { closing = lang.stringRepeat("}", maybeInsertedBrackets); CstyleBehaviour.clearMaybeInsertedClosing(); } var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}' || closing !== "") { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column}, '}'); if (!openBracePos) return null; var indent = this.getNextLineIndent(state, line.substring(0, cursor.column), session.getTabString()); var next_indent = this.$getIndent(line); return { text: '\n' + indent + '\n' + next_indent + closing, selection: [1, indent.length, 1, indent.length] }; } } }); this.add("braces", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } else { maybeInsertedBrackets--; } } }); this.add("parens", "insertion", function (state, action, editor, session, text) { if (text == '(') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && editor.getWrapBehavioursEnabled()) { return { text: '(' + selected + ')', selection: false }; } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { CstyleBehaviour.recordAutoInsert(editor, session, ")"); return { text: '()', selection: [1, 1] }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { CstyleBehaviour.popAutoInsertedClosing(); return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("brackets", "insertion", function (state, action, editor, session, text) { if (text == '[') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && editor.getWrapBehavioursEnabled()) { return { text: '[' + selected + ']', selection: false }; } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { CstyleBehaviour.recordAutoInsert(editor, session, "]"); return { text: '[]', selection: [1, 1] }; } } else if (text == ']') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ']') { var matching = session.$findOpeningBracket(']', {column: cursor.column + 1, row: cursor.row}); if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { CstyleBehaviour.popAutoInsertedClosing(); return { text: '', selection: [1, 1] }; } } } }); this.add("brackets", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '[') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ']') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) { return { text: quote + selected + quote, selection: false }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); if (leftChar == '\\') { return null; } var tokens = session.getTokens(selection.start.row); var col = 0, token; var quotepos = -1; // Track whether we're inside an open quote. for (var x = 0; x < tokens.length; x++) { token = tokens[x]; if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; } col += tokens[x].value.length; } if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { if (!CstyleBehaviour.isSaneInsertion(editor, session)) return; return { text: quote + quote, selection: [1,1] }; } else if (token && token.type === "string") { var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == quote) { return { text: '', selection: [1, 1] }; } } } } }); this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { range.end.column++; return range; } } }); }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); define('ace/mode/folding/xml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/range', 'ace/mode/folding/fold_mode', 'ace/token_iterator'], function(require, exports, module) { var oop = require("../../lib/oop"); var lang = require("../../lib/lang"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var TokenIterator = require("../../token_iterator").TokenIterator; var FoldMode = exports.FoldMode = function(voidElements) { BaseFoldMode.call(this); this.voidElements = voidElements || {}; }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.getFoldWidget = function(session, foldStyle, row) { var tag = this._getFirstTagInLine(session, row); if (tag.closing) return foldStyle == "markbeginend" ? "end" : ""; if (!tag.tagName || this.voidElements[tag.tagName.toLowerCase()]) return ""; if (tag.selfClosing) return ""; if (tag.value.indexOf("/" + tag.tagName) !== -1) return ""; return "start"; }; this._getFirstTagInLine = function(session, row) { var tokens = session.getTokens(row); var value = ""; for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (token.type.indexOf("meta.tag") === 0) value += token.value; else value += lang.stringRepeat(" ", token.value.length); } return this._parseTag(value); }; this.tagRe = /^(\s*)(<?(\/?)([-_a-zA-Z0-9:!]*)\s*(\/?)>?)/; this._parseTag = function(tag) { var match = this.tagRe.exec(tag); var column = this.tagRe.lastIndex || 0; this.tagRe.lastIndex = 0; return { value: tag, match: match ? match[2] : "", closing: match ? !!match[3] : false, selfClosing: match ? !!match[5] || match[2] == "/>" : false, tagName: match ? match[4] : "", column: match[1] ? column + match[1].length : column }; }; this._readTagForward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var value = ""; var start; do { if (token.type.indexOf("meta.tag") === 0) { if (!start) { var start = { row: iterator.getCurrentTokenRow(), column: iterator.getCurrentTokenColumn() }; } value += token.value; if (value.indexOf(">") !== -1) { var tag = this._parseTag(value); tag.start = start; tag.end = { row: iterator.getCurrentTokenRow(), column: iterator.getCurrentTokenColumn() + token.value.length }; iterator.stepForward(); return tag; } } } while(token = iterator.stepForward()); return null; }; this._readTagBackward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var value = ""; var end; do { if (token.type.indexOf("meta.tag") === 0) { if (!end) { end = { row: iterator.getCurrentTokenRow(), column: iterator.getCurrentTokenColumn() + token.value.length }; } value = token.value + value; if (value.indexOf("<") !== -1) { var tag = this._parseTag(value); tag.end = end; tag.start = { row: iterator.getCurrentTokenRow(), column: iterator.getCurrentTokenColumn() }; iterator.stepBackward(); return tag; } } } while(token = iterator.stepBackward()); return null; };<|fim▁hole|> this._pop = function(stack, tag) { while (stack.length) { var top = stack[stack.length-1]; if (!tag || top.tagName == tag.tagName) { return stack.pop(); } else if (this.voidElements[tag.tagName]) { return; } else if (this.voidElements[top.tagName]) { stack.pop(); continue; } else { return null; } } }; this.getFoldWidgetRange = function(session, foldStyle, row) { var firstTag = this._getFirstTagInLine(session, row); if (!firstTag.match) return null; var isBackward = firstTag.closing || firstTag.selfClosing; var stack = []; var tag; if (!isBackward) { var iterator = new TokenIterator(session, row, firstTag.column); var start = { row: row, column: firstTag.column + firstTag.tagName.length + 2 }; while (tag = this._readTagForward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (tag.closing) { this._pop(stack, tag); if (stack.length == 0) return Range.fromPoints(start, tag.start); } else { stack.push(tag) } } } else { var iterator = new TokenIterator(session, row, firstTag.column + firstTag.match.length); var end = { row: row, column: firstTag.column }; while (tag = this._readTagBackward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (!tag.closing) { this._pop(stack, tag); if (stack.length == 0) { tag.start.column += tag.tagName.length + 2; return Range.fromPoints(tag.start, end); } } else { stack.push(tag) } } } }; }).call(FoldMode.prototype); });<|fim▁end|>
<|file_name|>rtconfig.py<|end_file_name|><|fim▁begin|>import os # toolchains options ARCH='arm' CPU='cortex-m7' CROSS_TOOL='gcc' # bsp lib config BSP_LIBRARY_TYPE = None if os.getenv('RTT_CC'): CROSS_TOOL = os.getenv('RTT_CC') if os.getenv('RTT_ROOT'): RTT_ROOT = os.getenv('RTT_ROOT') # cross_tool provides the cross compiler # EXEC_PATH is the compiler execute path, for example, CodeSourcery, Keil MDK, IAR if CROSS_TOOL == 'gcc': PLATFORM = 'gcc' EXEC_PATH = r'C:\Users\XXYYZZ' elif CROSS_TOOL == 'keil': PLATFORM = 'armcc' EXEC_PATH = r'C:/Keil_v5' elif CROSS_TOOL == 'iar': PLATFORM = 'iar' EXEC_PATH = r'C:/Program Files (x86)/IAR Systems/Embedded Workbench 8.0' if os.getenv('RTT_EXEC_PATH'): EXEC_PATH = os.getenv('RTT_EXEC_PATH') BUILD = 'debug' if PLATFORM == 'gcc': # toolchains PREFIX = 'arm-none-eabi-' CC = PREFIX + 'gcc' AS = PREFIX + 'gcc' AR = PREFIX + 'ar' CXX = PREFIX + 'g++' LINK = PREFIX + 'gcc' TARGET_EXT = 'elf' SIZE = PREFIX + 'size' OBJDUMP = PREFIX + 'objdump' OBJCPY = PREFIX + 'objcopy' DEVICE = ' -mcpu=cortex-m7 -mthumb -mfpu=fpv5-d16 -mfloat-abi=hard -ffunction-sections -fdata-sections' CFLAGS = DEVICE + ' -Dgcc' AFLAGS = ' -c' + DEVICE + ' -x assembler-with-cpp -Wa,-mimplicit-it=thumb ' LFLAGS = DEVICE + ' -Wl,--gc-sections,-Map=rt-thread.map,-cref,-u,Reset_Handler -T board/linker_scripts/link.lds' CPATH = '' LPATH = '' if BUILD == 'debug': CFLAGS += ' -O0 -gdwarf-2 -g' AFLAGS += ' -gdwarf-2' else: CFLAGS += ' -O2' CXXFLAGS = CFLAGS POST_ACTION = OBJCPY + ' -O binary $TARGET rtthread.bin\n' + SIZE + ' $TARGET \n' elif PLATFORM == 'armcc':<|fim▁hole|> CXX = 'armcc' AS = 'armasm' AR = 'armar' LINK = 'armlink' TARGET_EXT = 'axf' DEVICE = ' --cpu Cortex-M7.fp.sp' CFLAGS = '-c ' + DEVICE + ' --apcs=interwork --c99' AFLAGS = DEVICE + ' --apcs=interwork ' LFLAGS = DEVICE + ' --scatter "board\linker_scripts\link.sct" --info sizes --info totals --info unused --info veneers --list rt-thread.map --strict' CFLAGS += ' -I' + EXEC_PATH + '/ARM/ARMCC/include' LFLAGS += ' --libpath=' + EXEC_PATH + '/ARM/ARMCC/lib' CFLAGS += ' -D__MICROLIB ' AFLAGS += ' --pd "__MICROLIB SETA 1" ' LFLAGS += ' --library_type=microlib ' EXEC_PATH += '/ARM/ARMCC/bin/' if BUILD == 'debug': CFLAGS += ' -g -O0' AFLAGS += ' -g' else: CFLAGS += ' -O2' CXXFLAGS = CFLAGS CFLAGS += ' -std=c99' POST_ACTION = 'fromelf --bin $TARGET --output rtthread.bin \nfromelf -z $TARGET' elif PLATFORM == 'iar': # toolchains CC = 'iccarm' CXX = 'iccarm' AS = 'iasmarm' AR = 'iarchive' LINK = 'ilinkarm' TARGET_EXT = 'out' DEVICE = '-Dewarm' CFLAGS = DEVICE CFLAGS += ' --diag_suppress Pa050' CFLAGS += ' --no_cse' CFLAGS += ' --no_unroll' CFLAGS += ' --no_inline' CFLAGS += ' --no_code_motion' CFLAGS += ' --no_tbaa' CFLAGS += ' --no_clustering' CFLAGS += ' --no_scheduling' CFLAGS += ' --endian=little' CFLAGS += ' --cpu=Cortex-M7' CFLAGS += ' -e' CFLAGS += ' --fpu=VFPv5_sp' CFLAGS += ' --dlib_config "' + EXEC_PATH + '/arm/INC/c/DLib_Config_Normal.h"' CFLAGS += ' --silent' AFLAGS = DEVICE AFLAGS += ' -s+' AFLAGS += ' -w+' AFLAGS += ' -r' AFLAGS += ' --cpu Cortex-M7' AFLAGS += ' --fpu VFPv5_sp' AFLAGS += ' -S' if BUILD == 'debug': CFLAGS += ' --debug' CFLAGS += ' -On' else: CFLAGS += ' -Oh' LFLAGS = ' --config "board/linker_scripts/link.icf"' LFLAGS += ' --entry __iar_program_start' CXXFLAGS = CFLAGS EXEC_PATH = EXEC_PATH + '/arm/bin/' POST_ACTION = 'ielftool --bin $TARGET rtthread.bin' def dist_handle(BSP_ROOT, dist_dir): import sys cwd_path = os.getcwd() sys.path.append(os.path.join(os.path.dirname(BSP_ROOT), 'tools')) from sdk_dist import dist_do_building dist_do_building(BSP_ROOT, dist_dir)<|fim▁end|>
# toolchains CC = 'armcc'
<|file_name|>ScratchBuffer.cpp<|end_file_name|><|fim▁begin|>//===--- ScratchBuffer.cpp - Scratch space for forming tokens -------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the ScratchBuffer interface. // //===----------------------------------------------------------------------===// #include "clang/Lex/ScratchBuffer.h" #include "clang/Basic/SourceManager.h" #include "llvm/Support/MemoryBuffer.h" #include <cstring> using namespace clang; // ScratchBufSize - The size of each chunk of scratch memory. Slightly less //than a page, almost certainly enough for anything. :) static const unsigned ScratchBufSize = 4060; ScratchBuffer::ScratchBuffer(SourceManager &SM) : SourceMgr(SM), CurBuffer(0) { // Set BytesUsed so that the first call to getToken will require an alloc. BytesUsed = ScratchBufSize;<|fim▁hole|>/// return a SourceLocation that refers to the token. This is just like the /// method below, but returns a location that indicates the physloc of the /// token. SourceLocation ScratchBuffer::getToken(const char *Buf, unsigned Len, const char *&DestPtr) { if (BytesUsed+Len+2 > ScratchBufSize) AllocScratchBuffer(Len+2); // Prefix the token with a \n, so that it looks like it is the first thing on // its own virtual line in caret diagnostics. CurBuffer[BytesUsed++] = '\n'; // Return a pointer to the character data. DestPtr = CurBuffer+BytesUsed; // Copy the token data into the buffer. memcpy(CurBuffer+BytesUsed, Buf, Len); // Remember that we used these bytes. BytesUsed += Len+1; // Add a NUL terminator to the token. This keeps the tokens separated, in // case they get relexed, and puts them on their own virtual lines in case a // diagnostic points to one. CurBuffer[BytesUsed-1] = '\0'; return BufferStartLoc.getLocWithOffset(BytesUsed-Len-1); } void ScratchBuffer::AllocScratchBuffer(unsigned RequestLen) { // Only pay attention to the requested length if it is larger than our default // page size. If it is, we allocate an entire chunk for it. This is to // support gigantic tokens, which almost certainly won't happen. :) if (RequestLen < ScratchBufSize) RequestLen = ScratchBufSize; llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getNewMemBuffer(RequestLen, "<scratch space>"); FileID FID = SourceMgr.createFileIDForMemBuffer(Buf); BufferStartLoc = SourceMgr.getLocForStartOfFile(FID); CurBuffer = const_cast<char*>(Buf->getBufferStart()); BytesUsed = 1; CurBuffer[0] = '0'; // Start out with a \0 for cleanliness. }<|fim▁end|>
} /// getToken - Splat the specified text into a temporary MemoryBuffer and
<|file_name|>breadcrumbs.js<|end_file_name|><|fim▁begin|><|fim▁hole|>angular.module('breadcrumbs', []);<|fim▁end|>
<|file_name|>vote.ts<|end_file_name|><|fim▁begin|>import {Component, View} from 'angular2/angular2'; import {RouteParams} from 'angular2/router'; import {PlayerVote} from './PlayerVote';<|fim▁hole|>let template = require('./vote.html'); @Component({ selector: 'vote' }) @View({ template: template, directives: [PlayerVote] }) export class Vote { players; player; constructor(params: RouteParams, playerService: PlayerService) { this.players = playerService.get('players'); this.player = this.players[params.get('player')]; this.player.$index = params.get('player'); } }<|fim▁end|>
import {PlayerService} from '../../services/PlayerService';
<|file_name|>regions-early-bound-used-in-bound-method.rs<|end_file_name|><|fim▁begin|>// 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. // Tests that you can use a fn lifetime parameter as part of // the value for a type parameter in a bound. trait GetRef<'a> { fn get(&self) -> &'a isize; } #[derive(Copy, Clone)] struct Box<'a> { t: &'a isize<|fim▁hole|> self.t } } impl<'a> Box<'a> { fn add<'b,G:GetRef<'b>>(&self, g2: G) -> isize { *self.t + *g2.get() } } pub fn main() { let b1 = Box { t: &3 }; assert_eq!(b1.add(b1), 6); }<|fim▁end|>
} impl<'a> GetRef<'a> for Box<'a> { fn get(&self) -> &'a isize {
<|file_name|>index.js<|end_file_name|><|fim▁begin|>function __processArg(obj, key) { var arg = null; if (obj) { arg = obj[key] || null; delete obj[key]; } return arg; } function Controller() { require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments)); this.__controllerPath = "index"; this.args = arguments[0] || {};<|fim▁hole|> __processArg(arguments[0], "__parentSymbol"); } { __processArg(arguments[0], "$model"); } { __processArg(arguments[0], "__itemTemplate"); } } var $ = this; var exports = {}; $.__views.index = Ti.UI.createWindow({ backgroundColor: "#fff", fullscreen: false, exitOnClose: true, id: "index" }); $.__views.index && $.addTopLevelView($.__views.index); $.__views.__alloyId0 = Ti.UI.createLabel({ text: "This app is supported only on iOS", id: "__alloyId0" }); $.__views.index.add($.__views.__alloyId0); exports.destroy = function() {}; _.extend($, $.__views); $.index.open(); _.extend($, exports); } var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._; module.exports = Controller;<|fim▁end|>
if (arguments[0]) { {
<|file_name|>testlib.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright Martin Manns # Distributed under the terms of the GNU General Public License<|fim▁hole|># -------------------------------------------------------------------- # pyspread is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # pyspread is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with pyspread. If not, see <http://www.gnu.org/licenses/>. # -------------------------------------------------------------------- """ testlib.py ========== Helper functions for unit tests """ from copy import deepcopy import wx from src.lib.undo import stack as undo_stack # Standard grid values for initial filling grid_values = { \ (0, 0, 0): "'Test'", (999, 0, 0): "1", (999, 99, 0): "$^%&$^", (0, 1, 0): "1", (0, 2, 0): "2", (1, 1, 0): "3", (1, 2, 0): "4", (1, 2, 2): "78", } # Helper methods for efficient testing def _fill_grid(grid, values): """Fills grid with values (use e. g. grid_values)""" for key in values: grid.code_array[key] = values[key] def restore_basic_grid(grid): """Restores basic, filled grid""" default_test_shape = (1000, 100, 3) grid.actions.clear(default_test_shape) _fill_grid(grid, grid_values) def basic_setup_test(grid, func, test_key, test_val, *args, **kwargs): """Sets up basic test env, runs func and tests test_key in grid""" restore_basic_grid(grid) func(*args, **kwargs) grid.code_array.result_cache.clear() assert grid.code_array(test_key) == test_val def params(funcarglist): """Test function parameter decorator Provides arguments based on the dict funcarglist. """ def wrapper(function): function.funcarglist = funcarglist return function return wrapper def pytest_generate_tests(metafunc): """Enables params to work in py.test environment""" for funcargs in getattr(metafunc.function, 'funcarglist', ()): metafunc.addcall(funcargs=funcargs) def undo_test(grid): """Tests if the model is identical after an undo and a redo""" code_array = deepcopy(grid.code_array) undo_stack().undo() undo_stack().redo() assert code_array.dict_grid == grid.code_array.dict_grid assert code_array == grid.code_array def undotest_model(function): """Tests if the model is identical after an undo and a redo The wrapped function's self must be the code_array or the data_array. This function should be used nfor unit tests from within model.py """ def wrapper(self, *args, **kwargs): function(self, *args, **kwargs) code_array = deepcopy(self.data_array) undo_stack().undo() undo_stack().redo() assert code_array == self.data_array return wrapper<|fim▁end|>
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>use std::collections::HashSet; use std::hash::Hash; #[derive(Debug, PartialEq)] pub struct CustomSet<T: Hash + Eq> { store: HashSet<T>, } impl<T> CustomSet<T> where T: Hash + Eq, { pub fn new(list: Vec<T>) -> CustomSet<T> where T: Clone, { CustomSet { store: list.iter().cloned().collect(), } } pub fn is_empty(&self) -> bool { let h = &self.store; h.is_empty() } pub fn contains(&self, v: &T) -> bool { let h = &self.store; h.contains(v) } pub fn add(&mut self, v: T) -> bool { let h = &mut self.store; h.insert(v) } pub fn is_subset(&self, set: &CustomSet<T>) -> bool { let h = &self.store; h.is_subset(&set.store) } pub fn is_disjoint(&self, set: &CustomSet<T>) -> bool { let h = &self.store; h.is_disjoint(&set.store) } pub fn intersection(&self, set: &CustomSet<T>) -> CustomSet<T> where T: Clone, { let h = &self.store; CustomSet { store: h.intersection(&set.store).cloned().collect(), } }<|fim▁hole|> { let h = &self.store; CustomSet { store: h.difference(&set.store).cloned().collect(), } } pub fn union(&self, set: &CustomSet<T>) -> CustomSet<T> where T: Clone, { let h = &self.store; CustomSet { store: h.union(&set.store).cloned().collect(), } } }<|fim▁end|>
pub fn difference(&self, set: &CustomSet<T>) -> CustomSet<T> where T: Clone,
<|file_name|>debug.test.js<|end_file_name|><|fim▁begin|>var TestTime = require('logux-core').TestTime var ServerSync = require('../server-sync') var TestPair = require('../test-pair') var sync function createTest () { var test = new TestPair() sync = new ServerSync('server', TestTime.getLog(), test.left) test.leftSync = sync return test.left.connect().then(function () { return test }) } afterEach(function () { sync.destroy() }) it('sends debug messages', function () { return createTest().then(function (test) { test.leftSync.sendDebug('testType', 'testData') return test.wait('right') }).then(function (test) { expect(test.leftSent).toEqual([['debug', 'testType', 'testData']]) }) }) it('emits a debug on debug error messages', function () { var pair = new TestPair() sync = new ServerSync('server', TestTime.getLog(), pair.left)<|fim▁hole|> sync.authenticated = true var debugs = [] sync.on('debug', function (type, data) { debugs.push(type, data) }) sync.onMessage(['debug', 'error', 'testData']) expect(debugs).toEqual(['error', 'testData']) }) it('checks types', function () { var wrongs = [ ['debug'], ['debug', 0], ['debug', []], ['debug', {}, 'abc'], ['debug', 'error', 0], ['debug', 'error', []], ['debug', 'error', {}] ] return Promise.all(wrongs.map(function (command) { return createTest().then(function (test) { test.right.send(command) return test.wait('right') }).then(function (test) { expect(test.leftSync.connected).toBeFalsy() expect(test.leftSent).toEqual([ ['error', 'wrong-format', JSON.stringify(command)] ]) }) })) })<|fim▁end|>
<|file_name|>ex_244.py<|end_file_name|><|fim▁begin|>class WordDistance(object): def __init__(self, words): """ initialize your data structure here. :type words: List[str] """ self.word_dict = {} for idx, w in enumerate(words): self.word_dict[w] = self.word_dict.get(w, []) + [idx] def shortest(self, word1, word2): """ Adds a word into the data structure. :type word1: str :type word2: str :rtype: int """ return min(abs(i - j) for i in self.word_dict[word1] for j in self.word_dict[word2]) # Your WordDistance object will be instantiated and called as such: <|fim▁hole|># wordDistance = WordDistance(words) # wordDistance.shortest("word1", "word2") # wordDistance.shortest("anotherWord1", "anotherWord2")<|fim▁end|>
<|file_name|>virtualmachineruncommands.go<|end_file_name|><|fim▁begin|>package compute // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "context" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/validation" "github.com/Azure/go-autorest/tracing" "net/http" ) // VirtualMachineRunCommandsClient is the compute Client type VirtualMachineRunCommandsClient struct { BaseClient } // NewVirtualMachineRunCommandsClient creates an instance of the VirtualMachineRunCommandsClient client. func NewVirtualMachineRunCommandsClient(subscriptionID string) VirtualMachineRunCommandsClient { return NewVirtualMachineRunCommandsClientWithBaseURI(DefaultBaseURI, subscriptionID) } // NewVirtualMachineRunCommandsClientWithBaseURI creates an instance of the VirtualMachineRunCommandsClient client // using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign // clouds, Azure stack). func NewVirtualMachineRunCommandsClientWithBaseURI(baseURI string, subscriptionID string) VirtualMachineRunCommandsClient { return VirtualMachineRunCommandsClient{NewWithBaseURI(baseURI, subscriptionID)} } // Get gets specific run command for a subscription in a location. // Parameters: // location - the location upon which run commands is queried. // commandID - the command id. func (client VirtualMachineRunCommandsClient) Get(ctx context.Context, location string, commandID string) (result RunCommandDocument, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineRunCommandsClient.Get") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: location, Constraints: []validation.Constraint{{Target: "location", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}}); err != nil { return result, validation.NewError("compute.VirtualMachineRunCommandsClient", "Get", err.Error()) } req, err := client.GetPreparer(ctx, location, commandID) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "Get", nil, "Failure preparing request") return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "Get", resp, "Failure sending request") return } result, err = client.GetResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "Get", resp, "Failure responding to request") } return } // GetPreparer prepares the Get request. func (client VirtualMachineRunCommandsClient) GetPreparer(ctx context.Context, location string, commandID string) (*http.Request, error) { pathParameters := map[string]interface{}{ "commandId": autorest.Encode("path", commandID), "location": autorest.Encode("path", location), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2019-12-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/runCommands/{commandId}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineRunCommandsClient) GetSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // GetResponder handles the response to the Get request. The method always // closes the http.Response Body. func (client VirtualMachineRunCommandsClient) GetResponder(resp *http.Response) (result RunCommandDocument, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // List lists all available run commands for a subscription in a location. // Parameters: // location - the location upon which run commands is queried. func (client VirtualMachineRunCommandsClient) List(ctx context.Context, location string) (result RunCommandListResultPage, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineRunCommandsClient.List") defer func() { sc := -1 if result.rclr.Response.Response != nil { sc = result.rclr.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: location, Constraints: []validation.Constraint{{Target: "location", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}}); err != nil { return result, validation.NewError("compute.VirtualMachineRunCommandsClient", "List", err.Error()) } result.fn = client.listNextResults req, err := client.ListPreparer(ctx, location) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "List", nil, "Failure preparing request") return }<|fim▁hole|> result.rclr.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "List", resp, "Failure sending request") return } result.rclr, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "List", resp, "Failure responding to request") } return } // ListPreparer prepares the List request. func (client VirtualMachineRunCommandsClient) ListPreparer(ctx context.Context, location string) (*http.Request, error) { pathParameters := map[string]interface{}{ "location": autorest.Encode("path", location), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2019-12-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/runCommands", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineRunCommandsClient) ListSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // ListResponder handles the response to the List request. The method always // closes the http.Response Body. func (client VirtualMachineRunCommandsClient) ListResponder(resp *http.Response) (result RunCommandListResult, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // listNextResults retrieves the next set of results, if any. func (client VirtualMachineRunCommandsClient) listNextResults(ctx context.Context, lastResults RunCommandListResult) (result RunCommandListResult, err error) { req, err := lastResults.runCommandListResultPreparer(ctx) if err != nil { return result, autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "listNextResults", nil, "Failure preparing next results request") } if req == nil { return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} return result, autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "listNextResults", resp, "Failure sending next results request") } result, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "listNextResults", resp, "Failure responding to next results request") } return } // ListComplete enumerates all values, automatically crossing page boundaries as required. func (client VirtualMachineRunCommandsClient) ListComplete(ctx context.Context, location string) (result RunCommandListResultIterator, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineRunCommandsClient.List") defer func() { sc := -1 if result.Response().Response.Response != nil { sc = result.page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.page, err = client.List(ctx, location) return }<|fim▁end|>
resp, err := client.ListSender(req) if err != nil {
<|file_name|>homepage.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Copyright(C) 2013 Mathieu Jourdan # # This file is part of weboob.<|fim▁hole|># it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # weboob is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with weboob. If not, see <http://www.gnu.org/licenses/>. from datetime import date from weboob.deprecated.browser import Page from weboob.capabilities.bill import Subscription class LoginPage(Page): def login(self, login, password): self.browser.select_form('symConnexionForm') self.browser["portlet_login_plein_page_3{pageFlow.mForm.login}"] = unicode(login) self.browser["portlet_login_plein_page_3{pageFlow.mForm.password}"] = unicode(password) self.browser.submit() class HomePage(Page): def on_loaded(self): pass class AccountPage(Page): def get_subscription_list(self): table = self.document.xpath('//table[@id="ensemble_contrat_N0"]')[0] if len(table) > 0: # some clients may have subscriptions to gas and electricity, # but they receive a single bill # to avoid "boobill details" and "boobill bills" returning the same # table twice, we could return only one subscription for both. # We do not, and "boobill details" will take care of parsing only the # relevant section in the bill files. for line in table[0].xpath('//tbody/tr'): cells = line.xpath('td') snumber = cells[2].attrib['id'].replace('Contrat_', '') slabel = cells[0].xpath('a')[0].text.replace('offre', '').strip() d = unicode(cells[3].xpath('strong')[0].text.strip()) sdate = date(*reversed([int(x) for x in d.split("/")])) sub = Subscription(snumber) sub._id = snumber sub.label = slabel sub.subscriber = unicode(cells[1]) sub.renewdate = sdate yield sub class TimeoutPage(Page): def on_loaded(self): pass<|fim▁end|>
# # weboob is free software: you can redistribute it and/or modify
<|file_name|>A.js<|end_file_name|><|fim▁begin|>/* This file is part of Ext JS 4 Copyright (c) 2011 Sencha Inc Contact: http://www.sencha.com/contact Commercial Usage Licensees holding valid commercial licenses may use this file in accordance with the Commercial Software License Agreement provided with the Software or, alternatively, in accordance with the terms contained in a written agreement between you and Sencha. <|fim▁hole|>*/ Ext.define('Sample.notdeadlock.A', { extend: 'Sample.notdeadlock.B' });<|fim▁end|>
If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact.
<|file_name|>metrics.go<|end_file_name|><|fim▁begin|>// Copyright 2020 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package runtime // Metrics implementation exported to runtime/metrics. import ( "runtime/internal/atomic" "unsafe" ) var ( // metrics is a map of runtime/metrics keys to // data used by the runtime to sample each metric's // value. metricsSema uint32 = 1 metricsInit bool metrics map[string]metricData sizeClassBuckets []float64 timeHistBuckets []float64 ) type metricData struct { // deps is the set of runtime statistics that this metric // depends on. Before compute is called, the statAggregate // which will be passed must ensure() these dependencies. deps statDepSet // compute is a function that populates a metricValue // given a populated statAggregate structure. compute func(in *statAggregate, out *metricValue) } // initMetrics initializes the metrics map if it hasn't been yet. // // metricsSema must be held. func initMetrics() { if metricsInit { return } sizeClassBuckets = make([]float64, _NumSizeClasses) for i := range sizeClassBuckets { sizeClassBuckets[i] = float64(class_to_size[i]) } timeHistBuckets = timeHistogramMetricsBuckets() metrics = map[string]metricData{ "/gc/cycles/automatic:gc-cycles": { deps: makeStatDepSet(sysStatsDep), compute: func(in *statAggregate, out *metricValue) { out.kind = metricKindUint64 out.scalar = in.sysStats.gcCyclesDone - in.sysStats.gcCyclesForced }, }, "/gc/cycles/forced:gc-cycles": { deps: makeStatDepSet(sysStatsDep), compute: func(in *statAggregate, out *metricValue) { out.kind = metricKindUint64 out.scalar = in.sysStats.gcCyclesForced }, }, "/gc/cycles/total:gc-cycles": { deps: makeStatDepSet(sysStatsDep), compute: func(in *statAggregate, out *metricValue) { out.kind = metricKindUint64 out.scalar = in.sysStats.gcCyclesDone }, }, "/gc/heap/allocs-by-size:objects": { deps: makeStatDepSet(heapStatsDep), compute: func(in *statAggregate, out *metricValue) { hist := out.float64HistOrInit(sizeClassBuckets) hist.counts[len(hist.counts)-1] = uint64(in.heapStats.largeAllocCount) for i := range hist.buckets { hist.counts[i] = uint64(in.heapStats.smallAllocCount[i]) } }, }, "/gc/heap/frees-by-size:objects": { deps: makeStatDepSet(heapStatsDep), compute: func(in *statAggregate, out *metricValue) { hist := out.float64HistOrInit(sizeClassBuckets) hist.counts[len(hist.counts)-1] = uint64(in.heapStats.largeFreeCount) for i := range hist.buckets { hist.counts[i] = uint64(in.heapStats.smallFreeCount[i]) } }, }, "/gc/heap/goal:bytes": { deps: makeStatDepSet(sysStatsDep), compute: func(in *statAggregate, out *metricValue) { out.kind = metricKindUint64 out.scalar = in.sysStats.heapGoal }, }, "/gc/heap/objects:objects": { deps: makeStatDepSet(heapStatsDep), compute: func(in *statAggregate, out *metricValue) { out.kind = metricKindUint64 out.scalar = in.heapStats.numObjects }, }, "/gc/pauses:seconds": { compute: func(_ *statAggregate, out *metricValue) { hist := out.float64HistOrInit(timeHistBuckets) hist.counts[len(hist.counts)-1] = atomic.Load64(&memstats.gcPauseDist.overflow) for i := range hist.buckets { hist.counts[i] = atomic.Load64(&memstats.gcPauseDist.counts[i]) } }, }, "/memory/classes/heap/free:bytes": { deps: makeStatDepSet(heapStatsDep), compute: func(in *statAggregate, out *metricValue) { out.kind = metricKindUint64 out.scalar = uint64(in.heapStats.committed - in.heapStats.inHeap - in.heapStats.inStacks - in.heapStats.inWorkBufs - in.heapStats.inPtrScalarBits) }, }, "/memory/classes/heap/objects:bytes": { deps: makeStatDepSet(heapStatsDep), compute: func(in *statAggregate, out *metricValue) { out.kind = metricKindUint64 out.scalar = in.heapStats.inObjects }, }, "/memory/classes/heap/released:bytes": { deps: makeStatDepSet(heapStatsDep), compute: func(in *statAggregate, out *metricValue) { out.kind = metricKindUint64 out.scalar = uint64(in.heapStats.released) }, }, "/memory/classes/heap/stacks:bytes": { deps: makeStatDepSet(heapStatsDep), compute: func(in *statAggregate, out *metricValue) { out.kind = metricKindUint64 out.scalar = uint64(in.heapStats.inStacks) }, }, "/memory/classes/heap/unused:bytes": { deps: makeStatDepSet(heapStatsDep), compute: func(in *statAggregate, out *metricValue) { out.kind = metricKindUint64 out.scalar = uint64(in.heapStats.inHeap) - in.heapStats.inObjects }, }, "/memory/classes/metadata/mcache/free:bytes": { deps: makeStatDepSet(sysStatsDep), compute: func(in *statAggregate, out *metricValue) { out.kind = metricKindUint64 out.scalar = in.sysStats.mCacheSys - in.sysStats.mCacheInUse }, }, "/memory/classes/metadata/mcache/inuse:bytes": { deps: makeStatDepSet(sysStatsDep), compute: func(in *statAggregate, out *metricValue) { out.kind = metricKindUint64 out.scalar = in.sysStats.mCacheInUse }, }, "/memory/classes/metadata/mspan/free:bytes": { deps: makeStatDepSet(sysStatsDep), compute: func(in *statAggregate, out *metricValue) { out.kind = metricKindUint64 out.scalar = in.sysStats.mSpanSys - in.sysStats.mSpanInUse }, }, "/memory/classes/metadata/mspan/inuse:bytes": { deps: makeStatDepSet(sysStatsDep),<|fim▁hole|> out.scalar = in.sysStats.mSpanInUse }, }, "/memory/classes/metadata/other:bytes": { deps: makeStatDepSet(heapStatsDep, sysStatsDep), compute: func(in *statAggregate, out *metricValue) { out.kind = metricKindUint64 out.scalar = uint64(in.heapStats.inWorkBufs+in.heapStats.inPtrScalarBits) + in.sysStats.gcMiscSys }, }, "/memory/classes/os-stacks:bytes": { deps: makeStatDepSet(sysStatsDep), compute: func(in *statAggregate, out *metricValue) { out.kind = metricKindUint64 out.scalar = in.sysStats.stacksSys }, }, "/memory/classes/other:bytes": { deps: makeStatDepSet(sysStatsDep), compute: func(in *statAggregate, out *metricValue) { out.kind = metricKindUint64 out.scalar = in.sysStats.otherSys }, }, "/memory/classes/profiling/buckets:bytes": { deps: makeStatDepSet(sysStatsDep), compute: func(in *statAggregate, out *metricValue) { out.kind = metricKindUint64 out.scalar = in.sysStats.buckHashSys }, }, "/memory/classes/total:bytes": { deps: makeStatDepSet(heapStatsDep, sysStatsDep), compute: func(in *statAggregate, out *metricValue) { out.kind = metricKindUint64 out.scalar = uint64(in.heapStats.committed+in.heapStats.released) + in.sysStats.stacksSys + in.sysStats.mSpanSys + in.sysStats.mCacheSys + in.sysStats.buckHashSys + in.sysStats.gcMiscSys + in.sysStats.otherSys }, }, "/sched/goroutines:goroutines": { compute: func(_ *statAggregate, out *metricValue) { out.kind = metricKindUint64 out.scalar = uint64(gcount()) }, }, } metricsInit = true } // statDep is a dependency on a group of statistics // that a metric might have. type statDep uint const ( heapStatsDep statDep = iota // corresponds to heapStatsAggregate sysStatsDep // corresponds to sysStatsAggregate numStatsDeps ) // statDepSet represents a set of statDeps. // // Under the hood, it's a bitmap. type statDepSet [1]uint64 // makeStatDepSet creates a new statDepSet from a list of statDeps. func makeStatDepSet(deps ...statDep) statDepSet { var s statDepSet for _, d := range deps { s[d/64] |= 1 << (d % 64) } return s } // differennce returns set difference of s from b as a new set. func (s statDepSet) difference(b statDepSet) statDepSet { var c statDepSet for i := range s { c[i] = s[i] &^ b[i] } return c } // union returns the union of the two sets as a new set. func (s statDepSet) union(b statDepSet) statDepSet { var c statDepSet for i := range s { c[i] = s[i] | b[i] } return c } // empty returns true if there are no dependencies in the set. func (s *statDepSet) empty() bool { for _, c := range s { if c != 0 { return false } } return true } // has returns true if the set contains a given statDep. func (s *statDepSet) has(d statDep) bool { return s[d/64]&(1<<(d%64)) != 0 } // heapStatsAggregate represents memory stats obtained from the // runtime. This set of stats is grouped together because they // depend on each other in some way to make sense of the runtime's // current heap memory use. They're also sharded across Ps, so it // makes sense to grab them all at once. type heapStatsAggregate struct { heapStatsDelta // Derived from values in heapStatsDelta. // inObjects is the bytes of memory occupied by objects, inObjects uint64 // numObjects is the number of live objects in the heap. numObjects uint64 } // compute populates the heapStatsAggregate with values from the runtime. func (a *heapStatsAggregate) compute() { memstats.heapStats.read(&a.heapStatsDelta) // Calculate derived stats. a.inObjects = uint64(a.largeAlloc - a.largeFree) a.numObjects = uint64(a.largeAllocCount - a.largeFreeCount) for i := range a.smallAllocCount { n := uint64(a.smallAllocCount[i] - a.smallFreeCount[i]) a.inObjects += n * uint64(class_to_size[i]) a.numObjects += n } } // sysStatsAggregate represents system memory stats obtained // from the runtime. This set of stats is grouped together because // they're all relatively cheap to acquire and generally independent // of one another and other runtime memory stats. The fact that they // may be acquired at different times, especially with respect to // heapStatsAggregate, means there could be some skew, but because of // these stats are independent, there's no real consistency issue here. type sysStatsAggregate struct { stacksSys uint64 mSpanSys uint64 mSpanInUse uint64 mCacheSys uint64 mCacheInUse uint64 buckHashSys uint64 gcMiscSys uint64 otherSys uint64 heapGoal uint64 gcCyclesDone uint64 gcCyclesForced uint64 } // compute populates the sysStatsAggregate with values from the runtime. func (a *sysStatsAggregate) compute() { a.stacksSys = memstats.stacks_sys.load() a.buckHashSys = memstats.buckhash_sys.load() a.gcMiscSys = memstats.gcMiscSys.load() a.otherSys = memstats.other_sys.load() a.heapGoal = atomic.Load64(&memstats.next_gc) a.gcCyclesDone = uint64(memstats.numgc) a.gcCyclesForced = uint64(memstats.numforcedgc) systemstack(func() { lock(&mheap_.lock) a.mSpanSys = memstats.mspan_sys.load() a.mSpanInUse = uint64(mheap_.spanalloc.inuse) a.mCacheSys = memstats.mcache_sys.load() a.mCacheInUse = uint64(mheap_.cachealloc.inuse) unlock(&mheap_.lock) }) } // statAggregate is the main driver of the metrics implementation. // // It contains multiple aggregates of runtime statistics, as well // as a set of these aggregates that it has populated. The aggergates // are populated lazily by its ensure method. type statAggregate struct { ensured statDepSet heapStats heapStatsAggregate sysStats sysStatsAggregate } // ensure populates statistics aggregates determined by deps if they // haven't yet been populated. func (a *statAggregate) ensure(deps *statDepSet) { missing := deps.difference(a.ensured) if missing.empty() { return } for i := statDep(0); i < numStatsDeps; i++ { if !missing.has(i) { continue } switch i { case heapStatsDep: a.heapStats.compute() case sysStatsDep: a.sysStats.compute() } } a.ensured = a.ensured.union(missing) } // metricValidKind is a runtime copy of runtime/metrics.ValueKind and // must be kept structurally identical to that type. type metricKind int const ( // These values must be kept identical to their corresponding Kind* values // in the runtime/metrics package. metricKindBad metricKind = iota metricKindUint64 metricKindFloat64 metricKindFloat64Histogram ) // metricSample is a runtime copy of runtime/metrics.Sample and // must be kept structurally identical to that type. type metricSample struct { name string value metricValue } // metricValue is a runtime copy of runtime/metrics.Sample and // must be kept structurally identical to that type. type metricValue struct { kind metricKind scalar uint64 // contains scalar values for scalar Kinds. pointer unsafe.Pointer // contains non-scalar values. } // float64HistOrInit tries to pull out an existing float64Histogram // from the value, but if none exists, then it allocates one with // the given buckets. func (v *metricValue) float64HistOrInit(buckets []float64) *metricFloat64Histogram { var hist *metricFloat64Histogram if v.kind == metricKindFloat64Histogram && v.pointer != nil { hist = (*metricFloat64Histogram)(v.pointer) } else { v.kind = metricKindFloat64Histogram hist = new(metricFloat64Histogram) v.pointer = unsafe.Pointer(hist) } hist.buckets = buckets if len(hist.counts) != len(hist.buckets)+1 { hist.counts = make([]uint64, len(buckets)+1) } return hist } // metricFloat64Histogram is a runtime copy of runtime/metrics.Float64Histogram // and must be kept structurally identical to that type. type metricFloat64Histogram struct { counts []uint64 buckets []float64 } // agg is used by readMetrics, and is protected by metricsSema. // // Managed as a global variable because its pointer will be // an argument to a dynamically-defined function, and we'd // like to avoid it escaping to the heap. var agg statAggregate // readMetrics is the implementation of runtime/metrics.Read. // //go:linkname readMetrics runtime_1metrics.runtime__readMetrics func readMetrics(samplesp unsafe.Pointer, len int, cap int) { // Construct a slice from the args. sl := slice{samplesp, len, cap} samples := *(*[]metricSample)(unsafe.Pointer(&sl)) // Acquire the metricsSema but with handoff. This operation // is expensive enough that queueing up goroutines and handing // off between them will be noticably better-behaved. semacquire1(&metricsSema, true, 0, 0) // Ensure the map is initialized. initMetrics() // Clear agg defensively. agg = statAggregate{} // Sample. for i := range samples { sample := &samples[i] data, ok := metrics[sample.name] if !ok { sample.value.kind = metricKindBad continue } // Ensure we have all the stats we need. // agg is populated lazily. agg.ensure(&data.deps) // Compute the value based on the stats we have. data.compute(&agg, &sample.value) } semrelease(&metricsSema) }<|fim▁end|>
compute: func(in *statAggregate, out *metricValue) { out.kind = metricKindUint64
<|file_name|>test_kubernetes_executor.py<|end_file_name|><|fim▁begin|># Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import time import pytest from kubernetes_tests.test_base import EXECUTOR, TestBase <|fim▁hole|>class TestKubernetesExecutor(TestBase): def test_integration_run_dag(self): dag_id = 'example_kubernetes_executor' dag_run_id, execution_date = self.start_job_in_kubernetes(dag_id, self.host) print(f"Found the job with execution_date {execution_date}") # Wait some time for the operator to complete self.monitor_task( host=self.host, dag_run_id=dag_run_id, dag_id=dag_id, task_id='start_task', expected_final_state='success', timeout=300, ) self.ensure_dag_expected_state( host=self.host, execution_date=execution_date, dag_id=dag_id, expected_final_state='success', timeout=300, ) def test_integration_run_dag_with_scheduler_failure(self): dag_id = 'example_kubernetes_executor' dag_run_id, execution_date = self.start_job_in_kubernetes(dag_id, self.host) self._delete_airflow_pod("scheduler") time.sleep(10) # give time for pod to restart # Wait some time for the operator to complete self.monitor_task( host=self.host, dag_run_id=dag_run_id, dag_id=dag_id, task_id='start_task', expected_final_state='success', timeout=300, ) self.monitor_task( host=self.host, dag_run_id=dag_run_id, dag_id=dag_id, task_id='other_namespace_task', expected_final_state='success', timeout=300, ) self.ensure_dag_expected_state( host=self.host, execution_date=execution_date, dag_id=dag_id, expected_final_state='success', timeout=300, ) assert self._num_pods_in_namespace('test-namespace') == 0, "failed to delete pods in other namespace"<|fim▁end|>
@pytest.mark.skipif(EXECUTOR != 'KubernetesExecutor', reason="Only runs on KubernetesExecutor")
<|file_name|>headerfooter.js<|end_file_name|><|fim▁begin|>/*- * #%L * ARROWHEAD::WP5::Market Manager * %% * Copyright (C) 2016 The ARROWHEAD Consortium * %% * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell<|fim▁hole|> * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * #L% */ 'use strict'; angular.module('marketManApp') .controller('HeaderCtrl', function ($scope, $location, $timeout, serviceMarket) { $scope.isActive = function (viewLocation) { return viewLocation === $location.path(); }; $scope.connect = function(connect) { var c = new serviceMarket.Connection(); c.value = connect; c.$save(); }; $scope.isConnected = { value: false }; (function tick() { serviceMarket.Connection.get().$promise.then( function(val) { $scope.isConnected = val; }, function(error){ $scope.isConnected = null; }); $timeout(tick, 2000); })(); });<|fim▁end|>
* copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions:
<|file_name|>response.js<|end_file_name|><|fim▁begin|>"use strict"; var Response = (function () { function Response(result, childWork) { this.result = result; this.childWork = childWork; } return Response;<|fim▁hole|>exports.default = Response; //# sourceMappingURL=response.js.map<|fim▁end|>
}()); Object.defineProperty(exports, "__esModule", { value: true });
<|file_name|>test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 import Parser, Lexer from DSL import _lexerParser, _lexerLexer from DSL import _parserLexer, _parserParser from DSL import makeParser, makeLexer lexerLexerConfig = r"""#dsl %keys ::= '%ignore' '%keys' '::=' comment ::= /#[^\n]*\n/ identifier ::= /[_a-zA-Z][_a-zA-Z0-9]*/ sqString ::= /'[^']*'/ dqString ::= /"[^"\\]*(\\\\.[^"\\]*)*"/ reString ::= /\/[^\/\\]*(\\\\.[^\/\\]*)*\// %ignore ::= comment """ lexerLexer = makeLexer(lexerLexerConfig) lexerParserConfig = r"""#dsl LexRules ::= rule* rule ::= identifier '::=' (sqString | dqString | reString) | '%keys' '::=' (sqString | dqString)+ | '%ignore' '::=' (identifier | sqString | dqString)+ %ignore ::= '::=' """ lexerParser = makeParser(lexerParserConfig) parserLexerConfig = r"""#dsl %keys ::= '$' '|' '::=' '(' ')' '*' '+' '?' identifier ::= /[_a-zA-Z][_a-zA-Z0-9]*/ configType ::= /%(ignore|expandSingle|expand)/ sqString ::= /'[^']*'/ dqString ::= /"[^"\\]*(\\\\.[^"\\]*)*"/ comment ::= /#[^\n]*\n/ %ignore ::= comment """ parserLexer = makeLexer(parserLexerConfig) parserParserConfig = r"""#dsl ParseRules ::= rule* rule ::= identifier '::=' alternate ('|' alternate)* | configType '::=' simpleItem+ alternate ::= '$' | rhsItem+ rhsItem ::= itemValue ('?' | '+' | '*')? itemValue ::= simpleItem | '(' alternate ('|' alternate)* ')' simpleItem ::= identifier | dqString | sqString %ignore ::= '::=' '|' '$' '(' ')' %expand ::= simpleItem """ parserParser = makeParser(parserParserConfig) <|fim▁hole|>assert(str(realOutput) == str(testOutput)) realOutput = _lexerParser.parse(_lexerLexer.parse(parserLexerConfig)) testOutput = lexerParser.parse(lexerLexer.parse(parserLexerConfig)) assert(str(realOutput) == str(testOutput)) realOutput = _parserParser.parse(_parserLexer.parse(lexerParserConfig)) testOutput = parserParser.parse(parserLexer.parse(lexerParserConfig)) assert(str(realOutput) == str(testOutput)) realOutput = _parserParser.parse(_parserLexer.parse(parserParserConfig)) testOutput = parserParser.parse(parserLexer.parse(parserParserConfig)) assert(str(realOutput) == str(testOutput)) print('YA!')<|fim▁end|>
realOutput = _lexerParser.parse(_lexerLexer.parse(lexerLexerConfig)) testOutput = lexerParser.parse(lexerLexer.parse(lexerLexerConfig))
<|file_name|>codeship-notifications.js<|end_file_name|><|fim▁begin|>'use babel';<|fim▁hole|> const addError = ({ project, branch, build, endDate, commit }) => { const relativeTime = moment(endDate).fromNow(); atom.notifications.addError(`Build #${build.id} has failed`, { buttons: [ { onDidClick() { openUrl(`https://app.codeship.com/projects/${project.id}/builds/${build.id}`); this.model.dismiss(); }, text: 'View Details', }, { text: 'Dismiss', onDidClick() { this.model.dismiss(); }, }, ], description: `**branch:** ${branch}<br />**commit:** ${commit.message}`, detail: `The build for ${project.name} failed ${relativeTime}, view details to find out why.`, dismissable: true, icon: 'alert', }); }; const addStart = () => {}; const addSuccess = () => {}; export { addError, addStart, addSuccess };<|fim▁end|>
import moment from 'moment'; import openUrl from 'opn';
<|file_name|>test.main.js<|end_file_name|><|fim▁begin|>/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var tape = require( 'tape' ); var Readable = require( 'readable-stream' ).Readable; var now = require( '@stdlib/time/now' ); var arcsine = require( '@stdlib/random/base/arcsine' ).factory; var isBuffer = require( '@stdlib/assert/is-buffer' ); var isnan = require( '@stdlib/math/base/assert/is-nan' ); var isUint32Array = require( '@stdlib/assert/is-uint32array' ); var UINT32_MAX = require( '@stdlib/constants/uint32/max' ); var Uint32Array = require( '@stdlib/array/uint32' ); var minstd = require( '@stdlib/random/base/minstd' ); var inspectStream = require( '@stdlib/streams/node/inspect-sink' ); var randomStream = require( './../lib/main.js' ); // TESTS // tape( 'main export is a function', function test( t ) { t.ok( true, __filename ); t.equal( typeof randomStream, 'function', 'main export is a function' ); t.end(); }); tape( 'the function throws an error if minimum support `a` is not a number primitive', function test( t ) { var values; var i; values = [ '5', null, true, false, void 0, NaN, [], {}, function noop() {} ]; for ( i = 0; i < values.length; i++ ) { t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); } t.end(); function badValue( value ) { return function badValue() { randomStream( value, 2.0 ); }; } }); tape( 'the function throws an error if maximum support `b` is not a number primitive', function test( t ) { var values; var i; values = [ '5', null, true, false, void 0, NaN, [], {}, function noop() {} ]; for ( i = 0; i < values.length; i++ ) { t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); } t.end(); function badValue( value ) { return function badValue() { randomStream( 2.0, value ); }; } }); tape( 'the function throws an error if minimum support `a` is greater than or equal to maximum support `b`', function test( t ) { var values; var i; values = [ [ 0.0, 0.0 ], [ -2.0, -4.0 ], [ 2.0, 1.0 ] ]; for ( i = 0; i < values.length; i++ ) { t.throws( badValue( values[i] ), RangeError, 'throws an error when provided '+values[i] ); } t.end(); function badValue( arr ) { return function badValue() { randomStream( arr[0], arr[1] ); }; } }); tape( 'the function throws an error if provided an options argument which is not an object', function test( t ) { var values; var i; values = [ 'abc', 5, null, true, false, void 0, NaN, [], function noop() {} ]; for ( i = 0; i < values.length; i++ ) { t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); } t.end(); function badValue( value ) { return function badValue() { randomStream( 2.0, 5.0, value ); }; } }); tape( 'the function throws an error if provided an invalid `iter` option', function test( t ) { var values; var i; values = [ 'abc', -5, 3.14, null, true, false, void 0, NaN, [], {}, function noop() {} ]; for ( i = 0; i < values.length; i++ ) { t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); } t.end(); function badValue( value ) { return function badValue() { randomStream( 2.0, 5.0, { 'iter': value }); }; } }); tape( 'if provided a `prng` option which is not a function, the function throws an error', function test( t ) { var values; var i; values = [ '5', 3.14, NaN, true, false, null, void 0, [], {} ]; for ( i = 0; i < values.length; i++ ) { t.throws( badValue( values[i] ), TypeError, 'throws a type error when provided '+values[i] ); } t.end(); function badValue( value ) { return function badValue() { randomStream( 2.0, 5.0, { 'prng': value }); }; } }); tape( 'if provided a `copy` option which is not a boolean, the function throws an error', function test( t ) { var values; var i; values = [ '5', 5, NaN, null, void 0, {}, [], function noop() {} ]; for ( i = 0; i < values.length; i++ ) { t.throws( badValue( values[i] ), TypeError, 'throws a type error when provided '+values[i] ); } t.end();<|fim▁hole|> function badValue( value ) { return function badValue() { randomStream( 2.0, 5.0, { 'copy': value }); }; } }); tape( 'if provided a `seed` which is not a positive integer or a non-empty array-like object, the function throws an error', function test( t ) { var values; var i; values = [ '5', 3.14, 0.0, -5.0, NaN, true, false, null, void 0, {}, [], function noop() {} ]; for ( i = 0; i < values.length; i++ ) { t.throws( badValue( values[i] ), TypeError, 'throws a type error when provided '+values[i] ); } t.end(); function badValue( value ) { return function badValue() { randomStream( 2.0, 5.0, { 'seed': value }); }; } }); tape( 'the function throws a range error if provided a `seed` which is an integer greater than the maximum unsigned 32-bit integer', function test( t ) { var values; var i; values = [ UINT32_MAX + 1, UINT32_MAX + 2, UINT32_MAX + 3 ]; for ( i = 0; i < values.length; i++ ) { t.throws( badValue( values[i] ), RangeError, 'throws a range error when provided '+values[i] ); } t.end(); function badValue( value ) { return function badValue() { randomStream( 2.0, 5.0, { 'seed': value }); }; } }); tape( 'if provided a `state` option which is not a Uint32Array, the function throws an error', function test( t ) { var values; var i; values = [ '5', 5, NaN, true, false, null, void 0, {}, [], function noop() {} ]; for ( i = 0; i < values.length; i++ ) { t.throws( badValue( values[i] ), TypeError, 'throws a type error when provided '+values[i] ); } t.end(); function badValue( value ) { return function badValue() { randomStream( 2.0, 5.0, { 'state': value }); }; } }); tape( 'if provided an invalid `state` option, the function throws an error', function test( t ) { var values; var i; values = [ new Uint32Array( 0 ), new Uint32Array( 10 ), new Uint32Array( 100 ) ]; for ( i = 0; i < values.length; i++ ) { t.throws( badValue( values[i] ), RangeError, 'throws an error when provided '+values[i] ); } t.end(); function badValue( value ) { return function badValue() { randomStream( 2.0, 5.0, { 'state': value }); }; } }); tape( 'if provided an invalid readable stream option, the function throws an error', function test( t ) { var values; var i; values = [ '5', 5, NaN, null, void 0, {}, [], function noop() {} ]; for ( i = 0; i < values.length; i++ ) { t.throws( badValue( values[i] ), TypeError, 'throws a type error when provided '+values[i] ); } t.end(); function badValue( value ) { return function badValue() { randomStream( 2.0, 5.0, { 'objectMode': value }); }; } }); tape( 'the function is a constructor which returns a readable stream', function test( t ) { var RandomStream = randomStream; var s; s = new RandomStream( 2.0, 5.0 ); t.equal( s instanceof Readable, true, 'returns expected value' ); t.end(); }); tape( 'the constructor does not require the `new` operator', function test( t ) { var RandomStream = randomStream; var s; s = randomStream( 2.0, 5.0 ); t.equal( s instanceof RandomStream, true, 'returns expected value' ); t.end(); }); tape( 'the constructor returns a readable stream (no new)', function test( t ) { var s = randomStream( 2.0, 5.0 ); t.equal( s instanceof Readable, true, 'returns expected value' ); t.end(); }); tape( 'the returned stream provides a method to destroy a stream (object)', function test( t ) { var count = 0; var s; s = randomStream( 2.0, 5.0 ); t.equal( typeof s.destroy, 'function', 'has destroy method' ); s.on( 'error', onError ); s.on( 'close', onClose ); s.destroy({ 'message': 'beep' }); function onError( err ) { count += 1; if ( err ) { t.ok( true, err.message ); } else { t.ok( false, 'does not error' ); } if ( count === 2 ) { t.end(); } } function onClose() { count += 1; t.ok( true, 'stream closes' ); if ( count === 2 ) { t.end(); } } }); tape( 'the returned stream provides a method to destroy a stream (error object)', function test( t ) { var count = 0; var s; s = randomStream( 2.0, 5.0 ); t.equal( typeof s.destroy, 'function', 'has destroy method' ); s.on( 'error', onError ); s.on( 'close', onClose ); s.destroy( new Error( 'beep' ) ); function onError( err ) { count += 1; if ( err ) { t.ok( true, err.message ); } else { t.ok( false, 'does not error' ); } if ( count === 2 ) { t.end(); } } function onClose() { count += 1; t.ok( true, 'stream closes' ); if ( count === 2 ) { t.end(); } } }); tape( 'the returned stream does not allow itself to be destroyed more than once', function test( t ) { var s; s = randomStream( 2.0, 5.0 ); s.on( 'error', onError ); s.on( 'close', onClose ); // If the stream is closed twice, the test will error... s.destroy(); s.destroy(); function onClose() { t.ok( true, 'stream closes' ); t.end(); } function onError( err ) { t.ok( false, err.message ); } }); tape( 'attached to the returned stream is the underlying PRNG', function test( t ) { var s = randomStream( 2.0, 5.0 ); t.equal( typeof s.PRNG, 'function', 'has property' ); s = randomStream( 2.0, 5.0, { 'prng': minstd.normalized }); t.equal( s.PRNG, minstd.normalized, 'has property' ); t.end(); }); tape( 'attached to the returned stream is the generator seed', function test( t ) { var s = randomStream( 2.0, 5.0, { 'seed': 12345 }); t.equal( isUint32Array( s.seed ), true, 'has property' ); t.equal( s.seed[ 0 ], 12345, 'equal to provided seed' ); s = randomStream( 2.0, 5.0, { 'seed': 12345, 'prng': minstd.normalized }); t.equal( s.seed, null, 'equal to `null`' ); t.end(); }); tape( 'attached to the returned stream is the generator seed (array seed)', function test( t ) { var actual; var seed; var s; var i; seed = [ 1234, 5678 ]; s = randomStream( 2.0, 5.0, { 'seed': seed }); actual = s.seed; t.equal( isUint32Array( actual ), true, 'has property' ); for ( i = 0; i < seed.length; i++ ) { t.equal( actual[ i ], seed[ i ], 'returns expected value for word '+i ); } t.end(); }); tape( 'attached to the returned stream is the generator seed length', function test( t ) { var s = randomStream( 2.0, 5.0 ); t.equal( typeof s.seedLength, 'number', 'has property' ); s = randomStream( 2.0, 5.0, { 'prng': minstd.normalized }); t.equal( s.seedLength, null, 'equal to `null`' ); t.end(); }); tape( 'attached to the returned stream is the generator state', function test( t ) { var s = randomStream( 2.0, 5.0 ); t.equal( isUint32Array( s.state ), true, 'has property' ); s = randomStream( 2.0, 5.0, { 'prng': minstd.normalized }); t.equal( s.state, null, 'equal to `null`' ); t.end(); }); tape( 'attached to the returned stream is the generator state length', function test( t ) { var s = randomStream( 2.0, 5.0 ); t.equal( typeof s.stateLength, 'number', 'has property' ); s = randomStream( 2.0, 5.0, { 'prng': minstd.normalized }); t.equal( s.stateLength, null, 'equal to `null`' ); t.end(); }); tape( 'attached to the returned stream is the generator state size', function test( t ) { var s = randomStream( 2.0, 5.0 ); t.equal( typeof s.byteLength, 'number', 'has property' ); s = randomStream( 2.0, 5.0, { 'prng': minstd.normalized }); t.equal( s.byteLength, null, 'equal to `null`' ); t.end(); }); tape( 'the constructor returns a stream for generating pseudorandom numbers from an arcsine distribution', function test( t ) { var iStream; var result; var rand; var opts; var s; // Note: we assume that the underlying generator is the following PRNG... rand = arcsine( 2.0, 5.0, { 'seed': 12345 }); opts = { 'seed': 12345, 'iter': 10, 'sep': '\n' }; s = randomStream( 2.0, 5.0, opts ); s.on( 'end', onEnd ); opts = { 'objectMode': true }; iStream = inspectStream( opts, inspect ); result = ''; s.pipe( iStream ); function inspect( chunk ) { t.equal( isBuffer( chunk ), true, 'returns a buffer' ); result += chunk.toString(); } function onEnd() { var i; t.pass( 'stream ended' ); result = result.split( '\n' ); t.equal( result.length, 10, 'has expected length' ); for ( i = 0; i < result.length; i++ ) { t.equal( parseFloat( result[ i ] ), rand(), 'returns expected value. i: ' + i + '.' ); } t.end(); } }); tape( 'the constructor returns a stream for generating pseudorandom numbers from an arcsine distribution (object mode)', function test( t ) { var iStream; var count; var rand; var opts; var s; // Note: we assume that the underlying generator is the following PRNG... rand = arcsine( 2.0, 5.0, { 'seed': 12345 }); opts = { 'seed': 12345, 'objectMode': true }; s = randomStream( 2.0, 5.0, opts ); s.on( 'close', onClose ); opts = { 'objectMode': true }; iStream = inspectStream( opts, inspect ); count = 0; s.pipe( iStream ); function inspect( v ) { count += 1; t.equal( rand(), v, 'returns expected value. i: '+count+'.' ); if ( count >= 10 ) { s.destroy(); } } function onClose() { t.pass( 'stream closed' ); t.end(); } }); tape( 'the constructor supports limiting the number of iterations', function test( t ) { var iStream; var count; var niter; var opts; var s; niter = 10; count = 0; opts = { 'iter': niter, 'objectMode': true }; s = randomStream( 2.0, 5.0, opts ); s.on( 'end', onEnd ); opts = { 'objectMode': true }; iStream = inspectStream( opts, inspect ); s.pipe( iStream ); function inspect( v ) { count += 1; t.equal( typeof v, 'number', 'returns expected value' ); } function onEnd() { t.equal( count === niter, true, 'performs expected number of iterations' ); t.end(); } }); tape( 'by default, the constructor generates newline-delimited pseudorandom numbers', function test( t ) { var iStream; var result; var opts; var s; opts = { 'iter': 10 }; s = randomStream( 2.0, 5.0, opts ); s.on( 'end', onEnd ); iStream = inspectStream( inspect ); result = ''; s.pipe( iStream ); function inspect( chunk ) { result += chunk.toString(); } function onEnd() { var v; var i; result = result.split( '\n' ); t.equal( result.length, opts.iter, 'has expected length' ); for ( i = 0; i < result.length; i++ ) { v = parseFloat( result[ i ] ); t.equal( typeof v, 'number', 'returns expected value' ); t.equal( isnan( v ), false, 'is not NaN' ); } t.end(); } }); tape( 'the constructor supports providing a custom separator for streamed values', function test( t ) { var iStream; var result; var opts; var s; opts = { 'iter': 10, 'sep': '--++--' }; s = randomStream( 2.0, 5.0, opts ); s.on( 'end', onEnd ); iStream = inspectStream( inspect ); result = ''; s.pipe( iStream ); function inspect( chunk ) { result += chunk.toString(); } function onEnd() { var v; var i; result = result.split( opts.sep ); t.equal( result.length, opts.iter, 'has expected length' ); for ( i = 0; i < result.length; i++ ) { v = parseFloat( result[ i ] ); t.equal( typeof v, 'number', 'returns expected value' ); t.equal( isnan( v ), false, 'is not NaN' ); } t.end(); } }); tape( 'the constructor supports returning a seeded readable stream', function test( t ) { var iStream; var opts; var seed; var arr; var s1; var s2; var i; seed = now(); opts = { 'objectMode': true, 'seed': seed, 'iter': 10 }; s1 = randomStream( 2.0, 5.0, opts ); s1.on( 'end', onEnd1 ); s2 = randomStream( 2.0, 5.0, opts ); s2.on( 'end', onEnd2 ); t.notEqual( s1, s2, 'separate streams' ); opts = { 'objectMode': true }; iStream = inspectStream( opts, inspect1 ); arr = []; i = 0; s1.pipe( iStream ); function inspect1( v ) { arr.push( v ); } function onEnd1() { var iStream; var opts; opts = { 'objectMode': true }; iStream = inspectStream( opts, inspect2 ); s2.pipe( iStream ); } function inspect2( v ) { t.equal( v, arr[ i ], 'returns expected value' ); i += 1; } function onEnd2() { t.end(); } }); tape( 'the constructor supports specifying the underlying PRNG', function test( t ) { var iStream; var opts; var s; opts = { 'prng': minstd.normalized, 'objectMode': true, 'iter': 10 }; s = randomStream( 2.0, 5.0, opts ); s.on( 'end', onEnd ); opts = { 'objectMode': true }; iStream = inspectStream( opts, inspect ); s.pipe( iStream ); function inspect( v ) { t.equal( typeof v, 'number', 'returns a number' ); } function onEnd() { t.end(); } }); tape( 'the constructor supports providing a seeded underlying PRNG', function test( t ) { var iStream1; var iStream2; var randu; var seed; var opts; var FLG; var s1; var s2; var r1; var r2; seed = now(); randu = minstd.factory({ 'seed': seed }); opts = { 'prng': randu.normalized, 'objectMode': true, 'iter': 10 }; s1 = randomStream( 2.0, 5.0, opts ); s1.on( 'end', onEnd ); randu = minstd.factory({ 'seed': seed }); opts = { 'prng': randu.normalized, 'objectMode': true, 'iter': 10 }; s2 = randomStream( 2.0, 5.0, opts ); s2.on( 'end', onEnd ); t.notEqual( s1, s2, 'separate streams' ); opts = { 'objectMode': true }; iStream1 = inspectStream( opts, inspect1 ); iStream2 = inspectStream( opts, inspect2 ); r1 = []; r2 = []; s1.pipe( iStream1 ); s2.pipe( iStream2 ); function inspect1( v ) { r1.push( v ); } function inspect2( v ) { r2.push( v ); } function onEnd() { if ( FLG ) { t.deepEqual( r1, r2, 'streams expected values' ); return t.end(); } FLG = true; } }); tape( 'the constructor supports specifying the underlying generator state', function test( t ) { var iStream; var state; var count; var opts; var arr; var s; opts = { 'objectMode': true, 'iter': 10, 'siter': 5 }; s = randomStream( 2.0, 5.0, opts ); s.on( 'state', onState ); s.on( 'end', onEnd1 ); opts = { 'objectMode': true }; iStream = inspectStream( opts, inspect1 ); count = 0; arr = []; // Move to a future state... s.pipe( iStream ); function onState( s ) { // Only capture the first emitted state... if ( !state ) { state = s; } } function inspect1( v ) { count += 1; if ( count > 5 ) { arr.push( v ); } } function onEnd1() { var iStream; var opts; var s; t.pass( 'first stream ended' ); // Create another stream using the captured state: opts = { 'objectMode': true, 'iter': 5, 'state': state }; s = randomStream( 2.0, 5.0, opts ); s.on( 'end', onEnd2 ); t.deepEqual( state, s.state, 'same state' ); // Create a new inspect stream: opts = { 'objectMode': true }; iStream = inspectStream( opts, inspect2 ); // Replay previously generated values... count = 0; s.pipe( iStream ); } function inspect2( v ) { count += 1; t.equal( v, arr[ count-1 ], 'returns expected value. i: '+(count-1)+'.' ); } function onEnd2() { t.pass( 'second stream ended' ); t.end(); } }); tape( 'the constructor supports specifying a shared underlying generator state', function test( t ) { var iStream; var shared; var state; var count; var opts; var arr; var s; opts = { 'objectMode': true, 'iter': 10, 'siter': 4 }; s = randomStream( 2.0, 5.0, opts ); s.on( 'state', onState ); s.on( 'end', onEnd1 ); opts = { 'objectMode': true }; iStream = inspectStream( opts, inspect1 ); count = 0; arr = []; // Move to a future state... s.pipe( iStream ); function onState( s ) { // Only capture the first emitted state... if ( !state ) { state = s; // Create a copy of the state (to prevent mutation) which will be shared by more than one PRNG: shared = new Uint32Array( state ); } } function inspect1( v ) { count += 1; if ( count > 4 ) { arr.push( v ); } } function onEnd1() { var iStream; var opts; var s; t.pass( 'first stream ended' ); // Create another stream using the captured state: opts = { 'objectMode': true, 'iter': 3, 'state': shared, 'copy': false }; s = randomStream( 2.0, 5.0, opts ); s.on( 'end', onEnd2 ); t.deepEqual( state, s.state, 'same state' ); // Create a new inspect stream: opts = { 'objectMode': true }; iStream = inspectStream( opts, inspect2 ); // Replay previously generated values... count = 0; s.pipe( iStream ); } function inspect2( v ) { count += 1; t.equal( v, arr[ count-1 ], 'returns expected value. i: '+(count-1)+'.' ); } function onEnd2() { var iStream; var opts; var s; t.pass( 'second stream ended' ); // Create another stream using the captured state: opts = { 'objectMode': true, 'iter': 3, 'state': shared, 'copy': false }; s = randomStream( 2.0, 5.0, opts ); s.on( 'end', onEnd3 ); t.notDeepEqual( state, s.state, 'different state' ); // Create a new inspect stream: opts = { 'objectMode': true }; iStream = inspectStream( opts, inspect3 ); // Continue replaying previously generated values... s.pipe( iStream ); } function inspect3( v ) { count += 1; t.equal( v, arr[ count-1 ], 'returns expected value. i: '+(count-1)+'.' ); } function onEnd3() { t.pass( 'third stream ended' ); t.end(); } }); tape( 'the returned stream supports setting the underlying generator state', function test( t ) { var iStream; var state; var rand; var opts; var arr; var s; var i; rand = arcsine( 2.0, 5.0 ); // Move to a future state... for ( i = 0; i < 5; i++ ) { rand(); } // Capture the current state: state = rand.state; // Move to a future state... arr = []; for ( i = 0; i < 5; i++ ) { arr.push( rand() ); } // Create a random stream: opts = { 'objectMode': true, 'iter': 5 }; s = randomStream( 2.0, 5.0, opts ); s.on( 'end', onEnd ); // Set the PRNG state: s.state = state; // Create a new inspect stream: opts = { 'objectMode': true }; iStream = inspectStream( opts, inspect ); // Replay previously generated values: i = 0; s.pipe( iStream ); function inspect( v ) { t.equal( v, arr[ i ], 'returns expected value. i: ' + i + '.' ); i += 1; } function onEnd() { t.end(); } });<|fim▁end|>
<|file_name|>peoplegui--frame.py<|end_file_name|><|fim▁begin|>""" See peoplegui--old.py: the alternative here uses nedted row frames with fixed widdth labels with pack() to acheive the same aligned layout as grid(), but it takes two extra lines of code as is (though adding window resize support makes the two techniques roughly the same--see later in the book). """ from tkinter import * from tkinter.messagebox import showerror import shelve shelvename = 'class-shelve' fieldnames = ('name', 'age', 'job', 'pay') def makeWidgets(): global entries window = Tk() window.title('People Shelve') form = Frame(window) form.pack() entries = {} for label in ('key',) + fieldnames: row = Frame(form) <|fim▁hole|> ent.pack(side=RIGHT) entries[label] = ent Button(window, text="Fetch", command=fetchRecord).pack(side=LEFT) Button(window, text="Update", command=updateRecord).pack(side=LEFT) Button(window, text="Quit", command=window.quit).pack(side=RIGHT) return window def fetchRecord(): key = entries['key'].get() try: record = db[key] # fetch by key, show in GUI except: showerror(title='Error', message='No such key!') else: for field in fieldnames: entries[field].delete(0, END) entries[field].insert(0, repr(getattr(record, field))) def updateRecord(): key = entries['key'].get() if key in db: record = db[key] # update existing record else: from person import Person # make/store new one for key record = Person(name='?', age='?') # eval: strings must be quoted for field in fieldnames: setattr(record, field, eval(entries[field].get())) db[key] = record db = shelve.open(shelvename) window = makeWidgets() window.mainloop() db.close() # back here after quit or window close<|fim▁end|>
lab = Label(row, text=label, width=6) ent = Entry(row) row.pack(side=TOP) lab.pack(side=LEFT)
<|file_name|>Detay.java<|end_file_name|><|fim▁begin|>package org.ab.akademikbilisim; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; public class Detay extends ActionBarActivity { private Intent ben; private String yazi; private TextView girilenDeger; private Button btnKapat; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detay); ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); ben = getIntent(); yazi = ben.getStringExtra("gonderilen"); girilenDeger = (TextView) findViewById(R.id.girilen_deger); girilenDeger.setText(yazi); btnKapat = (Button) findViewById(R.id.btn_kapat); btnKapat.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_detay, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) {<|fim▁hole|> if(id == android.R.id.home){ // geri butonuna tıklandı finish(); } //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }<|fim▁end|>
// Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId();
<|file_name|>ConfigurationFactory.java<|end_file_name|><|fim▁begin|>// Copyright 2014 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.analysis.config; import com.google.common.cache.Cache; import com.google.common.collect.ImmutableList; import com.google.devtools.build.lib.analysis.BlazeDirectories; import com.google.devtools.build.lib.analysis.ConfigurationCollectionFactory; import com.google.devtools.build.lib.analysis.config.BuildConfiguration.Fragment; import com.google.devtools.build.lib.concurrent.ThreadSafety.ThreadCompatible; import com.google.devtools.build.lib.events.EventHandler; import com.google.devtools.build.lib.util.Preconditions; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Nullable; /** * A factory class for {@link BuildConfiguration} instances. This is unfortunately more complex, * and should be simplified in the future, if * possible. Right now, creating a {@link BuildConfiguration} instance involves * creating the instance itself and the related configurations; the main method * is {@link #createConfigurations}. * * <p>Avoid calling into this class, and instead use the skyframe infrastructure to obtain * configuration instances. * * <p>Blaze currently relies on the fact that all {@link BuildConfiguration} * instances used in a build can be constructed ahead of time by this class. */ @ThreadCompatible // safe as long as separate instances are used<|fim▁hole|> private final ConfigurationCollectionFactory configurationCollectionFactory; public ConfigurationFactory( ConfigurationCollectionFactory configurationCollectionFactory, ConfigurationFragmentFactory... fragmentFactories) { this(configurationCollectionFactory, ImmutableList.copyOf(fragmentFactories)); } public ConfigurationFactory( ConfigurationCollectionFactory configurationCollectionFactory, List<ConfigurationFragmentFactory> fragmentFactories) { this.configurationCollectionFactory = Preconditions.checkNotNull(configurationCollectionFactory); this.configurationFragmentFactories = ImmutableList.copyOf(fragmentFactories); } /** * Creates a set of build configurations with top-level configuration having the given options. * * <p>The rest of the configurations are created based on the set of transitions available. */ @Nullable public BuildConfiguration createConfigurations( Cache<String, BuildConfiguration> cache, PackageProviderForConfigurations loadedPackageProvider, BuildOptions buildOptions, EventHandler errorEventListener) throws InvalidConfigurationException, InterruptedException { return configurationCollectionFactory.createConfigurations(this, cache, loadedPackageProvider, buildOptions, errorEventListener); } /** * Returns a {@link com.google.devtools.build.lib.analysis.config.BuildConfiguration} based on the * given set of build options. * * <p>If the configuration has already been created, re-uses it, otherwise, creates a new one. */ @Nullable public BuildConfiguration getConfiguration( PackageProviderForConfigurations loadedPackageProvider, BuildOptions buildOptions, boolean actionsDisabled, Cache<String, BuildConfiguration> cache) throws InvalidConfigurationException, InterruptedException { String cacheKey = buildOptions.computeCacheKey(); BuildConfiguration result = cache.getIfPresent(cacheKey); if (result != null) { return result; } Map<Class<? extends Fragment>, Fragment> fragments = new HashMap<>(); // Create configuration fragments for (ConfigurationFragmentFactory factory : configurationFragmentFactories) { Class<? extends Fragment> fragmentType = factory.creates(); Fragment fragment = loadedPackageProvider.getFragment(buildOptions, fragmentType); if (fragment != null && fragments.get(fragment.getClass()) == null) { fragments.put(fragment.getClass(), fragment); } } BlazeDirectories directories = loadedPackageProvider.getDirectories(); if (loadedPackageProvider.valuesMissing()) { return null; } result = new BuildConfiguration(directories, fragments, buildOptions, actionsDisabled); cache.put(cacheKey, result); return result; } public List<ConfigurationFragmentFactory> getFactories() { return configurationFragmentFactories; } }<|fim▁end|>
public final class ConfigurationFactory { private final List<ConfigurationFragmentFactory> configurationFragmentFactories;