file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
cachestatus.js | /* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Cache Status.
*
* The Initial Developer of the Original Code is
* Jason Purdy.
* Portions created by the Initial Developer are Copyright (C) 2005
* the Initial Developer. All Rights Reserved.
*
* Thanks to the Fasterfox Extension for some pointers
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
function cs_updated_stat( type, aDeviceInfo, prefs ) {
var current = round_memory_usage( aDeviceInfo.totalSize/1024/1024 );
var max = round_memory_usage( aDeviceInfo.maximumSize/1024/1024 );
var cs_id = 'cachestatus';
var bool_pref_key = 'auto_clear';
var int_pref_key = 'ac';
var clear_directive;
if ( type == 'memory' ) {
cs_id += '-ram-label';
bool_pref_key += '_ram';
int_pref_key += 'r_percent';
clear_directive = 'ram';
// this is some sort of random bug workaround
if ( current > max && current == 4096 ) {
current = 0;
}
} else if ( type == 'disk' ) {
cs_id += '-hd-label';
bool_pref_key += '_disk';
int_pref_key += 'd_percent';
clear_directive = 'disk';
} else {
// offline ... or something else we don't manage
return;
}
/*
dump( 'type: ' + type + ' - aDeviceInfo' + aDeviceInfo );
// do we need to auto-clear?
dump( "evaling if we need to auto_clear...\n" );
dump( bool_pref_key + ": " + prefs.getBoolPref( bool_pref_key ) + " and " +
(( current/max )*100) + " > " +
prefs.getIntPref( int_pref_key ) + "\n" );
dump( "new min level: " + prefs.getIntPref( int_pref_key )*.01*max + " > 10\n" );
*/
/*
This is being disabled for now:
http://code.google.com/p/cachestatus/issues/detail?id=10
*/
/*
if (
prefs.getBoolPref( bool_pref_key ) &&
prefs.getIntPref( int_pref_key )*.01*max > 10 &&
(( current/max )*100) > prefs.getIntPref( int_pref_key )
) {
//dump( "clearing!\n" );
cs_clear_cache( clear_directive, 1 );
current = 0;
}
*/
// Now, update the status bar label...
var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
.getService(Components.interfaces.nsIWindowMediator);
var win = wm.getMostRecentWindow("navigator:browser");
if (win) {
win.document.getElementById(cs_id).setAttribute(
'value', current + " MB / " + max + " MB " );
}
}
function update_cache_status() {
var cache_service = Components.classes["@mozilla.org/network/cache-service;1"]
.getService(Components.interfaces.nsICacheService);
var prefService = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService);
| cs_updated_stat( device, aDeviceInfo, prefs );
}
}
cache_service.visitEntries( cache_visitor );
}
/*
* This function takes what could be 15.8912576891 and drops it to just
* one decimal place. In a future version, I could have the user say
* how many decimal places...
*/
function round_memory_usage( memory ) {
memory = parseFloat( memory );
memory *= 10;
memory = Math.round(memory)/10;
return memory;
}
// I got the cacheService code from the fasterfox extension
// http://www.xulplanet.com/references/xpcomref/ifaces/nsICacheService.html
function cs_clear_cache( param, noupdate ) {
var cacheService = Components.classes["@mozilla.org/network/cache-service;1"]
.getService(Components.interfaces.nsICacheService);
if ( param && param == 'ram' ) {
cacheService.evictEntries(Components.interfaces.nsICache.STORE_IN_MEMORY);
} else if ( param && param == 'disk' ) {
cacheService.evictEntries(Components.interfaces.nsICache.STORE_ON_DISK);
} else {
cacheService.evictEntries(Components.interfaces.nsICache.STORE_ON_DISK);
cacheService.evictEntries(Components.interfaces.nsICache.STORE_IN_MEMORY);
}
if ( ! noupdate ) {
update_cache_status();
}
}
/*
* Grabbed this helpful bit from:
* http://kb.mozillazine.org/On_Page_Load
* http://developer.mozilla.org/en/docs/Code_snippets:On_page_load
*/
var csExtension = {
onPageLoad: function(aEvent) {
update_cache_status();
},
QueryInterface : function (aIID) {
if (aIID.equals(Components.interfaces.nsIObserver) ||
aIID.equals(Components.interfaces.nsISupports) ||
aIID.equals(Components.interfaces.nsISupportsWeakReference))
return this;
throw Components.results.NS_NOINTERFACE;
},
register: function()
{
var prefService = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService);
this._prefs = prefService.getBranch("extensions.cachestatus.");
if ( this._prefs.getBoolPref( 'auto_update' ) ) {
var appcontent = document.getElementById( 'appcontent' );
if ( appcontent )
appcontent.addEventListener( "DOMContentLoaded", this.onPageLoad, true );
}
this._branch = this._prefs;
this._branch.QueryInterface(Components.interfaces.nsIPrefBranch2);
this._branch.addObserver("", this, true);
this._hbox = this.grabHBox();
this.rebuildPresence( this._prefs.getCharPref( 'presence' ) );
this.welcome();
},
welcome: function ()
{
//Do not show welcome page if user has turned it off from Settings.
if (!csExtension._prefs.getBoolPref( 'welcome' )) {
return
}
//Detect Firefox version
var version = "";
try {
version = (navigator.userAgent.match(/Firefox\/([\d\.]*)/) || navigator.userAgent.match(/Thunderbird\/([\d\.]*)/))[1];
} catch (e) {}
function welcome(version) {
if (csExtension._prefs.getCharPref( 'version' ) == version) {
return;
}
//Showing welcome screen
setTimeout(function () {
var newTab = getBrowser().addTab("http://add0n.com/cache-status.html?version=" + version);
getBrowser().selectedTab = newTab;
}, 5000);
csExtension._prefs.setCharPref( 'version', version );
}
//FF < 4.*
var versionComparator = Components.classes["@mozilla.org/xpcom/version-comparator;1"]
.getService(Components.interfaces.nsIVersionComparator)
.compare(version, "4.0");
if (versionComparator < 0) {
var extMan = Components.classes["@mozilla.org/extensions/manager;1"].getService(Components.interfaces.nsIExtensionManager);
var addon = extMan.getItemForID("cache@status.org");
welcome(addon.version);
}
//FF > 4.*
else {
Components.utils.import("resource://gre/modules/AddonManager.jsm");
AddonManager.getAddonByID("cache@status.org", function (addon) {
welcome(addon.version);
});
}
},
grabHBox: function()
{
var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
.getService(Components.interfaces.nsIWindowMediator);
var win = wm.getMostRecentWindow("navigator:browser");
var found_hbox;
if (win) {
this._doc = win.document;
found_hbox = win.document.getElementById("cs_presence");
}
//dump( "In grabHBox(): WIN: " + win + " HB: " + found_hbox + "\n" );
return found_hbox;
},
observe: function(aSubject, aTopic, aData)
{
if ( aTopic != 'nsPref:changed' ) return;
// aSubject is the nsIPrefBranch we're observing (after appropriate QI)
// aData is the name of the pref that's been changed (relative to aSubject)
//dump( "pref changed: S: " + aSubject + " T: " + aTopic + " D: " + aData + "\n" );
if ( aData == 'auto_update' ) {
var add_event_handler = this._prefs.getBoolPref( 'auto_update' );
if ( add_event_handler ) {
window.addEventListener( 'load', this.onPageLoad, true );
} else {
window.removeEventListener( 'load', this.onPageLoad, true );
}
} else if ( aData == 'presence' ) {
var presence = this._prefs.getCharPref( 'presence' );
if ( presence == 'original' || presence == 'icons' ) {
this.rebuildPresence( presence );
} else {
dump( "Unknown presence value: " + presence + "\n" );
}
}
},
rebuildPresence: function(presence)
{
// Take the hbox 'cs_presence' and replace it
if ( this._hbox == null ) {
this._hbox = this.grabHBox();
}
var hbox = this._hbox;
var child_node = hbox.firstChild;
while( child_node != null ) {
hbox.removeChild( child_node );
child_node = hbox.firstChild;
}
var popupset = this._doc.getElementById( 'cs_popupset' );
var child_node = popupset.firstChild;
while( child_node != null ) {
popupset.removeChild( child_node );
child_node = popupset.firstChild;
}
var string_bundle = this._doc.getElementById( 'cache-status-strings' );
if ( presence == 'original' ) {
var ram_image = this._doc.createElement( 'image' );
ram_image.setAttribute(
'tooltiptext', string_bundle.getString( 'ramcache' ) );
ram_image.setAttribute( 'src', 'chrome://cachestatus/skin/ram.png' );
var ram_label = this._doc.createElement( 'label' );
ram_label.setAttribute( 'id', 'cachestatus-ram-label' );
ram_label.setAttribute(
'value', ': ' + string_bundle.getString( 'nly' ) );
ram_label.setAttribute(
'tooltiptext', string_bundle.getString( 'ramcache' ) );
var disk_image = this._doc.createElement( 'image' );
disk_image.setAttribute(
'tooltiptext', string_bundle.getString( 'diskcache' ) );
disk_image.setAttribute( 'src', 'chrome://cachestatus/skin/hd.png' );
var disk_label = this._doc.createElement( 'label' );
disk_label.setAttribute(
'tooltiptext', string_bundle.getString( 'diskcache' ) );
disk_label.setAttribute( 'id', 'cachestatus-hd-label' );
disk_label.setAttribute(
'value', ': ' + string_bundle.getString( 'nly' ) );
hbox.appendChild( ram_image );
hbox.appendChild( ram_label );
hbox.appendChild( disk_image );
hbox.appendChild( disk_label );
} else if ( presence == 'icons' ) {
var ram_tooltip = this._doc.createElement( 'tooltip' );
ram_tooltip.setAttribute( 'id', 'ram_tooltip' );
ram_tooltip.setAttribute( 'orient', 'horizontal' );
var ram_desc_prefix = this._doc.createElement( 'description' );
ram_desc_prefix.setAttribute( 'id', 'cachestatus-ram-prefix' );
ram_desc_prefix.setAttribute(
'value', string_bundle.getString( 'ramcache' ) + ':' );
ram_desc_prefix.setAttribute( 'style', 'font-weight: bold;' );
var ram_desc = this._doc.createElement( 'description' );
ram_desc.setAttribute( 'id', 'cachestatus-ram-label' );
ram_desc.setAttribute(
'value', string_bundle.getString( 'nly' ) );
ram_tooltip.appendChild( ram_desc_prefix );
ram_tooltip.appendChild( ram_desc );
var hd_tooltip = this._doc.createElement( 'tooltip' );
hd_tooltip.setAttribute( 'id', 'hd_tooltip' );
hd_tooltip.setAttribute( 'orient', 'horizontal' );
var hd_desc_prefix = this._doc.createElement( 'description' );
hd_desc_prefix.setAttribute( 'id', 'cachestatus-hd-prefix' );
hd_desc_prefix.setAttribute(
'value', string_bundle.getString( 'diskcache' ) + ':' );
hd_desc_prefix.setAttribute( 'style', 'font-weight: bold;' );
var hd_desc = this._doc.createElement( 'description' );
hd_desc.setAttribute( 'id', 'cachestatus-hd-label' );
hd_desc.setAttribute(
'value', string_bundle.getString( 'nly' ) );
hd_tooltip.appendChild( hd_desc_prefix );
hd_tooltip.appendChild( hd_desc );
popupset.appendChild( ram_tooltip );
popupset.appendChild( hd_tooltip );
hbox.parentNode.insertBefore( popupset, hbox );
var ram_image = this._doc.createElement( 'image' );
ram_image.setAttribute( 'src', 'chrome://cachestatus/skin/ram.png' );
ram_image.setAttribute( 'tooltip', 'ram_tooltip' );
var disk_image = this._doc.createElement( 'image' );
disk_image.setAttribute( 'src', 'chrome://cachestatus/skin/hd.png' );
disk_image.setAttribute( 'tooltip', 'hd_tooltip' );
hbox.appendChild( ram_image );
hbox.appendChild( disk_image );
}
}
}
// I can't just call csExtension.register directly b/c the XUL
// might not be loaded yet.
window.addEventListener( 'load', function() { csExtension.register(); }, false ); | var prefs = prefService.getBranch("extensions.cachestatus.");
var cache_visitor = {
visitEntry: function(a,b) {},
visitDevice: function( device, aDeviceInfo ) {
| random_line_split |
cachestatus.js | /* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Cache Status.
*
* The Initial Developer of the Original Code is
* Jason Purdy.
* Portions created by the Initial Developer are Copyright (C) 2005
* the Initial Developer. All Rights Reserved.
*
* Thanks to the Fasterfox Extension for some pointers
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
function cs_updated_stat( type, aDeviceInfo, prefs ) {
var current = round_memory_usage( aDeviceInfo.totalSize/1024/1024 );
var max = round_memory_usage( aDeviceInfo.maximumSize/1024/1024 );
var cs_id = 'cachestatus';
var bool_pref_key = 'auto_clear';
var int_pref_key = 'ac';
var clear_directive;
if ( type == 'memory' ) {
cs_id += '-ram-label';
bool_pref_key += '_ram';
int_pref_key += 'r_percent';
clear_directive = 'ram';
// this is some sort of random bug workaround
if ( current > max && current == 4096 ) {
current = 0;
}
} else if ( type == 'disk' ) {
cs_id += '-hd-label';
bool_pref_key += '_disk';
int_pref_key += 'd_percent';
clear_directive = 'disk';
} else {
// offline ... or something else we don't manage
return;
}
/*
dump( 'type: ' + type + ' - aDeviceInfo' + aDeviceInfo );
// do we need to auto-clear?
dump( "evaling if we need to auto_clear...\n" );
dump( bool_pref_key + ": " + prefs.getBoolPref( bool_pref_key ) + " and " +
(( current/max )*100) + " > " +
prefs.getIntPref( int_pref_key ) + "\n" );
dump( "new min level: " + prefs.getIntPref( int_pref_key )*.01*max + " > 10\n" );
*/
/*
This is being disabled for now:
http://code.google.com/p/cachestatus/issues/detail?id=10
*/
/*
if (
prefs.getBoolPref( bool_pref_key ) &&
prefs.getIntPref( int_pref_key )*.01*max > 10 &&
(( current/max )*100) > prefs.getIntPref( int_pref_key )
) {
//dump( "clearing!\n" );
cs_clear_cache( clear_directive, 1 );
current = 0;
}
*/
// Now, update the status bar label...
var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
.getService(Components.interfaces.nsIWindowMediator);
var win = wm.getMostRecentWindow("navigator:browser");
if (win) {
win.document.getElementById(cs_id).setAttribute(
'value', current + " MB / " + max + " MB " );
}
}
function update_cache_status() {
var cache_service = Components.classes["@mozilla.org/network/cache-service;1"]
.getService(Components.interfaces.nsICacheService);
var prefService = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService);
var prefs = prefService.getBranch("extensions.cachestatus.");
var cache_visitor = {
visitEntry: function(a,b) {},
visitDevice: function( device, aDeviceInfo ) {
cs_updated_stat( device, aDeviceInfo, prefs );
}
}
cache_service.visitEntries( cache_visitor );
}
/*
* This function takes what could be 15.8912576891 and drops it to just
* one decimal place. In a future version, I could have the user say
* how many decimal places...
*/
function round_memory_usage( memory ) {
memory = parseFloat( memory );
memory *= 10;
memory = Math.round(memory)/10;
return memory;
}
// I got the cacheService code from the fasterfox extension
// http://www.xulplanet.com/references/xpcomref/ifaces/nsICacheService.html
function cs_clear_cache( param, noupdate ) {
var cacheService = Components.classes["@mozilla.org/network/cache-service;1"]
.getService(Components.interfaces.nsICacheService);
if ( param && param == 'ram' ) {
cacheService.evictEntries(Components.interfaces.nsICache.STORE_IN_MEMORY);
} else if ( param && param == 'disk' ) {
cacheService.evictEntries(Components.interfaces.nsICache.STORE_ON_DISK);
} else {
cacheService.evictEntries(Components.interfaces.nsICache.STORE_ON_DISK);
cacheService.evictEntries(Components.interfaces.nsICache.STORE_IN_MEMORY);
}
if ( ! noupdate ) {
update_cache_status();
}
}
/*
* Grabbed this helpful bit from:
* http://kb.mozillazine.org/On_Page_Load
* http://developer.mozilla.org/en/docs/Code_snippets:On_page_load
*/
var csExtension = {
onPageLoad: function(aEvent) {
update_cache_status();
},
QueryInterface : function (aIID) {
if (aIID.equals(Components.interfaces.nsIObserver) ||
aIID.equals(Components.interfaces.nsISupports) ||
aIID.equals(Components.interfaces.nsISupportsWeakReference))
return this;
throw Components.results.NS_NOINTERFACE;
},
register: function()
{
var prefService = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService);
this._prefs = prefService.getBranch("extensions.cachestatus.");
if ( this._prefs.getBoolPref( 'auto_update' ) ) {
var appcontent = document.getElementById( 'appcontent' );
if ( appcontent )
appcontent.addEventListener( "DOMContentLoaded", this.onPageLoad, true );
}
this._branch = this._prefs;
this._branch.QueryInterface(Components.interfaces.nsIPrefBranch2);
this._branch.addObserver("", this, true);
this._hbox = this.grabHBox();
this.rebuildPresence( this._prefs.getCharPref( 'presence' ) );
this.welcome();
},
welcome: function ()
{
//Do not show welcome page if user has turned it off from Settings.
if (!csExtension._prefs.getBoolPref( 'welcome' )) {
return
}
//Detect Firefox version
var version = "";
try {
version = (navigator.userAgent.match(/Firefox\/([\d\.]*)/) || navigator.userAgent.match(/Thunderbird\/([\d\.]*)/))[1];
} catch (e) {}
function welcome(version) {
if (csExtension._prefs.getCharPref( 'version' ) == version) {
return;
}
//Showing welcome screen
setTimeout(function () {
var newTab = getBrowser().addTab("http://add0n.com/cache-status.html?version=" + version);
getBrowser().selectedTab = newTab;
}, 5000);
csExtension._prefs.setCharPref( 'version', version );
}
//FF < 4.*
var versionComparator = Components.classes["@mozilla.org/xpcom/version-comparator;1"]
.getService(Components.interfaces.nsIVersionComparator)
.compare(version, "4.0");
if (versionComparator < 0) {
var extMan = Components.classes["@mozilla.org/extensions/manager;1"].getService(Components.interfaces.nsIExtensionManager);
var addon = extMan.getItemForID("cache@status.org");
welcome(addon.version);
}
//FF > 4.*
else {
Components.utils.import("resource://gre/modules/AddonManager.jsm");
AddonManager.getAddonByID("cache@status.org", function (addon) {
welcome(addon.version);
});
}
},
grabHBox: function()
{
var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
.getService(Components.interfaces.nsIWindowMediator);
var win = wm.getMostRecentWindow("navigator:browser");
var found_hbox;
if (win) {
this._doc = win.document;
found_hbox = win.document.getElementById("cs_presence");
}
//dump( "In grabHBox(): WIN: " + win + " HB: " + found_hbox + "\n" );
return found_hbox;
},
observe: function(aSubject, aTopic, aData)
{
if ( aTopic != 'nsPref:changed' ) return;
// aSubject is the nsIPrefBranch we're observing (after appropriate QI)
// aData is the name of the pref that's been changed (relative to aSubject)
//dump( "pref changed: S: " + aSubject + " T: " + aTopic + " D: " + aData + "\n" );
if ( aData == 'auto_update' ) {
var add_event_handler = this._prefs.getBoolPref( 'auto_update' );
if ( add_event_handler ) {
window.addEventListener( 'load', this.onPageLoad, true );
} else {
window.removeEventListener( 'load', this.onPageLoad, true );
}
} else if ( aData == 'presence' ) {
var presence = this._prefs.getCharPref( 'presence' );
if ( presence == 'original' || presence == 'icons' ) {
this.rebuildPresence( presence );
} else {
dump( "Unknown presence value: " + presence + "\n" );
}
}
},
rebuildPresence: function(presence)
{
// Take the hbox 'cs_presence' and replace it
if ( this._hbox == null ) {
this._hbox = this.grabHBox();
}
var hbox = this._hbox;
var child_node = hbox.firstChild;
while( child_node != null ) {
hbox.removeChild( child_node );
child_node = hbox.firstChild;
}
var popupset = this._doc.getElementById( 'cs_popupset' );
var child_node = popupset.firstChild;
while( child_node != null ) {
popupset.removeChild( child_node );
child_node = popupset.firstChild;
}
var string_bundle = this._doc.getElementById( 'cache-status-strings' );
if ( presence == 'original' ) {
var ram_image = this._doc.createElement( 'image' );
ram_image.setAttribute(
'tooltiptext', string_bundle.getString( 'ramcache' ) );
ram_image.setAttribute( 'src', 'chrome://cachestatus/skin/ram.png' );
var ram_label = this._doc.createElement( 'label' );
ram_label.setAttribute( 'id', 'cachestatus-ram-label' );
ram_label.setAttribute(
'value', ': ' + string_bundle.getString( 'nly' ) );
ram_label.setAttribute(
'tooltiptext', string_bundle.getString( 'ramcache' ) );
var disk_image = this._doc.createElement( 'image' );
disk_image.setAttribute(
'tooltiptext', string_bundle.getString( 'diskcache' ) );
disk_image.setAttribute( 'src', 'chrome://cachestatus/skin/hd.png' );
var disk_label = this._doc.createElement( 'label' );
disk_label.setAttribute(
'tooltiptext', string_bundle.getString( 'diskcache' ) );
disk_label.setAttribute( 'id', 'cachestatus-hd-label' );
disk_label.setAttribute(
'value', ': ' + string_bundle.getString( 'nly' ) );
hbox.appendChild( ram_image );
hbox.appendChild( ram_label );
hbox.appendChild( disk_image );
hbox.appendChild( disk_label );
} else if ( presence == 'icons' ) |
}
}
// I can't just call csExtension.register directly b/c the XUL
// might not be loaded yet.
window.addEventListener( 'load', function() { csExtension.register(); }, false );
| {
var ram_tooltip = this._doc.createElement( 'tooltip' );
ram_tooltip.setAttribute( 'id', 'ram_tooltip' );
ram_tooltip.setAttribute( 'orient', 'horizontal' );
var ram_desc_prefix = this._doc.createElement( 'description' );
ram_desc_prefix.setAttribute( 'id', 'cachestatus-ram-prefix' );
ram_desc_prefix.setAttribute(
'value', string_bundle.getString( 'ramcache' ) + ':' );
ram_desc_prefix.setAttribute( 'style', 'font-weight: bold;' );
var ram_desc = this._doc.createElement( 'description' );
ram_desc.setAttribute( 'id', 'cachestatus-ram-label' );
ram_desc.setAttribute(
'value', string_bundle.getString( 'nly' ) );
ram_tooltip.appendChild( ram_desc_prefix );
ram_tooltip.appendChild( ram_desc );
var hd_tooltip = this._doc.createElement( 'tooltip' );
hd_tooltip.setAttribute( 'id', 'hd_tooltip' );
hd_tooltip.setAttribute( 'orient', 'horizontal' );
var hd_desc_prefix = this._doc.createElement( 'description' );
hd_desc_prefix.setAttribute( 'id', 'cachestatus-hd-prefix' );
hd_desc_prefix.setAttribute(
'value', string_bundle.getString( 'diskcache' ) + ':' );
hd_desc_prefix.setAttribute( 'style', 'font-weight: bold;' );
var hd_desc = this._doc.createElement( 'description' );
hd_desc.setAttribute( 'id', 'cachestatus-hd-label' );
hd_desc.setAttribute(
'value', string_bundle.getString( 'nly' ) );
hd_tooltip.appendChild( hd_desc_prefix );
hd_tooltip.appendChild( hd_desc );
popupset.appendChild( ram_tooltip );
popupset.appendChild( hd_tooltip );
hbox.parentNode.insertBefore( popupset, hbox );
var ram_image = this._doc.createElement( 'image' );
ram_image.setAttribute( 'src', 'chrome://cachestatus/skin/ram.png' );
ram_image.setAttribute( 'tooltip', 'ram_tooltip' );
var disk_image = this._doc.createElement( 'image' );
disk_image.setAttribute( 'src', 'chrome://cachestatus/skin/hd.png' );
disk_image.setAttribute( 'tooltip', 'hd_tooltip' );
hbox.appendChild( ram_image );
hbox.appendChild( disk_image );
} | conditional_block |
cachestatus.js | /* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Cache Status.
*
* The Initial Developer of the Original Code is
* Jason Purdy.
* Portions created by the Initial Developer are Copyright (C) 2005
* the Initial Developer. All Rights Reserved.
*
* Thanks to the Fasterfox Extension for some pointers
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
function | ( type, aDeviceInfo, prefs ) {
var current = round_memory_usage( aDeviceInfo.totalSize/1024/1024 );
var max = round_memory_usage( aDeviceInfo.maximumSize/1024/1024 );
var cs_id = 'cachestatus';
var bool_pref_key = 'auto_clear';
var int_pref_key = 'ac';
var clear_directive;
if ( type == 'memory' ) {
cs_id += '-ram-label';
bool_pref_key += '_ram';
int_pref_key += 'r_percent';
clear_directive = 'ram';
// this is some sort of random bug workaround
if ( current > max && current == 4096 ) {
current = 0;
}
} else if ( type == 'disk' ) {
cs_id += '-hd-label';
bool_pref_key += '_disk';
int_pref_key += 'd_percent';
clear_directive = 'disk';
} else {
// offline ... or something else we don't manage
return;
}
/*
dump( 'type: ' + type + ' - aDeviceInfo' + aDeviceInfo );
// do we need to auto-clear?
dump( "evaling if we need to auto_clear...\n" );
dump( bool_pref_key + ": " + prefs.getBoolPref( bool_pref_key ) + " and " +
(( current/max )*100) + " > " +
prefs.getIntPref( int_pref_key ) + "\n" );
dump( "new min level: " + prefs.getIntPref( int_pref_key )*.01*max + " > 10\n" );
*/
/*
This is being disabled for now:
http://code.google.com/p/cachestatus/issues/detail?id=10
*/
/*
if (
prefs.getBoolPref( bool_pref_key ) &&
prefs.getIntPref( int_pref_key )*.01*max > 10 &&
(( current/max )*100) > prefs.getIntPref( int_pref_key )
) {
//dump( "clearing!\n" );
cs_clear_cache( clear_directive, 1 );
current = 0;
}
*/
// Now, update the status bar label...
var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
.getService(Components.interfaces.nsIWindowMediator);
var win = wm.getMostRecentWindow("navigator:browser");
if (win) {
win.document.getElementById(cs_id).setAttribute(
'value', current + " MB / " + max + " MB " );
}
}
function update_cache_status() {
var cache_service = Components.classes["@mozilla.org/network/cache-service;1"]
.getService(Components.interfaces.nsICacheService);
var prefService = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService);
var prefs = prefService.getBranch("extensions.cachestatus.");
var cache_visitor = {
visitEntry: function(a,b) {},
visitDevice: function( device, aDeviceInfo ) {
cs_updated_stat( device, aDeviceInfo, prefs );
}
}
cache_service.visitEntries( cache_visitor );
}
/*
* This function takes what could be 15.8912576891 and drops it to just
* one decimal place. In a future version, I could have the user say
* how many decimal places...
*/
function round_memory_usage( memory ) {
memory = parseFloat( memory );
memory *= 10;
memory = Math.round(memory)/10;
return memory;
}
// I got the cacheService code from the fasterfox extension
// http://www.xulplanet.com/references/xpcomref/ifaces/nsICacheService.html
function cs_clear_cache( param, noupdate ) {
var cacheService = Components.classes["@mozilla.org/network/cache-service;1"]
.getService(Components.interfaces.nsICacheService);
if ( param && param == 'ram' ) {
cacheService.evictEntries(Components.interfaces.nsICache.STORE_IN_MEMORY);
} else if ( param && param == 'disk' ) {
cacheService.evictEntries(Components.interfaces.nsICache.STORE_ON_DISK);
} else {
cacheService.evictEntries(Components.interfaces.nsICache.STORE_ON_DISK);
cacheService.evictEntries(Components.interfaces.nsICache.STORE_IN_MEMORY);
}
if ( ! noupdate ) {
update_cache_status();
}
}
/*
* Grabbed this helpful bit from:
* http://kb.mozillazine.org/On_Page_Load
* http://developer.mozilla.org/en/docs/Code_snippets:On_page_load
*/
var csExtension = {
onPageLoad: function(aEvent) {
update_cache_status();
},
QueryInterface : function (aIID) {
if (aIID.equals(Components.interfaces.nsIObserver) ||
aIID.equals(Components.interfaces.nsISupports) ||
aIID.equals(Components.interfaces.nsISupportsWeakReference))
return this;
throw Components.results.NS_NOINTERFACE;
},
register: function()
{
var prefService = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService);
this._prefs = prefService.getBranch("extensions.cachestatus.");
if ( this._prefs.getBoolPref( 'auto_update' ) ) {
var appcontent = document.getElementById( 'appcontent' );
if ( appcontent )
appcontent.addEventListener( "DOMContentLoaded", this.onPageLoad, true );
}
this._branch = this._prefs;
this._branch.QueryInterface(Components.interfaces.nsIPrefBranch2);
this._branch.addObserver("", this, true);
this._hbox = this.grabHBox();
this.rebuildPresence( this._prefs.getCharPref( 'presence' ) );
this.welcome();
},
welcome: function ()
{
//Do not show welcome page if user has turned it off from Settings.
if (!csExtension._prefs.getBoolPref( 'welcome' )) {
return
}
//Detect Firefox version
var version = "";
try {
version = (navigator.userAgent.match(/Firefox\/([\d\.]*)/) || navigator.userAgent.match(/Thunderbird\/([\d\.]*)/))[1];
} catch (e) {}
function welcome(version) {
if (csExtension._prefs.getCharPref( 'version' ) == version) {
return;
}
//Showing welcome screen
setTimeout(function () {
var newTab = getBrowser().addTab("http://add0n.com/cache-status.html?version=" + version);
getBrowser().selectedTab = newTab;
}, 5000);
csExtension._prefs.setCharPref( 'version', version );
}
//FF < 4.*
var versionComparator = Components.classes["@mozilla.org/xpcom/version-comparator;1"]
.getService(Components.interfaces.nsIVersionComparator)
.compare(version, "4.0");
if (versionComparator < 0) {
var extMan = Components.classes["@mozilla.org/extensions/manager;1"].getService(Components.interfaces.nsIExtensionManager);
var addon = extMan.getItemForID("cache@status.org");
welcome(addon.version);
}
//FF > 4.*
else {
Components.utils.import("resource://gre/modules/AddonManager.jsm");
AddonManager.getAddonByID("cache@status.org", function (addon) {
welcome(addon.version);
});
}
},
grabHBox: function()
{
var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
.getService(Components.interfaces.nsIWindowMediator);
var win = wm.getMostRecentWindow("navigator:browser");
var found_hbox;
if (win) {
this._doc = win.document;
found_hbox = win.document.getElementById("cs_presence");
}
//dump( "In grabHBox(): WIN: " + win + " HB: " + found_hbox + "\n" );
return found_hbox;
},
observe: function(aSubject, aTopic, aData)
{
if ( aTopic != 'nsPref:changed' ) return;
// aSubject is the nsIPrefBranch we're observing (after appropriate QI)
// aData is the name of the pref that's been changed (relative to aSubject)
//dump( "pref changed: S: " + aSubject + " T: " + aTopic + " D: " + aData + "\n" );
if ( aData == 'auto_update' ) {
var add_event_handler = this._prefs.getBoolPref( 'auto_update' );
if ( add_event_handler ) {
window.addEventListener( 'load', this.onPageLoad, true );
} else {
window.removeEventListener( 'load', this.onPageLoad, true );
}
} else if ( aData == 'presence' ) {
var presence = this._prefs.getCharPref( 'presence' );
if ( presence == 'original' || presence == 'icons' ) {
this.rebuildPresence( presence );
} else {
dump( "Unknown presence value: " + presence + "\n" );
}
}
},
rebuildPresence: function(presence)
{
// Take the hbox 'cs_presence' and replace it
if ( this._hbox == null ) {
this._hbox = this.grabHBox();
}
var hbox = this._hbox;
var child_node = hbox.firstChild;
while( child_node != null ) {
hbox.removeChild( child_node );
child_node = hbox.firstChild;
}
var popupset = this._doc.getElementById( 'cs_popupset' );
var child_node = popupset.firstChild;
while( child_node != null ) {
popupset.removeChild( child_node );
child_node = popupset.firstChild;
}
var string_bundle = this._doc.getElementById( 'cache-status-strings' );
if ( presence == 'original' ) {
var ram_image = this._doc.createElement( 'image' );
ram_image.setAttribute(
'tooltiptext', string_bundle.getString( 'ramcache' ) );
ram_image.setAttribute( 'src', 'chrome://cachestatus/skin/ram.png' );
var ram_label = this._doc.createElement( 'label' );
ram_label.setAttribute( 'id', 'cachestatus-ram-label' );
ram_label.setAttribute(
'value', ': ' + string_bundle.getString( 'nly' ) );
ram_label.setAttribute(
'tooltiptext', string_bundle.getString( 'ramcache' ) );
var disk_image = this._doc.createElement( 'image' );
disk_image.setAttribute(
'tooltiptext', string_bundle.getString( 'diskcache' ) );
disk_image.setAttribute( 'src', 'chrome://cachestatus/skin/hd.png' );
var disk_label = this._doc.createElement( 'label' );
disk_label.setAttribute(
'tooltiptext', string_bundle.getString( 'diskcache' ) );
disk_label.setAttribute( 'id', 'cachestatus-hd-label' );
disk_label.setAttribute(
'value', ': ' + string_bundle.getString( 'nly' ) );
hbox.appendChild( ram_image );
hbox.appendChild( ram_label );
hbox.appendChild( disk_image );
hbox.appendChild( disk_label );
} else if ( presence == 'icons' ) {
var ram_tooltip = this._doc.createElement( 'tooltip' );
ram_tooltip.setAttribute( 'id', 'ram_tooltip' );
ram_tooltip.setAttribute( 'orient', 'horizontal' );
var ram_desc_prefix = this._doc.createElement( 'description' );
ram_desc_prefix.setAttribute( 'id', 'cachestatus-ram-prefix' );
ram_desc_prefix.setAttribute(
'value', string_bundle.getString( 'ramcache' ) + ':' );
ram_desc_prefix.setAttribute( 'style', 'font-weight: bold;' );
var ram_desc = this._doc.createElement( 'description' );
ram_desc.setAttribute( 'id', 'cachestatus-ram-label' );
ram_desc.setAttribute(
'value', string_bundle.getString( 'nly' ) );
ram_tooltip.appendChild( ram_desc_prefix );
ram_tooltip.appendChild( ram_desc );
var hd_tooltip = this._doc.createElement( 'tooltip' );
hd_tooltip.setAttribute( 'id', 'hd_tooltip' );
hd_tooltip.setAttribute( 'orient', 'horizontal' );
var hd_desc_prefix = this._doc.createElement( 'description' );
hd_desc_prefix.setAttribute( 'id', 'cachestatus-hd-prefix' );
hd_desc_prefix.setAttribute(
'value', string_bundle.getString( 'diskcache' ) + ':' );
hd_desc_prefix.setAttribute( 'style', 'font-weight: bold;' );
var hd_desc = this._doc.createElement( 'description' );
hd_desc.setAttribute( 'id', 'cachestatus-hd-label' );
hd_desc.setAttribute(
'value', string_bundle.getString( 'nly' ) );
hd_tooltip.appendChild( hd_desc_prefix );
hd_tooltip.appendChild( hd_desc );
popupset.appendChild( ram_tooltip );
popupset.appendChild( hd_tooltip );
hbox.parentNode.insertBefore( popupset, hbox );
var ram_image = this._doc.createElement( 'image' );
ram_image.setAttribute( 'src', 'chrome://cachestatus/skin/ram.png' );
ram_image.setAttribute( 'tooltip', 'ram_tooltip' );
var disk_image = this._doc.createElement( 'image' );
disk_image.setAttribute( 'src', 'chrome://cachestatus/skin/hd.png' );
disk_image.setAttribute( 'tooltip', 'hd_tooltip' );
hbox.appendChild( ram_image );
hbox.appendChild( disk_image );
}
}
}
// I can't just call csExtension.register directly b/c the XUL
// might not be loaded yet.
window.addEventListener( 'load', function() { csExtension.register(); }, false );
| cs_updated_stat | identifier_name |
run_headless.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use compositing::*;
use geom::size::Size2D;
use std::unstable::intrinsics;
/// Starts the compositor, which listens for messages on the specified port.
///
/// This is the null compositor which doesn't draw anything to the screen. | Exit => break,
GetSize(chan) => {
chan.send(Size2D(500, 500));
}
GetGraphicsMetadata(chan) => {
unsafe {
chan.send(intrinsics::uninit());
}
}
SetIds(_, response_chan, _) => {
response_chan.send(());
}
// Explicitly list ignored messages so that when we add a new one,
// we'll notice and think about whether it needs a response, like
// SetIds.
NewLayer(*) | SetLayerPageSize(*) | SetLayerClipRect(*) | DeleteLayer(*) |
Paint(*) | InvalidateRect(*) | ChangeReadyState(*) | ChangeRenderState(*)
=> ()
}
}
compositor.shutdown_chan.send(())
} | /// It's intended for headless testing.
pub fn run_compositor(compositor: &CompositorTask) {
loop {
match compositor.port.recv() { | random_line_split |
run_headless.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use compositing::*;
use geom::size::Size2D;
use std::unstable::intrinsics;
/// Starts the compositor, which listens for messages on the specified port.
///
/// This is the null compositor which doesn't draw anything to the screen.
/// It's intended for headless testing.
pub fn | (compositor: &CompositorTask) {
loop {
match compositor.port.recv() {
Exit => break,
GetSize(chan) => {
chan.send(Size2D(500, 500));
}
GetGraphicsMetadata(chan) => {
unsafe {
chan.send(intrinsics::uninit());
}
}
SetIds(_, response_chan, _) => {
response_chan.send(());
}
// Explicitly list ignored messages so that when we add a new one,
// we'll notice and think about whether it needs a response, like
// SetIds.
NewLayer(*) | SetLayerPageSize(*) | SetLayerClipRect(*) | DeleteLayer(*) |
Paint(*) | InvalidateRect(*) | ChangeReadyState(*) | ChangeRenderState(*)
=> ()
}
}
compositor.shutdown_chan.send(())
}
| run_compositor | identifier_name |
run_headless.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use compositing::*;
use geom::size::Size2D;
use std::unstable::intrinsics;
/// Starts the compositor, which listens for messages on the specified port.
///
/// This is the null compositor which doesn't draw anything to the screen.
/// It's intended for headless testing.
pub fn run_compositor(compositor: &CompositorTask) | {
loop {
match compositor.port.recv() {
Exit => break,
GetSize(chan) => {
chan.send(Size2D(500, 500));
}
GetGraphicsMetadata(chan) => {
unsafe {
chan.send(intrinsics::uninit());
}
}
SetIds(_, response_chan, _) => {
response_chan.send(());
}
// Explicitly list ignored messages so that when we add a new one,
// we'll notice and think about whether it needs a response, like
// SetIds.
NewLayer(*) | SetLayerPageSize(*) | SetLayerClipRect(*) | DeleteLayer(*) |
Paint(*) | InvalidateRect(*) | ChangeReadyState(*) | ChangeRenderState(*)
=> ()
}
}
compositor.shutdown_chan.send(())
} | identifier_body | |
post.js | const mongoose = require('mongoose')
const TABLE_NAME = 'Post'
const Schema = mongoose.Schema
const ObjectId = Schema.Types.ObjectId
const escape = (require('../utils')).escape
const PostSchema = new Schema({
//类型
type: {
type: String,
default: 'post' // post | page
},
//标题
title: {
type: String,
trim: true,
set: escape
},
//别名
alias: {
type: String,
trim: true,
set: escape
},
//创建者
user: {
type: ObjectId,
ref: 'User'
},
//类别
category: {
type: ObjectId,
ref: 'Category'
},
//摘要
excerpt: {
type: String,
trim: true,
},
//内容
contents: {
type: String,
trim: true,
},
//markdown
markdown: {
type: String,
trim: true,
},
//标签
tags: Array,
//缩略图
thumbnail: {
type: String,
trim: true,
set: escape
},
//统计
count: {
//浏览次数
views: {
type: Number,
default: 1,
},
//评论数
comments: {
type: Number,
default: 0,
},
//点赞数
praises: {
type: Number,
default: 1
}
},
//状态
status: {
type: Number,
default: 1 // 1:发布, 0 :草稿, -1 :删除 | },
//置顶
top: Boolean,
//允许评论
allowComment: {
type: Boolean,
default: true
},
//允许打赏
allowReward: Boolean,
//著名版权
license: Boolean,
//使用密码
usePassword: Boolean,
//密码
password: {
type: String,
trim: true
},
order: {
type: Number,
default: 1
},
//创建时间
createTime: {
type: Date,
default: Date.now()
},
//修改时间
updateTime: {
type: Date,
default: Date.now()
}
}, {
connection: TABLE_NAME,
versionKey: false,
})
module.exports = mongoose.model(TABLE_NAME, PostSchema) | random_line_split | |
typeable.js | /*syn@0.1.4#typeable*/
var syn = require('./synthetic.js');
var typeables = [];
var __indexOf = [].indexOf || function (item) {
for (var i = 0, l = this.length; i < l; i++) {
if (i in this && this[i] === item) {
return i;
}
}
return -1;
};
syn.typeable = function (fn) {
if (__indexOf.call(typeables, fn) === -1) |
};
syn.typeable.test = function (el) {
for (var i = 0, len = typeables.length; i < len; i++) {
if (typeables[i](el)) {
return true;
}
}
return false;
};
var type = syn.typeable;
var typeableExp = /input|textarea/i;
type(function (el) {
return typeableExp.test(el.nodeName);
});
type(function (el) {
return __indexOf.call([
'',
'true'
], el.getAttribute('contenteditable')) !== -1;
}); | {
typeables.push(fn);
} | conditional_block |
typeable.js | /*syn@0.1.4#typeable*/
var syn = require('./synthetic.js');
var typeables = [];
var __indexOf = [].indexOf || function (item) {
for (var i = 0, l = this.length; i < l; i++) {
if (i in this && this[i] === item) {
return i;
}
}
return -1;
};
syn.typeable = function (fn) {
if (__indexOf.call(typeables, fn) === -1) { | syn.typeable.test = function (el) {
for (var i = 0, len = typeables.length; i < len; i++) {
if (typeables[i](el)) {
return true;
}
}
return false;
};
var type = syn.typeable;
var typeableExp = /input|textarea/i;
type(function (el) {
return typeableExp.test(el.nodeName);
});
type(function (el) {
return __indexOf.call([
'',
'true'
], el.getAttribute('contenteditable')) !== -1;
}); | typeables.push(fn);
}
}; | random_line_split |
en.js | /**
* @requires OpenLayers/Lang.js
*/
/**
* Namespace: OpenLayers.Lang["en"]
* Dictionary for English. Keys for entries are used in calls to
* <OpenLayers.Lang.translate>. Entry bodies are normal strings or
* strings formatted for use with <OpenLayers.String.format> calls.
*/
OpenLayers.Lang.en = {
'unhandledRequest': "Unhandled request return ${statusText}",
'Permalink': "Permalink",
'Overlays': "Overlays",
'Base Layer': "Base Layer",
'noFID': "Can't update a feature for which there is no FID.",
'browserNotSupported':
"Your browser does not support vector rendering. Currently supported renderers are:\n${renderers}",
// console message
'minZoomLevelError':
"The minZoomLevel property is only intended for use " +
"with the FixedZoomLevels-descendent layers. That this " +
"wfs layer checks for minZoomLevel is a relic of the" +
"past. We cannot, however, remove it without possibly " +
"breaking OL based applications that may depend on it." +
" Therefore we are deprecating it -- the minZoomLevel " +
"check below will be removed at 3.0. Please instead " +
"use min/max resolution setting as described here: " +
"http://trac.openlayers.org/wiki/SettingZoomLevels",
'commitSuccess': "WFS Transaction: SUCCESS ${response}",
'commitFailed': "WFS Transaction: FAILED ${response}",
'googleWarning':
"The Google Layer was unable to load correctly.<br><br>" +
"To get rid of this message, select a new BaseLayer " +
"in the layer switcher in the upper-right corner.<br><br>" +
"Most likely, this is because the Google Maps library " +
"script was either not included, or does not contain the " +
"correct API key for your site.<br><br>" +
"Developers: For help getting this working correctly, " +
"<a href='http://trac.openlayers.org/wiki/Google' " +
"target='_blank'>click here</a>",
'getLayerWarning':
"The ${layerType} Layer was unable to load correctly.<br><br>" +
"To get rid of this message, select a new BaseLayer " +
"in the layer switcher in the upper-right corner.<br><br>" +
"Most likely, this is because the ${layerLib} library " +
"script was not correctly included.<br><br>" +
"Developers: For help getting this working correctly, " +
"<a href='http://trac.openlayers.org/wiki/${layerLib}' " +
"target='_blank'>click here</a>",
'Scale = 1 : ${scaleDenom}': "Scale = 1 : ${scaleDenom}",
//labels for the graticule control
'W': 'W',
'E': 'E',
'N': 'N',
'S': 'S',
'Graticule': 'Graticule',
// console message
'reprojectDeprecated':
"You are using the 'reproject' option " +
"on the ${layerName} layer. This option is deprecated: " +
"its use was designed to support displaying data over commercial " +
"basemaps, but that functionality should now be achieved by using " +
"Spherical Mercator support. More information is available from " +
"http://trac.openlayers.org/wiki/SphericalMercator.",
// console message
'methodDeprecated':
"This method has been deprecated and will be removed in 3.0. " +
"Please use ${newMethod} instead.",
'proxyNeeded': "You probably need to set OpenLayers.ProxyHost to access ${url}."+
"See http://trac.osgeo.org/openlayers/wiki/FrequentlyAskedQuestions#ProxyHost",
|
}; |
// **** end ****
'end': ''
| random_line_split |
factory.py | from RPi import GPIO as gpio
from robotics.actors.redbot_motor_actor import RedbotMotorActor
from robotics.interfaces.spi.mcp3008_spi_interface import MCP3008SpiInterface
from robotics.robots.aizek_robot import AizekRobot
from robotics.sensors.redbot_wheel_encoder_sensor import RedbotWheelEncoderSensor
from robotics.sensors.sharp_ir_distance_sensor import SharpIrDistanceSensor
class RobotFactory(object):
@staticmethod
def createAizekRobot():
gpio.setmode(gpio.BOARD)
lmotor = RedbotMotorActor(gpio, 8, 10, 12)
rmotor = RedbotMotorActor(gpio, 11, 13, 15)
spi = MCP3008SpiInterface(0)
wencoder = RedbotWheelEncoderSensor(spi)
lsensor = SharpIrDistanceSensor(spi, 5)
fsensor = SharpIrDistanceSensor(spi, 4)
rsensor = SharpIrDistanceSensor(spi, 3)
wheel_radius = 0.032
wheel_distance = 0.1
| wheel_encoder=wencoder,
left_distance_sensor=lsensor,
front_distance_sensor=fsensor,
right_distance_sensor=rsensor,
wheel_radius=wheel_radius,
wheel_distance=wheel_distance,
)
return robot | robot = AizekRobot(
left_motor=lmotor,
right_motor=rmotor, | random_line_split |
factory.py | from RPi import GPIO as gpio
from robotics.actors.redbot_motor_actor import RedbotMotorActor
from robotics.interfaces.spi.mcp3008_spi_interface import MCP3008SpiInterface
from robotics.robots.aizek_robot import AizekRobot
from robotics.sensors.redbot_wheel_encoder_sensor import RedbotWheelEncoderSensor
from robotics.sensors.sharp_ir_distance_sensor import SharpIrDistanceSensor
class RobotFactory(object):
@staticmethod
def | ():
gpio.setmode(gpio.BOARD)
lmotor = RedbotMotorActor(gpio, 8, 10, 12)
rmotor = RedbotMotorActor(gpio, 11, 13, 15)
spi = MCP3008SpiInterface(0)
wencoder = RedbotWheelEncoderSensor(spi)
lsensor = SharpIrDistanceSensor(spi, 5)
fsensor = SharpIrDistanceSensor(spi, 4)
rsensor = SharpIrDistanceSensor(spi, 3)
wheel_radius = 0.032
wheel_distance = 0.1
robot = AizekRobot(
left_motor=lmotor,
right_motor=rmotor,
wheel_encoder=wencoder,
left_distance_sensor=lsensor,
front_distance_sensor=fsensor,
right_distance_sensor=rsensor,
wheel_radius=wheel_radius,
wheel_distance=wheel_distance,
)
return robot
| createAizekRobot | identifier_name |
factory.py | from RPi import GPIO as gpio
from robotics.actors.redbot_motor_actor import RedbotMotorActor
from robotics.interfaces.spi.mcp3008_spi_interface import MCP3008SpiInterface
from robotics.robots.aizek_robot import AizekRobot
from robotics.sensors.redbot_wheel_encoder_sensor import RedbotWheelEncoderSensor
from robotics.sensors.sharp_ir_distance_sensor import SharpIrDistanceSensor
class RobotFactory(object):
| @staticmethod
def createAizekRobot():
gpio.setmode(gpio.BOARD)
lmotor = RedbotMotorActor(gpio, 8, 10, 12)
rmotor = RedbotMotorActor(gpio, 11, 13, 15)
spi = MCP3008SpiInterface(0)
wencoder = RedbotWheelEncoderSensor(spi)
lsensor = SharpIrDistanceSensor(spi, 5)
fsensor = SharpIrDistanceSensor(spi, 4)
rsensor = SharpIrDistanceSensor(spi, 3)
wheel_radius = 0.032
wheel_distance = 0.1
robot = AizekRobot(
left_motor=lmotor,
right_motor=rmotor,
wheel_encoder=wencoder,
left_distance_sensor=lsensor,
front_distance_sensor=fsensor,
right_distance_sensor=rsensor,
wheel_radius=wheel_radius,
wheel_distance=wheel_distance,
)
return robot | identifier_body | |
epw2wea.py | # coding=utf-8
from ._commandbase import RadianceCommand
from ..datatype import RadiancePath
import os
class Epw2wea(RadianceCommand):
"""epw2wea transforms an EnergyPlus weather data (.epw) file into
the DAYSIM weather file format, for use with the RADIANCE gendaymtx
program.
Attributes:
epw_file: Filepath of the epw file that is to be converted into wea
format.
Usage:
from honeybee_plus.radiance.command.epw2wea import Epw2wea.
#create an epw2wea command.
epwWea = Epw2wea(epw_fileName='c:/ladybug/test.epw')
"""
_epw_file = RadiancePath('_epw_file',
descriptive_name='Epw weather data file',
relative_path=None, check_exists=False)
output_wea_file = RadiancePath('output_wea_file',
descriptive_name='Output wea file',
relative_path=None, check_exists=False)
def __init__(self, epw_file=None, output_wea_file=None):
RadianceCommand.__init__(self)
self.epw_file = epw_file
"""The path of the epw file that is to be converted to a wea file."""
self.output_wea_file = output_wea_file
"""The path of the output wea file. Note that this path will be created
if not specified by the user."""
@property
def epw_file(self):
|
@epw_file.setter
def epw_file(self, value):
"""The path of the epw file that is to be converted to a wea file."""
if value:
self._epw_file = value
if not self.output_wea_file._value:
self.output_wea_file = os.path.splitext(value)[0] + '.wea'
else:
self._epw_file = None
def to_rad_string(self, relative_path=False):
"""Return full radiance command as string"""
rad_string = "%s %s %s" % (
'"%s"' % os.path.join(self.radbin_path, 'epw2wea'),
self.epw_file.to_rad_string(),
self.output_wea_file.to_rad_string())
# self.check_input_files(rad_string)
return rad_string
@property
def input_files(self):
"""Return input files specified by user."""
return self.epw_file.normpath,
| return self._epw_file | identifier_body |
epw2wea.py | # coding=utf-8
from ._commandbase import RadianceCommand
from ..datatype import RadiancePath
import os
class Epw2wea(RadianceCommand):
"""epw2wea transforms an EnergyPlus weather data (.epw) file into
the DAYSIM weather file format, for use with the RADIANCE gendaymtx
program.
Attributes:
epw_file: Filepath of the epw file that is to be converted into wea
format.
Usage:
from honeybee_plus.radiance.command.epw2wea import Epw2wea.
#create an epw2wea command.
epwWea = Epw2wea(epw_fileName='c:/ladybug/test.epw')
"""
_epw_file = RadiancePath('_epw_file',
descriptive_name='Epw weather data file',
relative_path=None, check_exists=False)
output_wea_file = RadiancePath('output_wea_file',
descriptive_name='Output wea file',
relative_path=None, check_exists=False)
def __init__(self, epw_file=None, output_wea_file=None):
RadianceCommand.__init__(self)
self.epw_file = epw_file
"""The path of the epw file that is to be converted to a wea file."""
self.output_wea_file = output_wea_file
"""The path of the output wea file. Note that this path will be created
if not specified by the user."""
@property
def epw_file(self):
return self._epw_file
@epw_file.setter
def epw_file(self, value):
"""The path of the epw file that is to be converted to a wea file."""
if value:
self._epw_file = value
if not self.output_wea_file._value:
self.output_wea_file = os.path.splitext(value)[0] + '.wea'
else:
|
def to_rad_string(self, relative_path=False):
"""Return full radiance command as string"""
rad_string = "%s %s %s" % (
'"%s"' % os.path.join(self.radbin_path, 'epw2wea'),
self.epw_file.to_rad_string(),
self.output_wea_file.to_rad_string())
# self.check_input_files(rad_string)
return rad_string
@property
def input_files(self):
"""Return input files specified by user."""
return self.epw_file.normpath,
| self._epw_file = None | conditional_block |
epw2wea.py | # coding=utf-8
from ._commandbase import RadianceCommand
from ..datatype import RadiancePath
import os
class Epw2wea(RadianceCommand):
"""epw2wea transforms an EnergyPlus weather data (.epw) file into
the DAYSIM weather file format, for use with the RADIANCE gendaymtx
program.
Attributes:
epw_file: Filepath of the epw file that is to be converted into wea
format.
Usage:
from honeybee_plus.radiance.command.epw2wea import Epw2wea.
#create an epw2wea command.
epwWea = Epw2wea(epw_fileName='c:/ladybug/test.epw')
"""
_epw_file = RadiancePath('_epw_file',
descriptive_name='Epw weather data file',
relative_path=None, check_exists=False)
output_wea_file = RadiancePath('output_wea_file',
descriptive_name='Output wea file',
relative_path=None, check_exists=False)
def __init__(self, epw_file=None, output_wea_file=None):
RadianceCommand.__init__(self)
self.epw_file = epw_file
"""The path of the epw file that is to be converted to a wea file."""
self.output_wea_file = output_wea_file
"""The path of the output wea file. Note that this path will be created
if not specified by the user."""
@property
def epw_file(self):
return self._epw_file
@epw_file.setter
def epw_file(self, value):
"""The path of the epw file that is to be converted to a wea file."""
if value:
self._epw_file = value
if not self.output_wea_file._value:
self.output_wea_file = os.path.splitext(value)[0] + '.wea'
else:
self._epw_file = None
def | (self, relative_path=False):
"""Return full radiance command as string"""
rad_string = "%s %s %s" % (
'"%s"' % os.path.join(self.radbin_path, 'epw2wea'),
self.epw_file.to_rad_string(),
self.output_wea_file.to_rad_string())
# self.check_input_files(rad_string)
return rad_string
@property
def input_files(self):
"""Return input files specified by user."""
return self.epw_file.normpath,
| to_rad_string | identifier_name |
epw2wea.py | # coding=utf-8
from ._commandbase import RadianceCommand
from ..datatype import RadiancePath
import os
class Epw2wea(RadianceCommand):
"""epw2wea transforms an EnergyPlus weather data (.epw) file into
the DAYSIM weather file format, for use with the RADIANCE gendaymtx
program.
Attributes:
epw_file: Filepath of the epw file that is to be converted into wea
format.
Usage:
from honeybee_plus.radiance.command.epw2wea import Epw2wea.
#create an epw2wea command.
epwWea = Epw2wea(epw_fileName='c:/ladybug/test.epw') | """
_epw_file = RadiancePath('_epw_file',
descriptive_name='Epw weather data file',
relative_path=None, check_exists=False)
output_wea_file = RadiancePath('output_wea_file',
descriptive_name='Output wea file',
relative_path=None, check_exists=False)
def __init__(self, epw_file=None, output_wea_file=None):
RadianceCommand.__init__(self)
self.epw_file = epw_file
"""The path of the epw file that is to be converted to a wea file."""
self.output_wea_file = output_wea_file
"""The path of the output wea file. Note that this path will be created
if not specified by the user."""
@property
def epw_file(self):
return self._epw_file
@epw_file.setter
def epw_file(self, value):
"""The path of the epw file that is to be converted to a wea file."""
if value:
self._epw_file = value
if not self.output_wea_file._value:
self.output_wea_file = os.path.splitext(value)[0] + '.wea'
else:
self._epw_file = None
def to_rad_string(self, relative_path=False):
"""Return full radiance command as string"""
rad_string = "%s %s %s" % (
'"%s"' % os.path.join(self.radbin_path, 'epw2wea'),
self.epw_file.to_rad_string(),
self.output_wea_file.to_rad_string())
# self.check_input_files(rad_string)
return rad_string
@property
def input_files(self):
"""Return input files specified by user."""
return self.epw_file.normpath, | random_line_split | |
customer.d.ts | /**
* @file declaration of the Customer interface
* @author Bruno Ferreira <shirayuki@kitsune.com.br>
* @license MIT
*/
import { CustomVariable } from './custom-variable';
import { Object } from './object';
/**
* Defines a customer associated with an IUGU account
*/
export interface Customer extends Object {
/**
* Customer e-mail address. Required on creation.
*
* @type String
*/
email?: string;
/**
* Customer name. Required on creation.
*
* @type String
*/
name?: string;
/**
* Additional information
*
* @type String
*/
notes?: string;
/**
* The CPF or CNPJ. Required if emitting registered boletos
*
* @type String
*/
cpf_cnpj?: string;
/**
* Additional e-mail addresses for carbon-copy
*
* @type String
*/
cc_emails?: string;
/**
* CEP. Required if emitting registered boletos
*
* @type String
*/
zip_code?: string;
/**
* Address number. Required if zip_code is set
*
* @type Integer number
*/
number?: number;
/**
* Street name. Required if zip_code is set and incomplete. | * @type String
*/
street?: string;
/**
* Address' city
*
* @type String
*/
city?: string;
/**
* Address' state
*
* @type String
*/
state?: string;
/**
* Address' district. Required if zip_code is set.
*
* @type String
*/
district?: string;
/**
* Address' additional information
*
* @example room number, floor number, nearby references
* @type String
*/
complement?: string;
/**
* Custom information
*
* @example [{ name: 'database_id', value: '1' }]
* @type CustomVariable[]
*/
custom_variables?: CustomVariable[];
} | * | random_line_split |
state.py | # Copyright 2019 Objectif Libre
#
# 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 flask
import voluptuous
from werkzeug import exceptions as http_exceptions
from cloudkitty.api.v2 import base
from cloudkitty.api.v2 import utils as api_utils
from cloudkitty.common import policy
from cloudkitty import messaging
from cloudkitty import storage_state
from cloudkitty import tzutils
from cloudkitty import validation_utils as vutils
class ScopeState(base.BaseResource):
@classmethod
def reload(cls):
super(ScopeState, cls).reload()
cls._client = messaging.get_client()
cls._storage_state = storage_state.StateManager()
@api_utils.paginated
@api_utils.add_input_schema('query', {
voluptuous.Optional('scope_id', default=[]):
api_utils.MultiQueryParam(str),
voluptuous.Optional('scope_key', default=[]):
api_utils.MultiQueryParam(str),
voluptuous.Optional('fetcher', default=[]):
api_utils.MultiQueryParam(str),
voluptuous.Optional('collector', default=[]):
api_utils.MultiQueryParam(str),
})
@api_utils.add_output_schema({'results': [{
voluptuous.Required('scope_id'): vutils.get_string_type(),
voluptuous.Required('scope_key'): vutils.get_string_type(),
voluptuous.Required('fetcher'): vutils.get_string_type(),
voluptuous.Required('collector'): vutils.get_string_type(),
voluptuous.Required('state'): vutils.get_string_type(),
}]})
def get(self,
offset=0,
limit=100,
scope_id=None,
scope_key=None,
fetcher=None,
collector=None):
policy.authorize(
flask.request.context,
'scope:get_state',
{'tenant_id': scope_id or flask.request.context.project_id}
)
results = self._storage_state.get_all(
identifier=scope_id,
scope_key=scope_key,
fetcher=fetcher,
collector=collector,
offset=offset,
limit=limit,
)
if len(results) < 1:
|
return {
'results': [{
'scope_id': r.identifier,
'scope_key': r.scope_key,
'fetcher': r.fetcher,
'collector': r.collector,
'state': r.state.isoformat(),
} for r in results]
}
@api_utils.add_input_schema('body', {
voluptuous.Exclusive('all_scopes', 'scope_selector'):
voluptuous.Boolean(),
voluptuous.Exclusive('scope_id', 'scope_selector'):
api_utils.MultiQueryParam(str),
voluptuous.Optional('scope_key', default=[]):
api_utils.MultiQueryParam(str),
voluptuous.Optional('fetcher', default=[]):
api_utils.MultiQueryParam(str),
voluptuous.Optional('collector', default=[]):
api_utils.MultiQueryParam(str),
voluptuous.Required('state'):
voluptuous.Coerce(tzutils.dt_from_iso),
})
def put(self,
all_scopes=False,
scope_id=None,
scope_key=None,
fetcher=None,
collector=None,
state=None):
policy.authorize(
flask.request.context,
'scope:reset_state',
{'tenant_id': scope_id or flask.request.context.project_id}
)
if not all_scopes and scope_id is None:
raise http_exceptions.BadRequest(
"Either all_scopes or a scope_id should be specified.")
results = self._storage_state.get_all(
identifier=scope_id,
scope_key=scope_key,
fetcher=fetcher,
collector=collector,
)
if len(results) < 1:
raise http_exceptions.NotFound(
"No resource found for provided filters.")
serialized_results = [{
'scope_id': r.identifier,
'scope_key': r.scope_key,
'fetcher': r.fetcher,
'collector': r.collector,
} for r in results]
self._client.cast({}, 'reset_state', res_data={
'scopes': serialized_results, 'state': state.isoformat(),
})
return {}, 202
| raise http_exceptions.NotFound(
"No resource found for provided filters.") | conditional_block |
state.py | # Copyright 2019 Objectif Libre
#
# 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 flask
import voluptuous
from werkzeug import exceptions as http_exceptions
from cloudkitty.api.v2 import base
from cloudkitty.api.v2 import utils as api_utils
from cloudkitty.common import policy
from cloudkitty import messaging
from cloudkitty import storage_state
from cloudkitty import tzutils
from cloudkitty import validation_utils as vutils
class ScopeState(base.BaseResource):
@classmethod
def reload(cls):
super(ScopeState, cls).reload()
cls._client = messaging.get_client()
cls._storage_state = storage_state.StateManager()
@api_utils.paginated
@api_utils.add_input_schema('query', {
voluptuous.Optional('scope_id', default=[]):
api_utils.MultiQueryParam(str),
voluptuous.Optional('scope_key', default=[]):
api_utils.MultiQueryParam(str),
voluptuous.Optional('fetcher', default=[]):
api_utils.MultiQueryParam(str),
voluptuous.Optional('collector', default=[]):
api_utils.MultiQueryParam(str),
})
@api_utils.add_output_schema({'results': [{
voluptuous.Required('scope_id'): vutils.get_string_type(),
voluptuous.Required('scope_key'): vutils.get_string_type(),
voluptuous.Required('fetcher'): vutils.get_string_type(),
voluptuous.Required('collector'): vutils.get_string_type(),
voluptuous.Required('state'): vutils.get_string_type(),
}]})
def get(self,
offset=0,
limit=100,
scope_id=None,
scope_key=None,
fetcher=None,
collector=None):
policy.authorize( | results = self._storage_state.get_all(
identifier=scope_id,
scope_key=scope_key,
fetcher=fetcher,
collector=collector,
offset=offset,
limit=limit,
)
if len(results) < 1:
raise http_exceptions.NotFound(
"No resource found for provided filters.")
return {
'results': [{
'scope_id': r.identifier,
'scope_key': r.scope_key,
'fetcher': r.fetcher,
'collector': r.collector,
'state': r.state.isoformat(),
} for r in results]
}
@api_utils.add_input_schema('body', {
voluptuous.Exclusive('all_scopes', 'scope_selector'):
voluptuous.Boolean(),
voluptuous.Exclusive('scope_id', 'scope_selector'):
api_utils.MultiQueryParam(str),
voluptuous.Optional('scope_key', default=[]):
api_utils.MultiQueryParam(str),
voluptuous.Optional('fetcher', default=[]):
api_utils.MultiQueryParam(str),
voluptuous.Optional('collector', default=[]):
api_utils.MultiQueryParam(str),
voluptuous.Required('state'):
voluptuous.Coerce(tzutils.dt_from_iso),
})
def put(self,
all_scopes=False,
scope_id=None,
scope_key=None,
fetcher=None,
collector=None,
state=None):
policy.authorize(
flask.request.context,
'scope:reset_state',
{'tenant_id': scope_id or flask.request.context.project_id}
)
if not all_scopes and scope_id is None:
raise http_exceptions.BadRequest(
"Either all_scopes or a scope_id should be specified.")
results = self._storage_state.get_all(
identifier=scope_id,
scope_key=scope_key,
fetcher=fetcher,
collector=collector,
)
if len(results) < 1:
raise http_exceptions.NotFound(
"No resource found for provided filters.")
serialized_results = [{
'scope_id': r.identifier,
'scope_key': r.scope_key,
'fetcher': r.fetcher,
'collector': r.collector,
} for r in results]
self._client.cast({}, 'reset_state', res_data={
'scopes': serialized_results, 'state': state.isoformat(),
})
return {}, 202 | flask.request.context,
'scope:get_state',
{'tenant_id': scope_id or flask.request.context.project_id}
) | random_line_split |
state.py | # Copyright 2019 Objectif Libre
#
# 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 flask
import voluptuous
from werkzeug import exceptions as http_exceptions
from cloudkitty.api.v2 import base
from cloudkitty.api.v2 import utils as api_utils
from cloudkitty.common import policy
from cloudkitty import messaging
from cloudkitty import storage_state
from cloudkitty import tzutils
from cloudkitty import validation_utils as vutils
class ScopeState(base.BaseResource):
@classmethod
def | (cls):
super(ScopeState, cls).reload()
cls._client = messaging.get_client()
cls._storage_state = storage_state.StateManager()
@api_utils.paginated
@api_utils.add_input_schema('query', {
voluptuous.Optional('scope_id', default=[]):
api_utils.MultiQueryParam(str),
voluptuous.Optional('scope_key', default=[]):
api_utils.MultiQueryParam(str),
voluptuous.Optional('fetcher', default=[]):
api_utils.MultiQueryParam(str),
voluptuous.Optional('collector', default=[]):
api_utils.MultiQueryParam(str),
})
@api_utils.add_output_schema({'results': [{
voluptuous.Required('scope_id'): vutils.get_string_type(),
voluptuous.Required('scope_key'): vutils.get_string_type(),
voluptuous.Required('fetcher'): vutils.get_string_type(),
voluptuous.Required('collector'): vutils.get_string_type(),
voluptuous.Required('state'): vutils.get_string_type(),
}]})
def get(self,
offset=0,
limit=100,
scope_id=None,
scope_key=None,
fetcher=None,
collector=None):
policy.authorize(
flask.request.context,
'scope:get_state',
{'tenant_id': scope_id or flask.request.context.project_id}
)
results = self._storage_state.get_all(
identifier=scope_id,
scope_key=scope_key,
fetcher=fetcher,
collector=collector,
offset=offset,
limit=limit,
)
if len(results) < 1:
raise http_exceptions.NotFound(
"No resource found for provided filters.")
return {
'results': [{
'scope_id': r.identifier,
'scope_key': r.scope_key,
'fetcher': r.fetcher,
'collector': r.collector,
'state': r.state.isoformat(),
} for r in results]
}
@api_utils.add_input_schema('body', {
voluptuous.Exclusive('all_scopes', 'scope_selector'):
voluptuous.Boolean(),
voluptuous.Exclusive('scope_id', 'scope_selector'):
api_utils.MultiQueryParam(str),
voluptuous.Optional('scope_key', default=[]):
api_utils.MultiQueryParam(str),
voluptuous.Optional('fetcher', default=[]):
api_utils.MultiQueryParam(str),
voluptuous.Optional('collector', default=[]):
api_utils.MultiQueryParam(str),
voluptuous.Required('state'):
voluptuous.Coerce(tzutils.dt_from_iso),
})
def put(self,
all_scopes=False,
scope_id=None,
scope_key=None,
fetcher=None,
collector=None,
state=None):
policy.authorize(
flask.request.context,
'scope:reset_state',
{'tenant_id': scope_id or flask.request.context.project_id}
)
if not all_scopes and scope_id is None:
raise http_exceptions.BadRequest(
"Either all_scopes or a scope_id should be specified.")
results = self._storage_state.get_all(
identifier=scope_id,
scope_key=scope_key,
fetcher=fetcher,
collector=collector,
)
if len(results) < 1:
raise http_exceptions.NotFound(
"No resource found for provided filters.")
serialized_results = [{
'scope_id': r.identifier,
'scope_key': r.scope_key,
'fetcher': r.fetcher,
'collector': r.collector,
} for r in results]
self._client.cast({}, 'reset_state', res_data={
'scopes': serialized_results, 'state': state.isoformat(),
})
return {}, 202
| reload | identifier_name |
state.py | # Copyright 2019 Objectif Libre
#
# 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 flask
import voluptuous
from werkzeug import exceptions as http_exceptions
from cloudkitty.api.v2 import base
from cloudkitty.api.v2 import utils as api_utils
from cloudkitty.common import policy
from cloudkitty import messaging
from cloudkitty import storage_state
from cloudkitty import tzutils
from cloudkitty import validation_utils as vutils
class ScopeState(base.BaseResource):
| @classmethod
def reload(cls):
super(ScopeState, cls).reload()
cls._client = messaging.get_client()
cls._storage_state = storage_state.StateManager()
@api_utils.paginated
@api_utils.add_input_schema('query', {
voluptuous.Optional('scope_id', default=[]):
api_utils.MultiQueryParam(str),
voluptuous.Optional('scope_key', default=[]):
api_utils.MultiQueryParam(str),
voluptuous.Optional('fetcher', default=[]):
api_utils.MultiQueryParam(str),
voluptuous.Optional('collector', default=[]):
api_utils.MultiQueryParam(str),
})
@api_utils.add_output_schema({'results': [{
voluptuous.Required('scope_id'): vutils.get_string_type(),
voluptuous.Required('scope_key'): vutils.get_string_type(),
voluptuous.Required('fetcher'): vutils.get_string_type(),
voluptuous.Required('collector'): vutils.get_string_type(),
voluptuous.Required('state'): vutils.get_string_type(),
}]})
def get(self,
offset=0,
limit=100,
scope_id=None,
scope_key=None,
fetcher=None,
collector=None):
policy.authorize(
flask.request.context,
'scope:get_state',
{'tenant_id': scope_id or flask.request.context.project_id}
)
results = self._storage_state.get_all(
identifier=scope_id,
scope_key=scope_key,
fetcher=fetcher,
collector=collector,
offset=offset,
limit=limit,
)
if len(results) < 1:
raise http_exceptions.NotFound(
"No resource found for provided filters.")
return {
'results': [{
'scope_id': r.identifier,
'scope_key': r.scope_key,
'fetcher': r.fetcher,
'collector': r.collector,
'state': r.state.isoformat(),
} for r in results]
}
@api_utils.add_input_schema('body', {
voluptuous.Exclusive('all_scopes', 'scope_selector'):
voluptuous.Boolean(),
voluptuous.Exclusive('scope_id', 'scope_selector'):
api_utils.MultiQueryParam(str),
voluptuous.Optional('scope_key', default=[]):
api_utils.MultiQueryParam(str),
voluptuous.Optional('fetcher', default=[]):
api_utils.MultiQueryParam(str),
voluptuous.Optional('collector', default=[]):
api_utils.MultiQueryParam(str),
voluptuous.Required('state'):
voluptuous.Coerce(tzutils.dt_from_iso),
})
def put(self,
all_scopes=False,
scope_id=None,
scope_key=None,
fetcher=None,
collector=None,
state=None):
policy.authorize(
flask.request.context,
'scope:reset_state',
{'tenant_id': scope_id or flask.request.context.project_id}
)
if not all_scopes and scope_id is None:
raise http_exceptions.BadRequest(
"Either all_scopes or a scope_id should be specified.")
results = self._storage_state.get_all(
identifier=scope_id,
scope_key=scope_key,
fetcher=fetcher,
collector=collector,
)
if len(results) < 1:
raise http_exceptions.NotFound(
"No resource found for provided filters.")
serialized_results = [{
'scope_id': r.identifier,
'scope_key': r.scope_key,
'fetcher': r.fetcher,
'collector': r.collector,
} for r in results]
self._client.cast({}, 'reset_state', res_data={
'scopes': serialized_results, 'state': state.isoformat(),
})
return {}, 202 | identifier_body | |
error.rs | use mysql;
use std::{error, fmt, result};
#[derive(Debug)]
pub enum Error {
Mysql(mysql::Error),
RecordNotFound(u64),
ColumnNotFound,
AddressChecksumToTrits,
}
pub type Result<T> = result::Result<T, Error>;
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::Mysql(ref err) => write!(f, "MySQL error: {}", err),
Error::RecordNotFound(id) => write!(f, "Record not found ({})", id),
Error::ColumnNotFound => write!(f, "Column not found"),
Error::AddressChecksumToTrits => {
write!(f, "can't convert address checksum to trits")
}
}
}
}
impl error::Error for Error {
fn description(&self) -> &str {
match *self {
Error::Mysql(ref err) => err.description(),
Error::RecordNotFound(_) => "Record not found",
Error::ColumnNotFound => "Column not found",
Error::AddressChecksumToTrits => "Can't convert to trits",
}
}
fn cause(&self) -> Option<&error::Error> |
}
impl From<mysql::Error> for Error {
fn from(err: mysql::Error) -> Error {
Error::Mysql(err)
}
}
| {
match *self {
Error::Mysql(ref err) => Some(err),
Error::RecordNotFound(_) |
Error::ColumnNotFound |
Error::AddressChecksumToTrits => None,
}
} | identifier_body |
error.rs | use mysql;
use std::{error, fmt, result};
#[derive(Debug)]
pub enum Error {
Mysql(mysql::Error),
RecordNotFound(u64),
ColumnNotFound,
AddressChecksumToTrits,
}
pub type Result<T> = result::Result<T, Error>;
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::Mysql(ref err) => write!(f, "MySQL error: {}", err),
Error::RecordNotFound(id) => write!(f, "Record not found ({})", id),
Error::ColumnNotFound => write!(f, "Column not found"),
Error::AddressChecksumToTrits => { | write!(f, "can't convert address checksum to trits")
}
}
}
}
impl error::Error for Error {
fn description(&self) -> &str {
match *self {
Error::Mysql(ref err) => err.description(),
Error::RecordNotFound(_) => "Record not found",
Error::ColumnNotFound => "Column not found",
Error::AddressChecksumToTrits => "Can't convert to trits",
}
}
fn cause(&self) -> Option<&error::Error> {
match *self {
Error::Mysql(ref err) => Some(err),
Error::RecordNotFound(_) |
Error::ColumnNotFound |
Error::AddressChecksumToTrits => None,
}
}
}
impl From<mysql::Error> for Error {
fn from(err: mysql::Error) -> Error {
Error::Mysql(err)
}
} | random_line_split | |
error.rs | use mysql;
use std::{error, fmt, result};
#[derive(Debug)]
pub enum Error {
Mysql(mysql::Error),
RecordNotFound(u64),
ColumnNotFound,
AddressChecksumToTrits,
}
pub type Result<T> = result::Result<T, Error>;
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::Mysql(ref err) => write!(f, "MySQL error: {}", err),
Error::RecordNotFound(id) => write!(f, "Record not found ({})", id),
Error::ColumnNotFound => write!(f, "Column not found"),
Error::AddressChecksumToTrits => {
write!(f, "can't convert address checksum to trits")
}
}
}
}
impl error::Error for Error {
fn | (&self) -> &str {
match *self {
Error::Mysql(ref err) => err.description(),
Error::RecordNotFound(_) => "Record not found",
Error::ColumnNotFound => "Column not found",
Error::AddressChecksumToTrits => "Can't convert to trits",
}
}
fn cause(&self) -> Option<&error::Error> {
match *self {
Error::Mysql(ref err) => Some(err),
Error::RecordNotFound(_) |
Error::ColumnNotFound |
Error::AddressChecksumToTrits => None,
}
}
}
impl From<mysql::Error> for Error {
fn from(err: mysql::Error) -> Error {
Error::Mysql(err)
}
}
| description | identifier_name |
models.py | from django.db import models
from django_hstore import hstore
# Create your models here.
class Place(models.Model):
osm_type = models.CharField(max_length=1)
osm_id = models.IntegerField(primary_key=True)
class_field = models.TextField(db_column='class') # Field renamed because it was a Python reserved word.
type = models.TextField()
name = hstore.DictionaryField(blank=True) # This field type is a guess.
admin_level = models.IntegerField(null=True, blank=True)
housenumber = models.TextField(blank=True)
street = models.TextField(blank=True)
isin = models.TextField(blank=True) | geometry = models.TextField() # This field type is a guess.
objects = hstore.HStoreManager()
class Meta :
managed = False
db_table= 'place'
unique_together = ('osm_id', 'class_field')
class Phonetique(models.Model):
nom = models.TextField()
#osm_id = models.IntegerField()
osm = models.ForeignKey(Place)
poids = models.IntegerField()
ville = models.CharField(max_length=200)
semantic = models.CharField(max_length=25)
class Meta :
managed = False
db_table ='phonetique'
def __unicode__(self):
return '%d, %s' % (self.poids, self.nom) | postcode = models.TextField(blank=True)
country_code = models.CharField(max_length=2, blank=True)
extratags = models.TextField(blank=True) # This field type is a guess. | random_line_split |
models.py | from django.db import models
from django_hstore import hstore
# Create your models here.
class Place(models.Model):
osm_type = models.CharField(max_length=1)
osm_id = models.IntegerField(primary_key=True)
class_field = models.TextField(db_column='class') # Field renamed because it was a Python reserved word.
type = models.TextField()
name = hstore.DictionaryField(blank=True) # This field type is a guess.
admin_level = models.IntegerField(null=True, blank=True)
housenumber = models.TextField(blank=True)
street = models.TextField(blank=True)
isin = models.TextField(blank=True)
postcode = models.TextField(blank=True)
country_code = models.CharField(max_length=2, blank=True)
extratags = models.TextField(blank=True) # This field type is a guess.
geometry = models.TextField() # This field type is a guess.
objects = hstore.HStoreManager()
class Meta :
|
class Phonetique(models.Model):
nom = models.TextField()
#osm_id = models.IntegerField()
osm = models.ForeignKey(Place)
poids = models.IntegerField()
ville = models.CharField(max_length=200)
semantic = models.CharField(max_length=25)
class Meta :
managed = False
db_table ='phonetique'
def __unicode__(self):
return '%d, %s' % (self.poids, self.nom)
| managed = False
db_table= 'place'
unique_together = ('osm_id', 'class_field') | identifier_body |
models.py | from django.db import models
from django_hstore import hstore
# Create your models here.
class Place(models.Model):
osm_type = models.CharField(max_length=1)
osm_id = models.IntegerField(primary_key=True)
class_field = models.TextField(db_column='class') # Field renamed because it was a Python reserved word.
type = models.TextField()
name = hstore.DictionaryField(blank=True) # This field type is a guess.
admin_level = models.IntegerField(null=True, blank=True)
housenumber = models.TextField(blank=True)
street = models.TextField(blank=True)
isin = models.TextField(blank=True)
postcode = models.TextField(blank=True)
country_code = models.CharField(max_length=2, blank=True)
extratags = models.TextField(blank=True) # This field type is a guess.
geometry = models.TextField() # This field type is a guess.
objects = hstore.HStoreManager()
class Meta :
managed = False
db_table= 'place'
unique_together = ('osm_id', 'class_field')
class | (models.Model):
nom = models.TextField()
#osm_id = models.IntegerField()
osm = models.ForeignKey(Place)
poids = models.IntegerField()
ville = models.CharField(max_length=200)
semantic = models.CharField(max_length=25)
class Meta :
managed = False
db_table ='phonetique'
def __unicode__(self):
return '%d, %s' % (self.poids, self.nom)
| Phonetique | identifier_name |
webpack-isomorphic-tools.js | var WebpackIsomorphicToolsPlugin = require('webpack-isomorphic-tools/plugin');
// see this link for more info on what all of this means
// https://github.com/halt-hammerzeit/webpack-isomorphic-tools
module.exports = {
webpack_assets_file_path: 'webpack-stats.json',
assets: {
images: {
extensions: [
'jpeg',
'jpg',
'png',
'gif',
'svg'
],
parser: WebpackIsomorphicToolsPlugin.url_loader_parser
},
style_modules: {
extension: 'scss',
filter: function(m, regex, options, log) {
if (!options.development) {
return regex.test(m.name);
}
//filter by modules with '.scss' inside name string, that also have name and moduleName that end with 'ss'(allows for css, less, sass, and scss extensions)
//this ensures that the proper scss module is returned, so that namePrefix variable is no longer needed
return (regex.test(m.name) && m.name.slice(-2) === 'ss' && m.reasons[0].moduleName.slice(-2) === 'ss');
},
naming: function(m, options, log) {
//find index of '/src' inside the module name, slice it and resolve path
var srcIndex = m.name.indexOf('/src');
var name = '.' + m.name.slice(srcIndex);
if (name) {
// Resolve the e.g.: "C:\" issue on windows
const i = name.indexOf(':');
if (i >= 0) {
name = name.slice(i + 1);
}
}
return name;
},
parser: function(m, options, log) {
if (m.source) |
}
}
}
} | {
var regex = options.development ? /exports\.locals = ((.|\n)+);/ : /module\.exports = ((.|\n)+);/;
var match = m.source.match(regex);
return match ? JSON.parse(match[1]) : {};
} | conditional_block |
webpack-isomorphic-tools.js | var WebpackIsomorphicToolsPlugin = require('webpack-isomorphic-tools/plugin');
// see this link for more info on what all of this means
// https://github.com/halt-hammerzeit/webpack-isomorphic-tools
module.exports = {
webpack_assets_file_path: 'webpack-stats.json',
assets: {
images: {
extensions: [
'jpeg',
'jpg',
'png',
'gif',
'svg'
],
parser: WebpackIsomorphicToolsPlugin.url_loader_parser
}, | if (!options.development) {
return regex.test(m.name);
}
//filter by modules with '.scss' inside name string, that also have name and moduleName that end with 'ss'(allows for css, less, sass, and scss extensions)
//this ensures that the proper scss module is returned, so that namePrefix variable is no longer needed
return (regex.test(m.name) && m.name.slice(-2) === 'ss' && m.reasons[0].moduleName.slice(-2) === 'ss');
},
naming: function(m, options, log) {
//find index of '/src' inside the module name, slice it and resolve path
var srcIndex = m.name.indexOf('/src');
var name = '.' + m.name.slice(srcIndex);
if (name) {
// Resolve the e.g.: "C:\" issue on windows
const i = name.indexOf(':');
if (i >= 0) {
name = name.slice(i + 1);
}
}
return name;
},
parser: function(m, options, log) {
if (m.source) {
var regex = options.development ? /exports\.locals = ((.|\n)+);/ : /module\.exports = ((.|\n)+);/;
var match = m.source.match(regex);
return match ? JSON.parse(match[1]) : {};
}
}
}
}
} | style_modules: {
extension: 'scss',
filter: function(m, regex, options, log) { | random_line_split |
systemvision.js | /*
Video's aren't really an uploaded item...we just turn youtube/vimeo links into embeds
*/
var systemvision = P(Element, function(_, super_) {
_.helpText = "<<systemvision>>\nEmbed a SystemVision file. Enter the node id (click 'embed' in SystemVision and in the embed code, look for the 'systemvision.com/node/NODE_ID' url, where NODE_ID is a number you enter here.";
_.klass = ['import_video'];
_.innerHtml = function() {
return '<div class="' + css_prefix + 'top ' + css_prefix + 'focusableItems" data-id="0">' + focusableHTML('CodeBlock', 'SystemVision') + ' node: '
+ focusableHTML('CommandBlock', 'video_url') + ' ' + helpBlock() + '<BR>' + answerSpan() + '</div>';
}
_.postInsertHandler = function() {
super_.postInsertHandler.call(this);
var _this = this;
this.codeBlock = registerFocusable(CodeBlock,this, 'SystemVision', { });
this.block = registerFocusable(CommandBlock, this, 'video_url', { editable: true, border: true, handlers: {blur: function(el) { _this.processUrl(el.toString()); } } });
this.focusableItems = [[this.codeBlock,this.block]];
this.leftJQ.append('<span class="fa fa-upload"></span>');
return this;
}
_.processUrl = function(text) {
if(text.trim() == '') return this.outputBox.clearState().collapse();
var pattern = /^[0-9]+$/;
if(pattern.test(text)) {
var id = text;
} else |
// Success: Delete this block and replace with the video
var stream = !this.worksheet.trackingStream;
if(stream) this.worksheet.startUndoStream();
systemvisionBlock().insertAfter(this).setDocument(id).show();
this.remove();
if(stream) this.worksheet.endUndoStream();
this.worksheet.save();
}
_.toString = function() {
return '{systemvision}{{' + this.argumentList().join('}{') + '}}';
}
});
var systemvisionBlock = P(Element, function(_, super_) {
_.klass = ['systemvision'];
_.savedProperties = ['document_id'];
_.document_id = false;
_.innerHtml = function() {
return '<div class="' + css_prefix + 'top ' + css_prefix + 'focusableItems" data-id="0"><table style="width:100%;"><tbody><tr><td>' + focusableHTML('CodeBlock', '') + '</td><td class="' + css_prefix + 'insert"></td></tr></tbody></table></div>'
}
_.postInsertHandler = function() {
super_.postInsertHandler.call(this);
this.codeBlock = registerFocusable(CodeBlock, this, '', { });
this.focusableItems = [[this.codeBlock]];
return this;
}
_.empty = function() {
return false;
}
_.setDocument = function(document_id) {
this.document_id = document_id;
var html = '<iframe allowfullscreen="true" frameborder="0" width="100%" height="500" scrolling="no" src="https://systemvision.com/node/' + this.document_id + '" title="SystemVision Cloud"></iframe>';
this.insertJQ.html('');
this.insertJQ.append(html);
return this;
}
_.toString = function() {
return '{systemvisionBlock}{{' + this.argumentList().join('}{') + '}}';
}
_.parseSavedProperties = function(args) {
super_.parseSavedProperties.call(this, args);
this.setDocument(this.document_id);
return this;
}
_.mouseClick = function() {
this.codeBlock.focus(L);
return false;
}
}); | {
// No matching provider
this.outputBox.expand();
this.outputBox.setError("Invalid Node ID. Please copy in the node id (click 'embed' in SystemVision and in the embed code, look for the 'systemvision.com/node/NODE_ID' url, where NODE_ID is a number you enter here.");
return;
} | conditional_block |
systemvision.js | /*
Video's aren't really an uploaded item...we just turn youtube/vimeo links into embeds
*/
var systemvision = P(Element, function(_, super_) {
_.helpText = "<<systemvision>>\nEmbed a SystemVision file. Enter the node id (click 'embed' in SystemVision and in the embed code, look for the 'systemvision.com/node/NODE_ID' url, where NODE_ID is a number you enter here.";
_.klass = ['import_video'];
_.innerHtml = function() {
return '<div class="' + css_prefix + 'top ' + css_prefix + 'focusableItems" data-id="0">' + focusableHTML('CodeBlock', 'SystemVision') + ' node: '
+ focusableHTML('CommandBlock', 'video_url') + ' ' + helpBlock() + '<BR>' + answerSpan() + '</div>';
}
_.postInsertHandler = function() {
super_.postInsertHandler.call(this);
var _this = this;
this.codeBlock = registerFocusable(CodeBlock,this, 'SystemVision', { });
this.block = registerFocusable(CommandBlock, this, 'video_url', { editable: true, border: true, handlers: {blur: function(el) { _this.processUrl(el.toString()); } } });
this.focusableItems = [[this.codeBlock,this.block]];
this.leftJQ.append('<span class="fa fa-upload"></span>');
return this;
}
_.processUrl = function(text) {
if(text.trim() == '') return this.outputBox.clearState().collapse();
var pattern = /^[0-9]+$/;
if(pattern.test(text)) {
var id = text;
} else {
// No matching provider
this.outputBox.expand();
this.outputBox.setError("Invalid Node ID. Please copy in the node id (click 'embed' in SystemVision and in the embed code, look for the 'systemvision.com/node/NODE_ID' url, where NODE_ID is a number you enter here.");
return;
}
// Success: Delete this block and replace with the video
var stream = !this.worksheet.trackingStream;
if(stream) this.worksheet.startUndoStream();
systemvisionBlock().insertAfter(this).setDocument(id).show();
this.remove();
if(stream) this.worksheet.endUndoStream();
this.worksheet.save();
}
_.toString = function() {
return '{systemvision}{{' + this.argumentList().join('}{') + '}}';
}
});
var systemvisionBlock = P(Element, function(_, super_) {
_.klass = ['systemvision'];
_.savedProperties = ['document_id'];
_.document_id = false;
_.innerHtml = function() {
return '<div class="' + css_prefix + 'top ' + css_prefix + 'focusableItems" data-id="0"><table style="width:100%;"><tbody><tr><td>' + focusableHTML('CodeBlock', '') + '</td><td class="' + css_prefix + 'insert"></td></tr></tbody></table></div>'
}
_.postInsertHandler = function() {
super_.postInsertHandler.call(this);
this.codeBlock = registerFocusable(CodeBlock, this, '', { });
this.focusableItems = [[this.codeBlock]]; | }
_.empty = function() {
return false;
}
_.setDocument = function(document_id) {
this.document_id = document_id;
var html = '<iframe allowfullscreen="true" frameborder="0" width="100%" height="500" scrolling="no" src="https://systemvision.com/node/' + this.document_id + '" title="SystemVision Cloud"></iframe>';
this.insertJQ.html('');
this.insertJQ.append(html);
return this;
}
_.toString = function() {
return '{systemvisionBlock}{{' + this.argumentList().join('}{') + '}}';
}
_.parseSavedProperties = function(args) {
super_.parseSavedProperties.call(this, args);
this.setDocument(this.document_id);
return this;
}
_.mouseClick = function() {
this.codeBlock.focus(L);
return false;
}
}); | return this; | random_line_split |
bigquerystorage_v1beta2_generated_big_query_write_append_rows_sync.py | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# 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.
#
# Generated code. DO NOT EDIT!
#
# Snippet for AppendRows
# NOTE: This snippet has been automatically generated for illustrative purposes only.
# It may require modifications to work in your environment.
# To install the latest published package dependency, execute the following:
# python3 -m pip install google-cloud-bigquery-storage
# [START bigquerystorage_v1beta2_generated_BigQueryWrite_AppendRows_sync]
from google.cloud import bigquery_storage_v1beta2
def sample_append_rows():
# Create a client
client = bigquery_storage_v1beta2.BigQueryWriteClient()
# Initialize request argument(s)
request = bigquery_storage_v1beta2.AppendRowsRequest(
write_stream="write_stream_value",
)
# This method expects an iterator which contains
# 'bigquery_storage_v1beta2.AppendRowsRequest' objects
# Here we create a generator that yields a single `request` for
# demonstrative purposes.
requests = [request]
def | ():
for request in requests:
yield request
# Make the request
stream = client.append_rows(requests=request_generator())
# Handle the response
for response in stream:
print(response)
# [END bigquerystorage_v1beta2_generated_BigQueryWrite_AppendRows_sync]
| request_generator | identifier_name |
bigquerystorage_v1beta2_generated_big_query_write_append_rows_sync.py | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# 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.
#
# Generated code. DO NOT EDIT!
#
# Snippet for AppendRows
# NOTE: This snippet has been automatically generated for illustrative purposes only.
# It may require modifications to work in your environment.
# To install the latest published package dependency, execute the following:
# python3 -m pip install google-cloud-bigquery-storage
# [START bigquerystorage_v1beta2_generated_BigQueryWrite_AppendRows_sync]
from google.cloud import bigquery_storage_v1beta2
def sample_append_rows():
# Create a client
client = bigquery_storage_v1beta2.BigQueryWriteClient()
# Initialize request argument(s)
request = bigquery_storage_v1beta2.AppendRowsRequest(
write_stream="write_stream_value",
)
# This method expects an iterator which contains
# 'bigquery_storage_v1beta2.AppendRowsRequest' objects
# Here we create a generator that yields a single `request` for
# demonstrative purposes.
requests = [request]
def request_generator():
for request in requests:
|
# Make the request
stream = client.append_rows(requests=request_generator())
# Handle the response
for response in stream:
print(response)
# [END bigquerystorage_v1beta2_generated_BigQueryWrite_AppendRows_sync]
| yield request | conditional_block |
bigquerystorage_v1beta2_generated_big_query_write_append_rows_sync.py | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# 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.
#
# Generated code. DO NOT EDIT!
#
# Snippet for AppendRows
# NOTE: This snippet has been automatically generated for illustrative purposes only.
# It may require modifications to work in your environment.
# To install the latest published package dependency, execute the following:
# python3 -m pip install google-cloud-bigquery-storage
# [START bigquerystorage_v1beta2_generated_BigQueryWrite_AppendRows_sync]
from google.cloud import bigquery_storage_v1beta2
def sample_append_rows():
# Create a client
client = bigquery_storage_v1beta2.BigQueryWriteClient()
# Initialize request argument(s)
request = bigquery_storage_v1beta2.AppendRowsRequest(
write_stream="write_stream_value",
)
# This method expects an iterator which contains
# 'bigquery_storage_v1beta2.AppendRowsRequest' objects
# Here we create a generator that yields a single `request` for
# demonstrative purposes.
requests = [request]
def request_generator():
|
# Make the request
stream = client.append_rows(requests=request_generator())
# Handle the response
for response in stream:
print(response)
# [END bigquerystorage_v1beta2_generated_BigQueryWrite_AppendRows_sync]
| for request in requests:
yield request | identifier_body |
bigquerystorage_v1beta2_generated_big_query_write_append_rows_sync.py | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# 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.
#
# Generated code. DO NOT EDIT!
#
# Snippet for AppendRows
# NOTE: This snippet has been automatically generated for illustrative purposes only.
# It may require modifications to work in your environment.
# To install the latest published package dependency, execute the following:
# python3 -m pip install google-cloud-bigquery-storage
# [START bigquerystorage_v1beta2_generated_BigQueryWrite_AppendRows_sync]
from google.cloud import bigquery_storage_v1beta2
def sample_append_rows():
# Create a client
client = bigquery_storage_v1beta2.BigQueryWriteClient()
# Initialize request argument(s)
request = bigquery_storage_v1beta2.AppendRowsRequest(
write_stream="write_stream_value",
)
# This method expects an iterator which contains | def request_generator():
for request in requests:
yield request
# Make the request
stream = client.append_rows(requests=request_generator())
# Handle the response
for response in stream:
print(response)
# [END bigquerystorage_v1beta2_generated_BigQueryWrite_AppendRows_sync] | # 'bigquery_storage_v1beta2.AppendRowsRequest' objects
# Here we create a generator that yields a single `request` for
# demonstrative purposes.
requests = [request]
| random_line_split |
process.ts | const width = 50;
const height = 6;
let initialState: string[][] = [];
for (let j = 0; j < height; ++j) {
initialState.push([]);
for (let i = 0; i < width; ++i) {
initialState[j].push(".");
}
}
const actions = [
{
pattern: /^rect (\d+)x(\d+)$/,
action: (state: string[][], columns: number, rows: number) => {
for (let j = 0; j < rows; ++j) {
for (let i = 0; i < columns; ++i) { | state[j][i] = "#";
}
}
return state;
}
},
{
pattern: /^rotate column x=(\d+) by (\d+)$/,
action: (state: string[][], column: number, offset: number) => {
const original: string[] = [];
for (let j = 0; j < height; ++j) {
original.push(state[j][column]);
}
for (let j = 0; j < height; ++j) {
state[j][column] = original[(j - offset + height) % height]
}
return state;
}
},
{
pattern: /^rotate row y=(\d+) by (\d+)$/,
action: (state: string[][], row: number, offset: number) => {
const original: string[] = [];
for (let i = 0; i < width; ++i) {
original.push(state[row][i]);
}
for (let i = 0; i < width; ++i) {
state[row][i] = original[(i - offset + width) % width]
}
return state;
}
}
];
export const process = (input: string) =>
input.split("\n").reduce((state, line) => {
for (let i = 0; i < actions.length; ++i) {
let match = line.match(actions[i].pattern);
if (match) {
return actions[i].action(state, +match[1], +match[2]);
}
}
}, initialState); | random_line_split | |
process.ts | const width = 50;
const height = 6;
let initialState: string[][] = [];
for (let j = 0; j < height; ++j) {
initialState.push([]);
for (let i = 0; i < width; ++i) |
}
const actions = [
{
pattern: /^rect (\d+)x(\d+)$/,
action: (state: string[][], columns: number, rows: number) => {
for (let j = 0; j < rows; ++j) {
for (let i = 0; i < columns; ++i) {
state[j][i] = "#";
}
}
return state;
}
},
{
pattern: /^rotate column x=(\d+) by (\d+)$/,
action: (state: string[][], column: number, offset: number) => {
const original: string[] = [];
for (let j = 0; j < height; ++j) {
original.push(state[j][column]);
}
for (let j = 0; j < height; ++j) {
state[j][column] = original[(j - offset + height) % height]
}
return state;
}
},
{
pattern: /^rotate row y=(\d+) by (\d+)$/,
action: (state: string[][], row: number, offset: number) => {
const original: string[] = [];
for (let i = 0; i < width; ++i) {
original.push(state[row][i]);
}
for (let i = 0; i < width; ++i) {
state[row][i] = original[(i - offset + width) % width]
}
return state;
}
}
];
export const process = (input: string) =>
input.split("\n").reduce((state, line) => {
for (let i = 0; i < actions.length; ++i) {
let match = line.match(actions[i].pattern);
if (match) {
return actions[i].action(state, +match[1], +match[2]);
}
}
}, initialState);
| {
initialState[j].push(".");
} | conditional_block |
TestTan.rs | /*
* Copyright (C) 2014 The Android Open Source Project
* | *
* 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.
*/
#pragma version(1)
#pragma rs java_package_name(android.renderscript.cts)
// Don't edit this file! It is auto-generated by frameworks/rs/api/gen_runtime.
float __attribute__((kernel)) testTanFloatFloat(float in) {
return tan(in);
}
float2 __attribute__((kernel)) testTanFloat2Float2(float2 in) {
return tan(in);
}
float3 __attribute__((kernel)) testTanFloat3Float3(float3 in) {
return tan(in);
}
float4 __attribute__((kernel)) testTanFloat4Float4(float4 in) {
return tan(in);
} | * 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 | random_line_split |
settings.py | """
Django settings for school project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)))
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, '../templates'),
)
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'koeorn$p_9&6!%1!84=erv*)#40-f$&z+_hq1^a1+2#93_ev%y'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
# 'django.contrib.admin',
# 'django.contrib.auth',
# 'django.contrib.contenttypes',
# 'django.contrib.sessions',
# 'django.contrib.messages',
# 'django.contrib.staticfiles',
)
| 'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'school.urls'
WSGI_APPLICATION = 'school.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
# }
# }
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'asia/chongqing'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/' | MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware', | random_line_split |
profile.rs | use std::cell::RefCell;
use std::env;
use std::fmt;
use std::io::{stdout, StdoutLock, Write};
use std::iter::repeat;
use std::mem;
use std::time;
thread_local!(static PROFILE_STACK: RefCell<Vec<time::Instant>> = RefCell::new(Vec::new()));
thread_local!(static MESSAGES: RefCell<Vec<Message>> = RefCell::new(Vec::new()));
type Message = (usize, u64, String);
pub struct Profiler {
desc: String,
}
fn enabled_level() -> Option<usize> {
env::var("CARGO_PROFILE").ok().and_then(|s| s.parse().ok())
}
pub fn start<T: fmt::Display>(desc: T) -> Profiler {
if enabled_level().is_none() {
return Profiler {
desc: String::new(),
};
}
PROFILE_STACK.with(|stack| stack.borrow_mut().push(time::Instant::now()));
Profiler {
desc: desc.to_string(),
}
}
impl Drop for Profiler {
fn drop(&mut self) {
let enabled = match enabled_level() {
Some(i) => i,
None => return,
};
let (start, stack_len) = PROFILE_STACK.with(|stack| {
let mut stack = stack.borrow_mut();
let start = stack.pop().unwrap();
(start, stack.len())
});
let duration = start.elapsed();
let duration_ms = duration.as_secs() * 1000 + u64::from(duration.subsec_millis());
let msg = (stack_len, duration_ms, mem::take(&mut self.desc));
MESSAGES.with(|msgs| msgs.borrow_mut().push(msg));
if stack_len == 0 {
fn print(lvl: usize, msgs: &[Message], enabled: usize, stdout: &mut StdoutLock<'_>) {
if lvl > enabled {
return;
}
let mut last = 0;
for (i, &(l, time, ref msg)) in msgs.iter().enumerate() {
if l != lvl {
continue;
}
writeln!(
stdout,
"{} {:6}ms - {}",
repeat(" ").take(lvl + 1).collect::<String>(),
time, | msg
)
.expect("printing profiling info to stdout");
print(lvl + 1, &msgs[last..i], enabled, stdout);
last = i;
}
}
let stdout = stdout();
MESSAGES.with(|msgs| {
let mut msgs = msgs.borrow_mut();
print(0, &msgs, enabled, &mut stdout.lock());
msgs.clear();
});
}
}
} | random_line_split | |
profile.rs | use std::cell::RefCell;
use std::env;
use std::fmt;
use std::io::{stdout, StdoutLock, Write};
use std::iter::repeat;
use std::mem;
use std::time;
thread_local!(static PROFILE_STACK: RefCell<Vec<time::Instant>> = RefCell::new(Vec::new()));
thread_local!(static MESSAGES: RefCell<Vec<Message>> = RefCell::new(Vec::new()));
type Message = (usize, u64, String);
pub struct Profiler {
desc: String,
}
fn enabled_level() -> Option<usize> {
env::var("CARGO_PROFILE").ok().and_then(|s| s.parse().ok())
}
pub fn start<T: fmt::Display>(desc: T) -> Profiler {
if enabled_level().is_none() {
return Profiler {
desc: String::new(),
};
}
PROFILE_STACK.with(|stack| stack.borrow_mut().push(time::Instant::now()));
Profiler {
desc: desc.to_string(),
}
}
impl Drop for Profiler {
fn | (&mut self) {
let enabled = match enabled_level() {
Some(i) => i,
None => return,
};
let (start, stack_len) = PROFILE_STACK.with(|stack| {
let mut stack = stack.borrow_mut();
let start = stack.pop().unwrap();
(start, stack.len())
});
let duration = start.elapsed();
let duration_ms = duration.as_secs() * 1000 + u64::from(duration.subsec_millis());
let msg = (stack_len, duration_ms, mem::take(&mut self.desc));
MESSAGES.with(|msgs| msgs.borrow_mut().push(msg));
if stack_len == 0 {
fn print(lvl: usize, msgs: &[Message], enabled: usize, stdout: &mut StdoutLock<'_>) {
if lvl > enabled {
return;
}
let mut last = 0;
for (i, &(l, time, ref msg)) in msgs.iter().enumerate() {
if l != lvl {
continue;
}
writeln!(
stdout,
"{} {:6}ms - {}",
repeat(" ").take(lvl + 1).collect::<String>(),
time,
msg
)
.expect("printing profiling info to stdout");
print(lvl + 1, &msgs[last..i], enabled, stdout);
last = i;
}
}
let stdout = stdout();
MESSAGES.with(|msgs| {
let mut msgs = msgs.borrow_mut();
print(0, &msgs, enabled, &mut stdout.lock());
msgs.clear();
});
}
}
}
| drop | identifier_name |
profile.rs | use std::cell::RefCell;
use std::env;
use std::fmt;
use std::io::{stdout, StdoutLock, Write};
use std::iter::repeat;
use std::mem;
use std::time;
thread_local!(static PROFILE_STACK: RefCell<Vec<time::Instant>> = RefCell::new(Vec::new()));
thread_local!(static MESSAGES: RefCell<Vec<Message>> = RefCell::new(Vec::new()));
type Message = (usize, u64, String);
pub struct Profiler {
desc: String,
}
fn enabled_level() -> Option<usize> {
env::var("CARGO_PROFILE").ok().and_then(|s| s.parse().ok())
}
pub fn start<T: fmt::Display>(desc: T) -> Profiler |
impl Drop for Profiler {
fn drop(&mut self) {
let enabled = match enabled_level() {
Some(i) => i,
None => return,
};
let (start, stack_len) = PROFILE_STACK.with(|stack| {
let mut stack = stack.borrow_mut();
let start = stack.pop().unwrap();
(start, stack.len())
});
let duration = start.elapsed();
let duration_ms = duration.as_secs() * 1000 + u64::from(duration.subsec_millis());
let msg = (stack_len, duration_ms, mem::take(&mut self.desc));
MESSAGES.with(|msgs| msgs.borrow_mut().push(msg));
if stack_len == 0 {
fn print(lvl: usize, msgs: &[Message], enabled: usize, stdout: &mut StdoutLock<'_>) {
if lvl > enabled {
return;
}
let mut last = 0;
for (i, &(l, time, ref msg)) in msgs.iter().enumerate() {
if l != lvl {
continue;
}
writeln!(
stdout,
"{} {:6}ms - {}",
repeat(" ").take(lvl + 1).collect::<String>(),
time,
msg
)
.expect("printing profiling info to stdout");
print(lvl + 1, &msgs[last..i], enabled, stdout);
last = i;
}
}
let stdout = stdout();
MESSAGES.with(|msgs| {
let mut msgs = msgs.borrow_mut();
print(0, &msgs, enabled, &mut stdout.lock());
msgs.clear();
});
}
}
}
| {
if enabled_level().is_none() {
return Profiler {
desc: String::new(),
};
}
PROFILE_STACK.with(|stack| stack.borrow_mut().push(time::Instant::now()));
Profiler {
desc: desc.to_string(),
}
} | identifier_body |
profile.rs | use std::cell::RefCell;
use std::env;
use std::fmt;
use std::io::{stdout, StdoutLock, Write};
use std::iter::repeat;
use std::mem;
use std::time;
thread_local!(static PROFILE_STACK: RefCell<Vec<time::Instant>> = RefCell::new(Vec::new()));
thread_local!(static MESSAGES: RefCell<Vec<Message>> = RefCell::new(Vec::new()));
type Message = (usize, u64, String);
pub struct Profiler {
desc: String,
}
fn enabled_level() -> Option<usize> {
env::var("CARGO_PROFILE").ok().and_then(|s| s.parse().ok())
}
pub fn start<T: fmt::Display>(desc: T) -> Profiler {
if enabled_level().is_none() |
PROFILE_STACK.with(|stack| stack.borrow_mut().push(time::Instant::now()));
Profiler {
desc: desc.to_string(),
}
}
impl Drop for Profiler {
fn drop(&mut self) {
let enabled = match enabled_level() {
Some(i) => i,
None => return,
};
let (start, stack_len) = PROFILE_STACK.with(|stack| {
let mut stack = stack.borrow_mut();
let start = stack.pop().unwrap();
(start, stack.len())
});
let duration = start.elapsed();
let duration_ms = duration.as_secs() * 1000 + u64::from(duration.subsec_millis());
let msg = (stack_len, duration_ms, mem::take(&mut self.desc));
MESSAGES.with(|msgs| msgs.borrow_mut().push(msg));
if stack_len == 0 {
fn print(lvl: usize, msgs: &[Message], enabled: usize, stdout: &mut StdoutLock<'_>) {
if lvl > enabled {
return;
}
let mut last = 0;
for (i, &(l, time, ref msg)) in msgs.iter().enumerate() {
if l != lvl {
continue;
}
writeln!(
stdout,
"{} {:6}ms - {}",
repeat(" ").take(lvl + 1).collect::<String>(),
time,
msg
)
.expect("printing profiling info to stdout");
print(lvl + 1, &msgs[last..i], enabled, stdout);
last = i;
}
}
let stdout = stdout();
MESSAGES.with(|msgs| {
let mut msgs = msgs.borrow_mut();
print(0, &msgs, enabled, &mut stdout.lock());
msgs.clear();
});
}
}
}
| {
return Profiler {
desc: String::new(),
};
} | conditional_block |
line_path.rs | use crate::LinePathCommand;
use geometry::{Point, Transform, Transformation};
use internal_iter::{
ExtendFromInternalIterator, FromInternalIterator, InternalIterator, IntoInternalIterator,
};
use std::iter::Cloned;
use std::slice::Iter;
/// A sequence of commands that defines a set of contours, each of which consists of a sequence of
/// line segments. Each contour is either open or closed.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct LinePath {
verbs: Vec<Verb>,
points: Vec<Point>,
}
impl LinePath {
/// Creates a new empty line path.
pub fn new() -> LinePath {
LinePath::default()
}
/// Returns a slice of the points that make up `self`.
pub fn points(&self) -> &[Point] {
&self.points
}
/// Returns an iterator over the commands that make up `self`.
pub fn commands(&self) -> Commands {
Commands {
verbs: self.verbs.iter().cloned(),
points: self.points.iter().cloned(),
}
}
/// Returns a mutable slice of the points that make up `self`.
pub fn points_mut(&mut self) -> &mut [Point] {
&mut self.points
}
/// Adds a new contour, starting at the given point.
pub fn move_to(&mut self, p: Point) {
self.verbs.push(Verb::MoveTo);
self.points.push(p);
}
/// Adds a line segment to the current contour, starting at the current point.
pub fn line_to(&mut self, p: Point) {
self.verbs.push(Verb::LineTo);
self.points.push(p);
}
/// Closes the current contour.
pub fn close(&mut self) {
self.verbs.push(Verb::Close);
}
/// Clears `self`.
pub fn clear(&mut self) {
self.verbs.clear();
self.points.clear();
}
}
impl ExtendFromInternalIterator<LinePathCommand> for LinePath {
fn extend_from_internal_iter<I>(&mut self, internal_iter: I)
where
I: IntoInternalIterator<Item = LinePathCommand>,
{
internal_iter.into_internal_iter().for_each(&mut |command| {
match command {
LinePathCommand::MoveTo(p) => self.move_to(p),
LinePathCommand::LineTo(p) => self.line_to(p),
LinePathCommand::Close => self.close(),
}
true
});
}
}
impl FromInternalIterator<LinePathCommand> for LinePath {
fn from_internal_iter<I>(internal_iter: I) -> Self
where
I: IntoInternalIterator<Item = LinePathCommand>,
{
let mut path = LinePath::new();
path.extend_from_internal_iter(internal_iter);
path
}
}
impl Transform for LinePath {
fn transform<T>(mut self, t: &T) -> LinePath
where
T: Transformation,
{
self.transform_mut(t);
self
}
fn transform_mut<T>(&mut self, t: &T)
where
T: Transformation, | }
/// An iterator over the commands that make up a line path.
#[derive(Clone, Debug)]
pub struct Commands<'a> {
verbs: Cloned<Iter<'a, Verb>>,
points: Cloned<Iter<'a, Point>>,
}
impl<'a> Iterator for Commands<'a> {
type Item = LinePathCommand;
fn next(&mut self) -> Option<LinePathCommand> {
self.verbs.next().map(|verb| match verb {
Verb::MoveTo => LinePathCommand::MoveTo(self.points.next().unwrap()),
Verb::LineTo => LinePathCommand::LineTo(self.points.next().unwrap()),
Verb::Close => LinePathCommand::Close,
})
}
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
enum Verb {
MoveTo,
LineTo,
Close,
} | {
for point in self.points_mut() {
point.transform_mut(t);
}
} | random_line_split |
line_path.rs | use crate::LinePathCommand;
use geometry::{Point, Transform, Transformation};
use internal_iter::{
ExtendFromInternalIterator, FromInternalIterator, InternalIterator, IntoInternalIterator,
};
use std::iter::Cloned;
use std::slice::Iter;
/// A sequence of commands that defines a set of contours, each of which consists of a sequence of
/// line segments. Each contour is either open or closed.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct LinePath {
verbs: Vec<Verb>,
points: Vec<Point>,
}
impl LinePath {
/// Creates a new empty line path.
pub fn new() -> LinePath {
LinePath::default()
}
/// Returns a slice of the points that make up `self`.
pub fn points(&self) -> &[Point] {
&self.points
}
/// Returns an iterator over the commands that make up `self`.
pub fn commands(&self) -> Commands {
Commands {
verbs: self.verbs.iter().cloned(),
points: self.points.iter().cloned(),
}
}
/// Returns a mutable slice of the points that make up `self`.
pub fn points_mut(&mut self) -> &mut [Point] {
&mut self.points
}
/// Adds a new contour, starting at the given point.
pub fn move_to(&mut self, p: Point) {
self.verbs.push(Verb::MoveTo);
self.points.push(p);
}
/// Adds a line segment to the current contour, starting at the current point.
pub fn line_to(&mut self, p: Point) {
self.verbs.push(Verb::LineTo);
self.points.push(p);
}
/// Closes the current contour.
pub fn close(&mut self) {
self.verbs.push(Verb::Close);
}
/// Clears `self`.
pub fn clear(&mut self) {
self.verbs.clear();
self.points.clear();
}
}
impl ExtendFromInternalIterator<LinePathCommand> for LinePath {
fn extend_from_internal_iter<I>(&mut self, internal_iter: I)
where
I: IntoInternalIterator<Item = LinePathCommand>,
{
internal_iter.into_internal_iter().for_each(&mut |command| {
match command {
LinePathCommand::MoveTo(p) => self.move_to(p),
LinePathCommand::LineTo(p) => self.line_to(p),
LinePathCommand::Close => self.close(),
}
true
});
}
}
impl FromInternalIterator<LinePathCommand> for LinePath {
fn from_internal_iter<I>(internal_iter: I) -> Self
where
I: IntoInternalIterator<Item = LinePathCommand>,
|
}
impl Transform for LinePath {
fn transform<T>(mut self, t: &T) -> LinePath
where
T: Transformation,
{
self.transform_mut(t);
self
}
fn transform_mut<T>(&mut self, t: &T)
where
T: Transformation,
{
for point in self.points_mut() {
point.transform_mut(t);
}
}
}
/// An iterator over the commands that make up a line path.
#[derive(Clone, Debug)]
pub struct Commands<'a> {
verbs: Cloned<Iter<'a, Verb>>,
points: Cloned<Iter<'a, Point>>,
}
impl<'a> Iterator for Commands<'a> {
type Item = LinePathCommand;
fn next(&mut self) -> Option<LinePathCommand> {
self.verbs.next().map(|verb| match verb {
Verb::MoveTo => LinePathCommand::MoveTo(self.points.next().unwrap()),
Verb::LineTo => LinePathCommand::LineTo(self.points.next().unwrap()),
Verb::Close => LinePathCommand::Close,
})
}
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
enum Verb {
MoveTo,
LineTo,
Close,
}
| {
let mut path = LinePath::new();
path.extend_from_internal_iter(internal_iter);
path
} | identifier_body |
line_path.rs | use crate::LinePathCommand;
use geometry::{Point, Transform, Transformation};
use internal_iter::{
ExtendFromInternalIterator, FromInternalIterator, InternalIterator, IntoInternalIterator,
};
use std::iter::Cloned;
use std::slice::Iter;
/// A sequence of commands that defines a set of contours, each of which consists of a sequence of
/// line segments. Each contour is either open or closed.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct LinePath {
verbs: Vec<Verb>,
points: Vec<Point>,
}
impl LinePath {
/// Creates a new empty line path.
pub fn new() -> LinePath {
LinePath::default()
}
/// Returns a slice of the points that make up `self`.
pub fn points(&self) -> &[Point] {
&self.points
}
/// Returns an iterator over the commands that make up `self`.
pub fn commands(&self) -> Commands {
Commands {
verbs: self.verbs.iter().cloned(),
points: self.points.iter().cloned(),
}
}
/// Returns a mutable slice of the points that make up `self`.
pub fn | (&mut self) -> &mut [Point] {
&mut self.points
}
/// Adds a new contour, starting at the given point.
pub fn move_to(&mut self, p: Point) {
self.verbs.push(Verb::MoveTo);
self.points.push(p);
}
/// Adds a line segment to the current contour, starting at the current point.
pub fn line_to(&mut self, p: Point) {
self.verbs.push(Verb::LineTo);
self.points.push(p);
}
/// Closes the current contour.
pub fn close(&mut self) {
self.verbs.push(Verb::Close);
}
/// Clears `self`.
pub fn clear(&mut self) {
self.verbs.clear();
self.points.clear();
}
}
impl ExtendFromInternalIterator<LinePathCommand> for LinePath {
fn extend_from_internal_iter<I>(&mut self, internal_iter: I)
where
I: IntoInternalIterator<Item = LinePathCommand>,
{
internal_iter.into_internal_iter().for_each(&mut |command| {
match command {
LinePathCommand::MoveTo(p) => self.move_to(p),
LinePathCommand::LineTo(p) => self.line_to(p),
LinePathCommand::Close => self.close(),
}
true
});
}
}
impl FromInternalIterator<LinePathCommand> for LinePath {
fn from_internal_iter<I>(internal_iter: I) -> Self
where
I: IntoInternalIterator<Item = LinePathCommand>,
{
let mut path = LinePath::new();
path.extend_from_internal_iter(internal_iter);
path
}
}
impl Transform for LinePath {
fn transform<T>(mut self, t: &T) -> LinePath
where
T: Transformation,
{
self.transform_mut(t);
self
}
fn transform_mut<T>(&mut self, t: &T)
where
T: Transformation,
{
for point in self.points_mut() {
point.transform_mut(t);
}
}
}
/// An iterator over the commands that make up a line path.
#[derive(Clone, Debug)]
pub struct Commands<'a> {
verbs: Cloned<Iter<'a, Verb>>,
points: Cloned<Iter<'a, Point>>,
}
impl<'a> Iterator for Commands<'a> {
type Item = LinePathCommand;
fn next(&mut self) -> Option<LinePathCommand> {
self.verbs.next().map(|verb| match verb {
Verb::MoveTo => LinePathCommand::MoveTo(self.points.next().unwrap()),
Verb::LineTo => LinePathCommand::LineTo(self.points.next().unwrap()),
Verb::Close => LinePathCommand::Close,
})
}
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
enum Verb {
MoveTo,
LineTo,
Close,
}
| points_mut | identifier_name |
squinney.js | Items = new Meteor.Collection('items');
Router.map(function () {
this.route('home', {
path: '/'
});
this.route('items', {
controller: 'ItemsController',
action: 'customAction'
});
});
if (Meteor.isServer) {
var seed = function () {
Items.remove({});
for (var i = 0; i < 100; i++) {
Items.insert({body: 'Item ' + i});
}
};
Meteor.startup(seed);
var Future = Npm.require('fibers/future');
Meteor.publish('items', function () {
var future = new Future;
// simulate high latency publish function
Meteor.setTimeout(function () {
future.return(Items.find());
}, 2000);
return future.wait();
});
}
if (Meteor.isClient) | {
Router.configure({
layout: 'layout',
notFoundTemplate: 'notFound',
loadingTemplate: 'loading'
});
Subscriptions = {
items: Meteor.subscribe('items')
};
ItemsController = RouteController.extend({
template: 'items',
/*
* During rendering, wait on the items subscription and show the loading
* template while the subscription is not ready. This can also be a function
* that returns on subscription handle or an array of subscription handles.
*/
waitOn: Subscriptions['items'],
/*
* The data function will be called after the subscrition is ready, at
* render time.
*/
data: function () {
// we can return anything here, but since I don't want to use 'this' in
// as the each parameter, I'm just returning an object here with a named
// property.
return {
items: Items.find()
};
},
/*
* By default the router will call the *run* method which will render the
* controller's template (or the template with the same name as the route)
* to the main yield area {{yield}}. But you can provide your own action
* methods as well.
*/
customAction: function () {
/* render customController into the main yield */
this.render('items');
/*
* You can call render multiple times. You can even pass an object of
* template names (keys) to render options (values). Typically, the
* options object would include a *to* property specifiying the named
* yield to render to.
*
*/
this.render({
itemsAside: { to: 'aside', waitOn: false, data: false },
itemsFooter: { to: 'footer', waitOn: false, data: false }
});
}
});
} | conditional_block | |
squinney.js | Items = new Meteor.Collection('items');
Router.map(function () {
this.route('home', {
path: '/'
});
this.route('items', {
controller: 'ItemsController',
action: 'customAction'
});
});
if (Meteor.isServer) {
var seed = function () {
Items.remove({});
for (var i = 0; i < 100; i++) {
Items.insert({body: 'Item ' + i});
}
};
Meteor.startup(seed);
var Future = Npm.require('fibers/future');
Meteor.publish('items', function () {
var future = new Future;
// simulate high latency publish function
Meteor.setTimeout(function () {
future.return(Items.find());
}, 2000);
return future.wait();
});
}
if (Meteor.isClient) {
Router.configure({
layout: 'layout',
notFoundTemplate: 'notFound',
loadingTemplate: 'loading'
});
Subscriptions = {
items: Meteor.subscribe('items')
};
ItemsController = RouteController.extend({
template: 'items',
/*
* During rendering, wait on the items subscription and show the loading
* template while the subscription is not ready. This can also be a function
* that returns on subscription handle or an array of subscription handles.
*/
waitOn: Subscriptions['items'],
/*
* The data function will be called after the subscrition is ready, at
* render time.
*/
data: function () {
// we can return anything here, but since I don't want to use 'this' in | },
/*
* By default the router will call the *run* method which will render the
* controller's template (or the template with the same name as the route)
* to the main yield area {{yield}}. But you can provide your own action
* methods as well.
*/
customAction: function () {
/* render customController into the main yield */
this.render('items');
/*
* You can call render multiple times. You can even pass an object of
* template names (keys) to render options (values). Typically, the
* options object would include a *to* property specifiying the named
* yield to render to.
*
*/
this.render({
itemsAside: { to: 'aside', waitOn: false, data: false },
itemsFooter: { to: 'footer', waitOn: false, data: false }
});
}
});
} | // as the each parameter, I'm just returning an object here with a named
// property.
return {
items: Items.find()
}; | random_line_split |
mock-project.js | 'use strict';
var Project = require('ember-cli/lib/models/project');
function MockProject() {
var root = process.cwd();
var pkg = {};
Project.apply(this, [root, pkg]);
}
MockProject.prototype.require = function(file) {
if (file === './server') {
return function() {
return {
listen: function() { arguments[arguments.length-1](); }
};
};
}
};
MockProject.prototype.config = function() {
return this._config || {
baseURL: '/',
locationType: 'auto'
};
};
MockProject.prototype.has = function(key) { |
MockProject.prototype.name = function() {
return 'mock-project';
};
MockProject.prototype.initializeAddons = Project.prototype.initializeAddons;
MockProject.prototype.buildAddonPackages = Project.prototype.buildAddonPackages;
MockProject.prototype.discoverAddons = Project.prototype.discoverAddons;
MockProject.prototype.addIfAddon = Project.prototype.addIfAddon;
MockProject.prototype.setupBowerDirectory = Project.prototype.setupBowerDirectory;
MockProject.prototype.dependencies = function() {
return [];
};
MockProject.prototype.isEmberCLIAddon = function() {
return false;
};
module.exports = MockProject; | return (/server/.test(key));
}; | random_line_split |
mock-project.js | 'use strict';
var Project = require('ember-cli/lib/models/project');
function | () {
var root = process.cwd();
var pkg = {};
Project.apply(this, [root, pkg]);
}
MockProject.prototype.require = function(file) {
if (file === './server') {
return function() {
return {
listen: function() { arguments[arguments.length-1](); }
};
};
}
};
MockProject.prototype.config = function() {
return this._config || {
baseURL: '/',
locationType: 'auto'
};
};
MockProject.prototype.has = function(key) {
return (/server/.test(key));
};
MockProject.prototype.name = function() {
return 'mock-project';
};
MockProject.prototype.initializeAddons = Project.prototype.initializeAddons;
MockProject.prototype.buildAddonPackages = Project.prototype.buildAddonPackages;
MockProject.prototype.discoverAddons = Project.prototype.discoverAddons;
MockProject.prototype.addIfAddon = Project.prototype.addIfAddon;
MockProject.prototype.setupBowerDirectory = Project.prototype.setupBowerDirectory;
MockProject.prototype.dependencies = function() {
return [];
};
MockProject.prototype.isEmberCLIAddon = function() {
return false;
};
module.exports = MockProject;
| MockProject | identifier_name |
mock-project.js | 'use strict';
var Project = require('ember-cli/lib/models/project');
function MockProject() {
var root = process.cwd();
var pkg = {};
Project.apply(this, [root, pkg]);
}
MockProject.prototype.require = function(file) {
if (file === './server') |
};
MockProject.prototype.config = function() {
return this._config || {
baseURL: '/',
locationType: 'auto'
};
};
MockProject.prototype.has = function(key) {
return (/server/.test(key));
};
MockProject.prototype.name = function() {
return 'mock-project';
};
MockProject.prototype.initializeAddons = Project.prototype.initializeAddons;
MockProject.prototype.buildAddonPackages = Project.prototype.buildAddonPackages;
MockProject.prototype.discoverAddons = Project.prototype.discoverAddons;
MockProject.prototype.addIfAddon = Project.prototype.addIfAddon;
MockProject.prototype.setupBowerDirectory = Project.prototype.setupBowerDirectory;
MockProject.prototype.dependencies = function() {
return [];
};
MockProject.prototype.isEmberCLIAddon = function() {
return false;
};
module.exports = MockProject;
| {
return function() {
return {
listen: function() { arguments[arguments.length-1](); }
};
};
} | conditional_block |
mock-project.js | 'use strict';
var Project = require('ember-cli/lib/models/project');
function MockProject() |
MockProject.prototype.require = function(file) {
if (file === './server') {
return function() {
return {
listen: function() { arguments[arguments.length-1](); }
};
};
}
};
MockProject.prototype.config = function() {
return this._config || {
baseURL: '/',
locationType: 'auto'
};
};
MockProject.prototype.has = function(key) {
return (/server/.test(key));
};
MockProject.prototype.name = function() {
return 'mock-project';
};
MockProject.prototype.initializeAddons = Project.prototype.initializeAddons;
MockProject.prototype.buildAddonPackages = Project.prototype.buildAddonPackages;
MockProject.prototype.discoverAddons = Project.prototype.discoverAddons;
MockProject.prototype.addIfAddon = Project.prototype.addIfAddon;
MockProject.prototype.setupBowerDirectory = Project.prototype.setupBowerDirectory;
MockProject.prototype.dependencies = function() {
return [];
};
MockProject.prototype.isEmberCLIAddon = function() {
return false;
};
module.exports = MockProject;
| {
var root = process.cwd();
var pkg = {};
Project.apply(this, [root, pkg]);
} | identifier_body |
raw.rs | // Copyright 2015 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 |
//! iOS-specific raw type definitions
use os::raw::c_long;
use os::unix::raw::{uid_t, gid_t};
pub type blkcnt_t = i64;
pub type blksize_t = i32;
pub type dev_t = i32;
pub type ino_t = u64;
pub type mode_t = u16;
pub type nlink_t = u16;
pub type off_t = i64;
pub type time_t = c_long;
#[repr(C)]
pub struct stat {
pub st_dev: dev_t,
pub st_mode: mode_t,
pub st_nlink: nlink_t,
pub st_ino: ino_t,
pub st_uid: uid_t,
pub st_gid: gid_t,
pub st_rdev: dev_t,
pub st_atime: time_t,
pub st_atime_nsec: c_long,
pub st_mtime: time_t,
pub st_mtime_nsec: c_long,
pub st_ctime: time_t,
pub st_ctime_nsec: c_long,
pub st_birthtime: time_t,
pub st_birthtime_nsec: c_long,
pub st_size: off_t,
pub st_blocks: blkcnt_t,
pub st_blksize: blksize_t,
pub st_flags: u32,
pub st_gen: u32,
pub st_lspare: i32,
pub st_qspare: [i64; 2],
} | // <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. | random_line_split |
raw.rs | // Copyright 2015 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.
//! iOS-specific raw type definitions
use os::raw::c_long;
use os::unix::raw::{uid_t, gid_t};
pub type blkcnt_t = i64;
pub type blksize_t = i32;
pub type dev_t = i32;
pub type ino_t = u64;
pub type mode_t = u16;
pub type nlink_t = u16;
pub type off_t = i64;
pub type time_t = c_long;
#[repr(C)]
pub struct | {
pub st_dev: dev_t,
pub st_mode: mode_t,
pub st_nlink: nlink_t,
pub st_ino: ino_t,
pub st_uid: uid_t,
pub st_gid: gid_t,
pub st_rdev: dev_t,
pub st_atime: time_t,
pub st_atime_nsec: c_long,
pub st_mtime: time_t,
pub st_mtime_nsec: c_long,
pub st_ctime: time_t,
pub st_ctime_nsec: c_long,
pub st_birthtime: time_t,
pub st_birthtime_nsec: c_long,
pub st_size: off_t,
pub st_blocks: blkcnt_t,
pub st_blksize: blksize_t,
pub st_flags: u32,
pub st_gen: u32,
pub st_lspare: i32,
pub st_qspare: [i64; 2],
}
| stat | identifier_name |
config.py | # Copyright (C) 2006-2007 Robey Pointer <robeypointer@gmail.com>
#
# This file is part of paramiko.
#
# Paramiko is free software; you can redistribute it and/or modify it under the
# terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 2.1 of the License, or (at your option)
# any later version.
#
# Paramiko is distrubuted 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 Paramiko; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
"""
L{SSHConfig}.
"""
import fnmatch
import os
import re
import socket
SSH_PORT=22
proxy_re = re.compile(r"^(proxycommand)\s*=*\s*(.*)", re.I)
class SSHConfig (object):
"""
Representation of config information as stored in the format used by
OpenSSH. Queries can be made via L{lookup}. The format is described in
OpenSSH's C{ssh_config} man page. This class is provided primarily as a
convenience to posix users (since the OpenSSH format is a de-facto
standard on posix) but should work fine on Windows too.
@since: 1.6
"""
def __init__(self):
"""
Create a new OpenSSH config object.
"""
self._config = [ { 'host': '*' } ]
def parse(self, file_obj):
"""
Read an OpenSSH config from the given file object.
@param file_obj: a file-like object to read the config file from
@type file_obj: file
"""
configs = [self._config[0]]
for line in file_obj:
line = line.rstrip('\n').lstrip()
if (line == '') or (line[0] == '#'):
continue
if '=' in line:
# Ensure ProxyCommand gets properly split
if line.lower().strip().startswith('proxycommand'):
|
else:
key, value = line.split('=', 1)
key = key.strip().lower()
else:
# find first whitespace, and split there
i = 0
while (i < len(line)) and not line[i].isspace():
i += 1
if i == len(line):
raise Exception('Unparsable line: %r' % line)
key = line[:i].lower()
value = line[i:].lstrip()
if key == 'host':
del configs[:]
# the value may be multiple hosts, space-delimited
for host in value.split():
# do we have a pre-existing host config to append to?
matches = [c for c in self._config if c['host'] == host]
if len(matches) > 0:
configs.append(matches[0])
else:
config = { 'host': host }
self._config.append(config)
configs.append(config)
else:
for config in configs:
config[key] = value
def lookup(self, hostname):
"""
Return a dict of config options for a given hostname.
The host-matching rules of OpenSSH's C{ssh_config} man page are used,
which means that all configuration options from matching host
specifications are merged, with more specific hostmasks taking
precedence. In other words, if C{"Port"} is set under C{"Host *"}
and also C{"Host *.example.com"}, and the lookup is for
C{"ssh.example.com"}, then the port entry for C{"Host *.example.com"}
will win out.
The keys in the returned dict are all normalized to lowercase (look for
C{"port"}, not C{"Port"}. No other processing is done to the keys or
values.
@param hostname: the hostname to lookup
@type hostname: str
"""
matches = [x for x in self._config if fnmatch.fnmatch(hostname, x['host'])]
# Move * to the end
_star = matches.pop(0)
matches.append(_star)
ret = {}
for m in matches:
for k,v in m.iteritems():
if not k in ret:
ret[k] = v
ret = self._expand_variables(ret, hostname)
del ret['host']
return ret
def _expand_variables(self, config, hostname ):
"""
Return a dict of config options with expanded substitutions
for a given hostname.
Please refer to man ssh_config(5) for the parameters that
are replaced.
@param config: the config for the hostname
@type hostname: dict
@param hostname: the hostname that the config belongs to
@type hostname: str
"""
if 'hostname' in config:
config['hostname'] = config['hostname'].replace('%h',hostname)
else:
config['hostname'] = hostname
if 'port' in config:
port = config['port']
else:
port = SSH_PORT
user = os.getenv('USER')
if 'user' in config:
remoteuser = config['user']
else:
remoteuser = user
host = socket.gethostname().split('.')[0]
fqdn = socket.getfqdn()
homedir = os.path.expanduser('~')
replacements = {
'controlpath': [
('%h', config['hostname']),
('%l', fqdn),
('%L', host),
('%n', hostname),
('%p', port),
('%r', remoteuser),
('%u', user)
],
'identityfile': [
('~', homedir),
('%d', homedir),
('%h', config['hostname']),
('%l', fqdn),
('%u', user),
('%r', remoteuser)
],
'proxycommand': [
('%h', config['hostname']),
('%p', port),
('%r', remoteuser),
],
}
for k in config:
if k in replacements:
for find, replace in replacements[k]:
config[k] = config[k].replace(find, str(replace))
return config
| match = proxy_re.match(line)
key, value = match.group(1).lower(), match.group(2) | conditional_block |
config.py | # Copyright (C) 2006-2007 Robey Pointer <robeypointer@gmail.com>
#
# This file is part of paramiko.
#
# Paramiko is free software; you can redistribute it and/or modify it under the
# terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 2.1 of the License, or (at your option)
# any later version.
#
# Paramiko is distrubuted 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 Paramiko; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
"""
L{SSHConfig}.
"""
import fnmatch
import os
import re
import socket
SSH_PORT=22
proxy_re = re.compile(r"^(proxycommand)\s*=*\s*(.*)", re.I)
class SSHConfig (object):
| """
Representation of config information as stored in the format used by
OpenSSH. Queries can be made via L{lookup}. The format is described in
OpenSSH's C{ssh_config} man page. This class is provided primarily as a
convenience to posix users (since the OpenSSH format is a de-facto
standard on posix) but should work fine on Windows too.
@since: 1.6
"""
def __init__(self):
"""
Create a new OpenSSH config object.
"""
self._config = [ { 'host': '*' } ]
def parse(self, file_obj):
"""
Read an OpenSSH config from the given file object.
@param file_obj: a file-like object to read the config file from
@type file_obj: file
"""
configs = [self._config[0]]
for line in file_obj:
line = line.rstrip('\n').lstrip()
if (line == '') or (line[0] == '#'):
continue
if '=' in line:
# Ensure ProxyCommand gets properly split
if line.lower().strip().startswith('proxycommand'):
match = proxy_re.match(line)
key, value = match.group(1).lower(), match.group(2)
else:
key, value = line.split('=', 1)
key = key.strip().lower()
else:
# find first whitespace, and split there
i = 0
while (i < len(line)) and not line[i].isspace():
i += 1
if i == len(line):
raise Exception('Unparsable line: %r' % line)
key = line[:i].lower()
value = line[i:].lstrip()
if key == 'host':
del configs[:]
# the value may be multiple hosts, space-delimited
for host in value.split():
# do we have a pre-existing host config to append to?
matches = [c for c in self._config if c['host'] == host]
if len(matches) > 0:
configs.append(matches[0])
else:
config = { 'host': host }
self._config.append(config)
configs.append(config)
else:
for config in configs:
config[key] = value
def lookup(self, hostname):
"""
Return a dict of config options for a given hostname.
The host-matching rules of OpenSSH's C{ssh_config} man page are used,
which means that all configuration options from matching host
specifications are merged, with more specific hostmasks taking
precedence. In other words, if C{"Port"} is set under C{"Host *"}
and also C{"Host *.example.com"}, and the lookup is for
C{"ssh.example.com"}, then the port entry for C{"Host *.example.com"}
will win out.
The keys in the returned dict are all normalized to lowercase (look for
C{"port"}, not C{"Port"}. No other processing is done to the keys or
values.
@param hostname: the hostname to lookup
@type hostname: str
"""
matches = [x for x in self._config if fnmatch.fnmatch(hostname, x['host'])]
# Move * to the end
_star = matches.pop(0)
matches.append(_star)
ret = {}
for m in matches:
for k,v in m.iteritems():
if not k in ret:
ret[k] = v
ret = self._expand_variables(ret, hostname)
del ret['host']
return ret
def _expand_variables(self, config, hostname ):
"""
Return a dict of config options with expanded substitutions
for a given hostname.
Please refer to man ssh_config(5) for the parameters that
are replaced.
@param config: the config for the hostname
@type hostname: dict
@param hostname: the hostname that the config belongs to
@type hostname: str
"""
if 'hostname' in config:
config['hostname'] = config['hostname'].replace('%h',hostname)
else:
config['hostname'] = hostname
if 'port' in config:
port = config['port']
else:
port = SSH_PORT
user = os.getenv('USER')
if 'user' in config:
remoteuser = config['user']
else:
remoteuser = user
host = socket.gethostname().split('.')[0]
fqdn = socket.getfqdn()
homedir = os.path.expanduser('~')
replacements = {
'controlpath': [
('%h', config['hostname']),
('%l', fqdn),
('%L', host),
('%n', hostname),
('%p', port),
('%r', remoteuser),
('%u', user)
],
'identityfile': [
('~', homedir),
('%d', homedir),
('%h', config['hostname']),
('%l', fqdn),
('%u', user),
('%r', remoteuser)
],
'proxycommand': [
('%h', config['hostname']),
('%p', port),
('%r', remoteuser),
],
}
for k in config:
if k in replacements:
for find, replace in replacements[k]:
config[k] = config[k].replace(find, str(replace))
return config | identifier_body | |
config.py | # Copyright (C) 2006-2007 Robey Pointer <robeypointer@gmail.com>
#
# This file is part of paramiko.
#
# Paramiko is free software; you can redistribute it and/or modify it under the
# terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 2.1 of the License, or (at your option)
# any later version.
#
# Paramiko is distrubuted 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 Paramiko; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
"""
L{SSHConfig}.
"""
import fnmatch
import os
import re
import socket
SSH_PORT=22
proxy_re = re.compile(r"^(proxycommand)\s*=*\s*(.*)", re.I)
class SSHConfig (object):
"""
Representation of config information as stored in the format used by
OpenSSH. Queries can be made via L{lookup}. The format is described in | OpenSSH's C{ssh_config} man page. This class is provided primarily as a
convenience to posix users (since the OpenSSH format is a de-facto
standard on posix) but should work fine on Windows too.
@since: 1.6
"""
def __init__(self):
"""
Create a new OpenSSH config object.
"""
self._config = [ { 'host': '*' } ]
def parse(self, file_obj):
"""
Read an OpenSSH config from the given file object.
@param file_obj: a file-like object to read the config file from
@type file_obj: file
"""
configs = [self._config[0]]
for line in file_obj:
line = line.rstrip('\n').lstrip()
if (line == '') or (line[0] == '#'):
continue
if '=' in line:
# Ensure ProxyCommand gets properly split
if line.lower().strip().startswith('proxycommand'):
match = proxy_re.match(line)
key, value = match.group(1).lower(), match.group(2)
else:
key, value = line.split('=', 1)
key = key.strip().lower()
else:
# find first whitespace, and split there
i = 0
while (i < len(line)) and not line[i].isspace():
i += 1
if i == len(line):
raise Exception('Unparsable line: %r' % line)
key = line[:i].lower()
value = line[i:].lstrip()
if key == 'host':
del configs[:]
# the value may be multiple hosts, space-delimited
for host in value.split():
# do we have a pre-existing host config to append to?
matches = [c for c in self._config if c['host'] == host]
if len(matches) > 0:
configs.append(matches[0])
else:
config = { 'host': host }
self._config.append(config)
configs.append(config)
else:
for config in configs:
config[key] = value
def lookup(self, hostname):
"""
Return a dict of config options for a given hostname.
The host-matching rules of OpenSSH's C{ssh_config} man page are used,
which means that all configuration options from matching host
specifications are merged, with more specific hostmasks taking
precedence. In other words, if C{"Port"} is set under C{"Host *"}
and also C{"Host *.example.com"}, and the lookup is for
C{"ssh.example.com"}, then the port entry for C{"Host *.example.com"}
will win out.
The keys in the returned dict are all normalized to lowercase (look for
C{"port"}, not C{"Port"}. No other processing is done to the keys or
values.
@param hostname: the hostname to lookup
@type hostname: str
"""
matches = [x for x in self._config if fnmatch.fnmatch(hostname, x['host'])]
# Move * to the end
_star = matches.pop(0)
matches.append(_star)
ret = {}
for m in matches:
for k,v in m.iteritems():
if not k in ret:
ret[k] = v
ret = self._expand_variables(ret, hostname)
del ret['host']
return ret
def _expand_variables(self, config, hostname ):
"""
Return a dict of config options with expanded substitutions
for a given hostname.
Please refer to man ssh_config(5) for the parameters that
are replaced.
@param config: the config for the hostname
@type hostname: dict
@param hostname: the hostname that the config belongs to
@type hostname: str
"""
if 'hostname' in config:
config['hostname'] = config['hostname'].replace('%h',hostname)
else:
config['hostname'] = hostname
if 'port' in config:
port = config['port']
else:
port = SSH_PORT
user = os.getenv('USER')
if 'user' in config:
remoteuser = config['user']
else:
remoteuser = user
host = socket.gethostname().split('.')[0]
fqdn = socket.getfqdn()
homedir = os.path.expanduser('~')
replacements = {
'controlpath': [
('%h', config['hostname']),
('%l', fqdn),
('%L', host),
('%n', hostname),
('%p', port),
('%r', remoteuser),
('%u', user)
],
'identityfile': [
('~', homedir),
('%d', homedir),
('%h', config['hostname']),
('%l', fqdn),
('%u', user),
('%r', remoteuser)
],
'proxycommand': [
('%h', config['hostname']),
('%p', port),
('%r', remoteuser),
],
}
for k in config:
if k in replacements:
for find, replace in replacements[k]:
config[k] = config[k].replace(find, str(replace))
return config | random_line_split | |
config.py | # Copyright (C) 2006-2007 Robey Pointer <robeypointer@gmail.com>
#
# This file is part of paramiko.
#
# Paramiko is free software; you can redistribute it and/or modify it under the
# terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 2.1 of the License, or (at your option)
# any later version.
#
# Paramiko is distrubuted 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 Paramiko; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
"""
L{SSHConfig}.
"""
import fnmatch
import os
import re
import socket
SSH_PORT=22
proxy_re = re.compile(r"^(proxycommand)\s*=*\s*(.*)", re.I)
class SSHConfig (object):
"""
Representation of config information as stored in the format used by
OpenSSH. Queries can be made via L{lookup}. The format is described in
OpenSSH's C{ssh_config} man page. This class is provided primarily as a
convenience to posix users (since the OpenSSH format is a de-facto
standard on posix) but should work fine on Windows too.
@since: 1.6
"""
def __init__(self):
"""
Create a new OpenSSH config object.
"""
self._config = [ { 'host': '*' } ]
def | (self, file_obj):
"""
Read an OpenSSH config from the given file object.
@param file_obj: a file-like object to read the config file from
@type file_obj: file
"""
configs = [self._config[0]]
for line in file_obj:
line = line.rstrip('\n').lstrip()
if (line == '') or (line[0] == '#'):
continue
if '=' in line:
# Ensure ProxyCommand gets properly split
if line.lower().strip().startswith('proxycommand'):
match = proxy_re.match(line)
key, value = match.group(1).lower(), match.group(2)
else:
key, value = line.split('=', 1)
key = key.strip().lower()
else:
# find first whitespace, and split there
i = 0
while (i < len(line)) and not line[i].isspace():
i += 1
if i == len(line):
raise Exception('Unparsable line: %r' % line)
key = line[:i].lower()
value = line[i:].lstrip()
if key == 'host':
del configs[:]
# the value may be multiple hosts, space-delimited
for host in value.split():
# do we have a pre-existing host config to append to?
matches = [c for c in self._config if c['host'] == host]
if len(matches) > 0:
configs.append(matches[0])
else:
config = { 'host': host }
self._config.append(config)
configs.append(config)
else:
for config in configs:
config[key] = value
def lookup(self, hostname):
"""
Return a dict of config options for a given hostname.
The host-matching rules of OpenSSH's C{ssh_config} man page are used,
which means that all configuration options from matching host
specifications are merged, with more specific hostmasks taking
precedence. In other words, if C{"Port"} is set under C{"Host *"}
and also C{"Host *.example.com"}, and the lookup is for
C{"ssh.example.com"}, then the port entry for C{"Host *.example.com"}
will win out.
The keys in the returned dict are all normalized to lowercase (look for
C{"port"}, not C{"Port"}. No other processing is done to the keys or
values.
@param hostname: the hostname to lookup
@type hostname: str
"""
matches = [x for x in self._config if fnmatch.fnmatch(hostname, x['host'])]
# Move * to the end
_star = matches.pop(0)
matches.append(_star)
ret = {}
for m in matches:
for k,v in m.iteritems():
if not k in ret:
ret[k] = v
ret = self._expand_variables(ret, hostname)
del ret['host']
return ret
def _expand_variables(self, config, hostname ):
"""
Return a dict of config options with expanded substitutions
for a given hostname.
Please refer to man ssh_config(5) for the parameters that
are replaced.
@param config: the config for the hostname
@type hostname: dict
@param hostname: the hostname that the config belongs to
@type hostname: str
"""
if 'hostname' in config:
config['hostname'] = config['hostname'].replace('%h',hostname)
else:
config['hostname'] = hostname
if 'port' in config:
port = config['port']
else:
port = SSH_PORT
user = os.getenv('USER')
if 'user' in config:
remoteuser = config['user']
else:
remoteuser = user
host = socket.gethostname().split('.')[0]
fqdn = socket.getfqdn()
homedir = os.path.expanduser('~')
replacements = {
'controlpath': [
('%h', config['hostname']),
('%l', fqdn),
('%L', host),
('%n', hostname),
('%p', port),
('%r', remoteuser),
('%u', user)
],
'identityfile': [
('~', homedir),
('%d', homedir),
('%h', config['hostname']),
('%l', fqdn),
('%u', user),
('%r', remoteuser)
],
'proxycommand': [
('%h', config['hostname']),
('%p', port),
('%r', remoteuser),
],
}
for k in config:
if k in replacements:
for find, replace in replacements[k]:
config[k] = config[k].replace(find, str(replace))
return config
| parse | identifier_name |
demo_mp_async.py | #!/usr/bin/env python
import freenect
import signal
import matplotlib.pyplot as mp
from misc.demo import frame_convert
mp.ion()
image_rgb = None
image_depth = None
keep_running = True
def | (dev, data, timestamp):
global image_depth
data = frame_convert.pretty_depth(data)
mp.gray()
mp.figure(1)
if image_depth:
image_depth.set_data(data)
else:
image_depth = mp.imshow(data, interpolation='nearest', animated=True)
mp.draw()
def display_rgb(dev, data, timestamp):
global image_rgb
mp.figure(2)
if image_rgb:
image_rgb.set_data(data)
else:
image_rgb = mp.imshow(data, interpolation='nearest', animated=True)
mp.draw()
def body(*args):
if not keep_running:
raise freenect.Kill
def handler(signum, frame):
global keep_running
keep_running = False
print('Press Ctrl-C in terminal to stop')
signal.signal(signal.SIGINT, handler)
freenect.runloop(depth=display_depth,
video=display_rgb,
body=body)
| display_depth | identifier_name |
demo_mp_async.py | #!/usr/bin/env python
import freenect
import signal
import matplotlib.pyplot as mp
from misc.demo import frame_convert
mp.ion()
image_rgb = None
image_depth = None
keep_running = True
def display_depth(dev, data, timestamp):
global image_depth
data = frame_convert.pretty_depth(data)
mp.gray()
mp.figure(1)
if image_depth:
image_depth.set_data(data)
else:
image_depth = mp.imshow(data, interpolation='nearest', animated=True)
mp.draw()
def display_rgb(dev, data, timestamp):
global image_rgb
mp.figure(2)
if image_rgb:
image_rgb.set_data(data)
else:
image_rgb = mp.imshow(data, interpolation='nearest', animated=True)
mp.draw()
def body(*args):
if not keep_running:
raise freenect.Kill
def handler(signum, frame):
|
print('Press Ctrl-C in terminal to stop')
signal.signal(signal.SIGINT, handler)
freenect.runloop(depth=display_depth,
video=display_rgb,
body=body)
| global keep_running
keep_running = False | identifier_body |
demo_mp_async.py | #!/usr/bin/env python
import freenect
import signal
import matplotlib.pyplot as mp
from misc.demo import frame_convert
mp.ion()
image_rgb = None
image_depth = None
keep_running = True
def display_depth(dev, data, timestamp):
global image_depth
data = frame_convert.pretty_depth(data)
mp.gray()
mp.figure(1)
if image_depth:
image_depth.set_data(data)
else:
image_depth = mp.imshow(data, interpolation='nearest', animated=True)
mp.draw()
def display_rgb(dev, data, timestamp):
global image_rgb
mp.figure(2)
if image_rgb:
image_rgb.set_data(data)
else:
|
mp.draw()
def body(*args):
if not keep_running:
raise freenect.Kill
def handler(signum, frame):
global keep_running
keep_running = False
print('Press Ctrl-C in terminal to stop')
signal.signal(signal.SIGINT, handler)
freenect.runloop(depth=display_depth,
video=display_rgb,
body=body)
| image_rgb = mp.imshow(data, interpolation='nearest', animated=True) | conditional_block |
demo_mp_async.py | #!/usr/bin/env python
import freenect
import signal
import matplotlib.pyplot as mp
from misc.demo import frame_convert
mp.ion()
image_rgb = None
image_depth = None
keep_running = True
def display_depth(dev, data, timestamp):
global image_depth
data = frame_convert.pretty_depth(data) | else:
image_depth = mp.imshow(data, interpolation='nearest', animated=True)
mp.draw()
def display_rgb(dev, data, timestamp):
global image_rgb
mp.figure(2)
if image_rgb:
image_rgb.set_data(data)
else:
image_rgb = mp.imshow(data, interpolation='nearest', animated=True)
mp.draw()
def body(*args):
if not keep_running:
raise freenect.Kill
def handler(signum, frame):
global keep_running
keep_running = False
print('Press Ctrl-C in terminal to stop')
signal.signal(signal.SIGINT, handler)
freenect.runloop(depth=display_depth,
video=display_rgb,
body=body) | mp.gray()
mp.figure(1)
if image_depth:
image_depth.set_data(data) | random_line_split |
animation.rs | use std::collections::HashMap;
use ggez::Context;
use serde_derive::{Deserialize, Serialize};
use warmy;
use loadable_macro_derive::{LoadableRon, LoadableYaml};
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct SpriteData {
pub sprites: HashMap<String, Sprite>,
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub enum ImageType {
NonSolid,
Collidee,
Collider,
Blood,
BloodStain,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Image {
pub sheet: String,
pub image: usize,
pub x: i32,
pub y: i32,
pub image_type: ImageType,
}
impl Image {
pub fn is_collidee(&self) -> bool {
self.image_type == ImageType::Collidee
}
pub fn is_collider(&self) -> bool {
self.image_type == ImageType::Collider
}
pub fn is_blood(&self) -> bool {
match self.image_type {
ImageType::Blood | ImageType::BloodStain => true,
_ => false,
} | }
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Frame {
pub images: Vec<Image>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Animation {
pub frames: Vec<Frame>,
#[serde(default)]
pub order: Option<Vec<i32>>,
}
#[derive(Debug, Clone, Serialize, Deserialize, LoadableRon, LoadableYaml)]
#[serde(transparent)]
pub struct Sprite {
pub animations: HashMap<String, Animation>,
} | } | random_line_split |
animation.rs | use std::collections::HashMap;
use ggez::Context;
use serde_derive::{Deserialize, Serialize};
use warmy;
use loadable_macro_derive::{LoadableRon, LoadableYaml};
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct SpriteData {
pub sprites: HashMap<String, Sprite>,
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub enum | {
NonSolid,
Collidee,
Collider,
Blood,
BloodStain,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Image {
pub sheet: String,
pub image: usize,
pub x: i32,
pub y: i32,
pub image_type: ImageType,
}
impl Image {
pub fn is_collidee(&self) -> bool {
self.image_type == ImageType::Collidee
}
pub fn is_collider(&self) -> bool {
self.image_type == ImageType::Collider
}
pub fn is_blood(&self) -> bool {
match self.image_type {
ImageType::Blood | ImageType::BloodStain => true,
_ => false,
}
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Frame {
pub images: Vec<Image>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Animation {
pub frames: Vec<Frame>,
#[serde(default)]
pub order: Option<Vec<i32>>,
}
#[derive(Debug, Clone, Serialize, Deserialize, LoadableRon, LoadableYaml)]
#[serde(transparent)]
pub struct Sprite {
pub animations: HashMap<String, Animation>,
}
| ImageType | identifier_name |
outbox.controller.js | /**
* Outbox Controller
*
* @description controller for outbox page.
*/
(function() {
'use strict';
angular
.module('starter.controllers')
.controller('OutboxCtrl', OutboxCtrl);
OutboxCtrl.$inject = ['$rootScope', '$scope', '$ionicLoading', '$timeout', 'logger', 'OutboxService', 'SyncService', 'NetworkService', 'UserService'];
function | ($rootScope, $scope, $ionicLoading, $timeout, logger, OutboxService, SyncService, NetworkService, UserService) {
logger.log("in OutboxCtrl");
var outboxControllerViewModel = this;
outboxControllerViewModel.dirtyRecordExist = false;
outboxControllerViewModel.syncing = false;
// Methods used in view
outboxControllerViewModel.syncNow = syncNow;
activate();
function activate() {
$ionicLoading.show({
duration: 5000,
template: 'Loading...',
animation: 'fade-in',
showBackdrop: true
});
// get the dirty records
OutboxService.getDirtyRecords().then(function(records) {
if (records.length === 0) {
// If no dirty records then show the 'No records...' message
outboxControllerViewModel.dirtyRecordExist = false;
outboxControllerViewModel.outboxCount = "";
} else {
// Update count in this view's title (the count next to the Outbox menu item is updated by raising event 'MenuCtrl:updateOutboxCount')
outboxControllerViewModel.outboxCount = records.length > 0 ? " (" + records.length + ")" : "";
outboxControllerViewModel.dirtyRecords = buildDisplayRecords(records);
// Show the Sync Now button
outboxControllerViewModel.dirtyRecordExist = true;
}
$ionicLoading.hide();
});
}
// Build the records to display in view
function buildDisplayRecords(records) {
// Count number of dirty records for each mobile table name
var counts = _.countBy(records, 'Mobile_Table_Name');
// Build data to display in view
var dirtyRecords = _.map(counts, function(value, key){
// Map a more user fiendly name to the mobile table name
var displayTableName;
switch (key) {
// Add lines below like this for each table you're interested in
// case "myDummyTable1__ap" :
// displayTableName = "Table 1";
// break;
// case "myDummyTable1__ap" :
// displayTableName = "Table 2";
// break;
default :
// Won't come in here unless a new mobile table has been mobilised for the app, and not catered for in switch
displayTableName = key;
}
return {
"displayTableName": displayTableName,
"mobileTableName": key,
"count": value
};
});
return dirtyRecords;
}
// Run the sync method in the MenuCtrl
function syncNow() {
if (NetworkService.getNetworkStatus() === "online") {
SyncService.syncAllTablesNow();
outboxControllerViewModel.syncing = true;
} else {
outboxControllerViewModel.syncing = false;
$ionicLoading.show({
template: 'Please go on-line before attempting to sync',
animation: 'fade-in',
showBackdrop: true,
duration: 2000
});
}
}
// Process events fired from the SyncService
var deregisterHandleSyncTables = $scope.$on('syncTables', function(event, args) {
logger.log("OutboxCtrl syncTables: " + JSON.stringify(args));
if (args.result.toString() == "Complete") {
// Refresh this view after sync is complete
activate();
outboxControllerViewModel.syncing = false;
}
});
$scope.$on('$destroy', function() {
logger.log("OutboxCtrl destroy");
deregisterHandleSyncTables();
});
}
})();
| OutboxCtrl | identifier_name |
outbox.controller.js | /**
* Outbox Controller
*
* @description controller for outbox page.
*/
(function() {
'use strict';
angular
.module('starter.controllers')
.controller('OutboxCtrl', OutboxCtrl);
OutboxCtrl.$inject = ['$rootScope', '$scope', '$ionicLoading', '$timeout', 'logger', 'OutboxService', 'SyncService', 'NetworkService', 'UserService'];
function OutboxCtrl($rootScope, $scope, $ionicLoading, $timeout, logger, OutboxService, SyncService, NetworkService, UserService) {
logger.log("in OutboxCtrl");
var outboxControllerViewModel = this;
outboxControllerViewModel.dirtyRecordExist = false;
outboxControllerViewModel.syncing = false;
// Methods used in view
outboxControllerViewModel.syncNow = syncNow;
activate();
function activate() {
$ionicLoading.show({
duration: 5000,
template: 'Loading...',
animation: 'fade-in',
showBackdrop: true
});
// get the dirty records
OutboxService.getDirtyRecords().then(function(records) {
if (records.length === 0) {
// If no dirty records then show the 'No records...' message
outboxControllerViewModel.dirtyRecordExist = false;
outboxControllerViewModel.outboxCount = "";
} else {
// Update count in this view's title (the count next to the Outbox menu item is updated by raising event 'MenuCtrl:updateOutboxCount')
outboxControllerViewModel.outboxCount = records.length > 0 ? " (" + records.length + ")" : "";
outboxControllerViewModel.dirtyRecords = buildDisplayRecords(records);
// Show the Sync Now button
outboxControllerViewModel.dirtyRecordExist = true;
}
$ionicLoading.hide();
});
}
// Build the records to display in view
function buildDisplayRecords(records) {
// Count number of dirty records for each mobile table name
var counts = _.countBy(records, 'Mobile_Table_Name');
// Build data to display in view
var dirtyRecords = _.map(counts, function(value, key){
// Map a more user fiendly name to the mobile table name
var displayTableName;
switch (key) {
// Add lines below like this for each table you're interested in
// case "myDummyTable1__ap" :
// displayTableName = "Table 1";
// break;
// case "myDummyTable1__ap" :
// displayTableName = "Table 2";
// break;
default :
// Won't come in here unless a new mobile table has been mobilised for the app, and not catered for in switch
displayTableName = key;
}
return {
"displayTableName": displayTableName,
"mobileTableName": key,
"count": value
};
});
return dirtyRecords;
}
// Run the sync method in the MenuCtrl
function syncNow() { | SyncService.syncAllTablesNow();
outboxControllerViewModel.syncing = true;
} else {
outboxControllerViewModel.syncing = false;
$ionicLoading.show({
template: 'Please go on-line before attempting to sync',
animation: 'fade-in',
showBackdrop: true,
duration: 2000
});
}
}
// Process events fired from the SyncService
var deregisterHandleSyncTables = $scope.$on('syncTables', function(event, args) {
logger.log("OutboxCtrl syncTables: " + JSON.stringify(args));
if (args.result.toString() == "Complete") {
// Refresh this view after sync is complete
activate();
outboxControllerViewModel.syncing = false;
}
});
$scope.$on('$destroy', function() {
logger.log("OutboxCtrl destroy");
deregisterHandleSyncTables();
});
}
})(); | if (NetworkService.getNetworkStatus() === "online") { | random_line_split |
outbox.controller.js | /**
* Outbox Controller
*
* @description controller for outbox page.
*/
(function() {
'use strict';
angular
.module('starter.controllers')
.controller('OutboxCtrl', OutboxCtrl);
OutboxCtrl.$inject = ['$rootScope', '$scope', '$ionicLoading', '$timeout', 'logger', 'OutboxService', 'SyncService', 'NetworkService', 'UserService'];
function OutboxCtrl($rootScope, $scope, $ionicLoading, $timeout, logger, OutboxService, SyncService, NetworkService, UserService) |
})();
| {
logger.log("in OutboxCtrl");
var outboxControllerViewModel = this;
outboxControllerViewModel.dirtyRecordExist = false;
outboxControllerViewModel.syncing = false;
// Methods used in view
outboxControllerViewModel.syncNow = syncNow;
activate();
function activate() {
$ionicLoading.show({
duration: 5000,
template: 'Loading...',
animation: 'fade-in',
showBackdrop: true
});
// get the dirty records
OutboxService.getDirtyRecords().then(function(records) {
if (records.length === 0) {
// If no dirty records then show the 'No records...' message
outboxControllerViewModel.dirtyRecordExist = false;
outboxControllerViewModel.outboxCount = "";
} else {
// Update count in this view's title (the count next to the Outbox menu item is updated by raising event 'MenuCtrl:updateOutboxCount')
outboxControllerViewModel.outboxCount = records.length > 0 ? " (" + records.length + ")" : "";
outboxControllerViewModel.dirtyRecords = buildDisplayRecords(records);
// Show the Sync Now button
outboxControllerViewModel.dirtyRecordExist = true;
}
$ionicLoading.hide();
});
}
// Build the records to display in view
function buildDisplayRecords(records) {
// Count number of dirty records for each mobile table name
var counts = _.countBy(records, 'Mobile_Table_Name');
// Build data to display in view
var dirtyRecords = _.map(counts, function(value, key){
// Map a more user fiendly name to the mobile table name
var displayTableName;
switch (key) {
// Add lines below like this for each table you're interested in
// case "myDummyTable1__ap" :
// displayTableName = "Table 1";
// break;
// case "myDummyTable1__ap" :
// displayTableName = "Table 2";
// break;
default :
// Won't come in here unless a new mobile table has been mobilised for the app, and not catered for in switch
displayTableName = key;
}
return {
"displayTableName": displayTableName,
"mobileTableName": key,
"count": value
};
});
return dirtyRecords;
}
// Run the sync method in the MenuCtrl
function syncNow() {
if (NetworkService.getNetworkStatus() === "online") {
SyncService.syncAllTablesNow();
outboxControllerViewModel.syncing = true;
} else {
outboxControllerViewModel.syncing = false;
$ionicLoading.show({
template: 'Please go on-line before attempting to sync',
animation: 'fade-in',
showBackdrop: true,
duration: 2000
});
}
}
// Process events fired from the SyncService
var deregisterHandleSyncTables = $scope.$on('syncTables', function(event, args) {
logger.log("OutboxCtrl syncTables: " + JSON.stringify(args));
if (args.result.toString() == "Complete") {
// Refresh this view after sync is complete
activate();
outboxControllerViewModel.syncing = false;
}
});
$scope.$on('$destroy', function() {
logger.log("OutboxCtrl destroy");
deregisterHandleSyncTables();
});
} | identifier_body |
internal.js | (function () {
var parent = window.parent;
//dialog对象
dialog = parent.$EDITORUI[window.frameElement.id.replace(/_iframe$/, '')];
//当前打开dialog的编辑器实例
editor = dialog.editor;
UE = parent.UE;
domUtils = UE.dom.domUtils;
utils = UE.utils;
browser = UE.browser;
ajax = UE.ajax;
$G = function (id) {
return document.getElementById(id)
};
//focus元素
$focus = function (node) {
setTimeout(function () {
if (browser.ie) {
var r = node.createTextRange();
r.collapse(false);
r.select();
} else {
node.focus()
}
}, 0)
};
utils.loadFile(document, {
href: '../../themes/' + editor.options.theme + "/dialogbase.css?cache=" + Math.random(),
tag: "link",
type: "text/css",
rel: "stylesheet"
});
lang = editor.getLang(dialog.className.split("-")[2]);
if (lang) {
domUtils.on(window, 'load', function () {
var langImgPath = editor.options.langPath + editor.options.lang + "/images/";
//针对静态资源
for (var i in lang["static"]) {
var dom = $G(i);
if (!dom) continue;
var tagName = dom.tagName,
content = lang["static"][i];
if (content.src) {
//clone
content = utils.extend({}, content, false);
content.src = langImgPath + content.src; | content.style = content.style.replace(/url\s*\(/g, "url(" + langImgPath)
}
switch (tagName.toLowerCase()) {
case "var":
dom.parentNode.replaceChild(document.createTextNode(content), dom);
break;
case "select":
var ops = dom.options;
for (var j = 0, oj; oj = ops[j];) {
oj.innerHTML = content.options[j++];
}
for (var p in content) {
p != "options" && dom.setAttribute(p, content[p]);
}
break;
default:
domUtils.setAttributes(dom, content);
}
}
});
}
})(); | }
if (content.style) {
content = utils.extend({}, content, false); | random_line_split |
internal.js | (function () {
var parent = window.parent;
//dialog对象
dialog = parent.$EDITORUI[window.frameElement.id.replace(/_iframe$/, '')];
//当前打开dialog的编辑器实例
editor = dialog.editor;
UE = parent.UE;
domUtils = UE.dom.domUtils;
utils = UE.utils;
browser = UE.browser;
ajax = UE.ajax;
$G = function (id) {
return document.getElementById(id)
};
//focus元素
$focus = function (node) {
setTimeout(function () {
if (browser.ie) {
var r = node.createTextRange();
r.collapse(false);
r.select();
} else {
node.focus | tils.loadFile(document, {
href: '../../themes/' + editor.options.theme + "/dialogbase.css?cache=" + Math.random(),
tag: "link",
type: "text/css",
rel: "stylesheet"
});
lang = editor.getLang(dialog.className.split("-")[2]);
if (lang) {
domUtils.on(window, 'load', function () {
var langImgPath = editor.options.langPath + editor.options.lang + "/images/";
//针对静态资源
for (var i in lang["static"]) {
var dom = $G(i);
if (!dom) continue;
var tagName = dom.tagName,
content = lang["static"][i];
if (content.src) {
//clone
content = utils.extend({}, content, false);
content.src = langImgPath + content.src;
}
if (content.style) {
content = utils.extend({}, content, false);
content.style = content.style.replace(/url\s*\(/g, "url(" + langImgPath)
}
switch (tagName.toLowerCase()) {
case "var":
dom.parentNode.replaceChild(document.createTextNode(content), dom);
break;
case "select":
var ops = dom.options;
for (var j = 0, oj; oj = ops[j];) {
oj.innerHTML = content.options[j++];
}
for (var p in content) {
p != "options" && dom.setAttribute(p, content[p]);
}
break;
default:
domUtils.setAttributes(dom, content);
}
}
});
}
})(); | ()
}
}, 0)
};
u | conditional_block |
main-config.rs | extern crate cargo_update;
extern crate tabwriter;
use std::io::{Write, stdout};
use tabwriter::TabWriter;
use std::process::exit;
use std::mem;
fn | () {
let result = actual_main().err().unwrap_or(0);
exit(result);
}
fn actual_main() -> Result<(), i32> {
let mut opts = cargo_update::ConfigOptions::parse();
let config_file = cargo_update::ops::resolve_crates_file(mem::replace(&mut opts.crates_file.1, Default::default())).with_file_name(".install_config.toml");
let mut configuration = cargo_update::ops::PackageConfig::read(&config_file).map_err(|(e, r)| {
eprintln!("Reading config: {}", e);
r
})?;
if !opts.ops.is_empty() {
if *configuration.entry(opts.package.clone())
.and_modify(|cfg| cfg.execute_operations(&opts.ops))
.or_insert_with(|| cargo_update::ops::PackageConfig::from(&opts.ops)) == Default::default() {
configuration.remove(&opts.package);
}
cargo_update::ops::PackageConfig::write(&configuration, &config_file).map_err(|(e, r)| {
eprintln!("Writing config: {}", e);
r
})?;
}
if let Some(cfg) = configuration.get(&opts.package) {
let mut out = TabWriter::new(stdout());
if let Some(ref t) = cfg.toolchain {
writeln!(out, "Toolchain\t{}", t).unwrap();
}
if let Some(d) = cfg.debug {
writeln!(out, "Debug mode\t{}", d).unwrap();
}
if let Some(ip) = cfg.install_prereleases {
writeln!(out, "Install prereleases\t{}", ip).unwrap();
}
if let Some(el) = cfg.enforce_lock {
writeln!(out, "Enforce lock\t{}", el).unwrap();
}
if let Some(rb) = cfg.respect_binaries {
writeln!(out, "Respect binaries\t{}", rb).unwrap();
}
if let Some(ref tv) = cfg.target_version {
writeln!(out, "Target version\t{}", tv).unwrap();
}
writeln!(out, "Default features\t{}", cfg.default_features).unwrap();
if !cfg.features.is_empty() {
write!(out, "Features").unwrap();
for f in &cfg.features {
writeln!(out, "\t{}", f).unwrap();
}
}
out.flush().unwrap();
} else {
println!("No configuration for package {}.", opts.package);
}
Ok(())
}
| main | identifier_name |
main-config.rs | extern crate cargo_update;
extern crate tabwriter;
use std::io::{Write, stdout};
use tabwriter::TabWriter;
use std::process::exit;
use std::mem;
fn main() {
let result = actual_main().err().unwrap_or(0);
exit(result);
}
fn actual_main() -> Result<(), i32> {
let mut opts = cargo_update::ConfigOptions::parse();
let config_file = cargo_update::ops::resolve_crates_file(mem::replace(&mut opts.crates_file.1, Default::default())).with_file_name(".install_config.toml");
let mut configuration = cargo_update::ops::PackageConfig::read(&config_file).map_err(|(e, r)| {
eprintln!("Reading config: {}", e);
r
})?;
if !opts.ops.is_empty() {
if *configuration.entry(opts.package.clone())
.and_modify(|cfg| cfg.execute_operations(&opts.ops))
.or_insert_with(|| cargo_update::ops::PackageConfig::from(&opts.ops)) == Default::default() {
configuration.remove(&opts.package);
}
cargo_update::ops::PackageConfig::write(&configuration, &config_file).map_err(|(e, r)| {
eprintln!("Writing config: {}", e);
r
})?;
}
if let Some(cfg) = configuration.get(&opts.package) {
let mut out = TabWriter::new(stdout());
if let Some(ref t) = cfg.toolchain {
writeln!(out, "Toolchain\t{}", t).unwrap();
}
if let Some(d) = cfg.debug {
writeln!(out, "Debug mode\t{}", d).unwrap();
}
if let Some(ip) = cfg.install_prereleases {
writeln!(out, "Install prereleases\t{}", ip).unwrap();
}
if let Some(el) = cfg.enforce_lock |
if let Some(rb) = cfg.respect_binaries {
writeln!(out, "Respect binaries\t{}", rb).unwrap();
}
if let Some(ref tv) = cfg.target_version {
writeln!(out, "Target version\t{}", tv).unwrap();
}
writeln!(out, "Default features\t{}", cfg.default_features).unwrap();
if !cfg.features.is_empty() {
write!(out, "Features").unwrap();
for f in &cfg.features {
writeln!(out, "\t{}", f).unwrap();
}
}
out.flush().unwrap();
} else {
println!("No configuration for package {}.", opts.package);
}
Ok(())
}
| {
writeln!(out, "Enforce lock\t{}", el).unwrap();
} | conditional_block |
main-config.rs | extern crate cargo_update;
extern crate tabwriter;
use std::io::{Write, stdout};
use tabwriter::TabWriter;
use std::process::exit;
use std::mem;
fn main() |
fn actual_main() -> Result<(), i32> {
let mut opts = cargo_update::ConfigOptions::parse();
let config_file = cargo_update::ops::resolve_crates_file(mem::replace(&mut opts.crates_file.1, Default::default())).with_file_name(".install_config.toml");
let mut configuration = cargo_update::ops::PackageConfig::read(&config_file).map_err(|(e, r)| {
eprintln!("Reading config: {}", e);
r
})?;
if !opts.ops.is_empty() {
if *configuration.entry(opts.package.clone())
.and_modify(|cfg| cfg.execute_operations(&opts.ops))
.or_insert_with(|| cargo_update::ops::PackageConfig::from(&opts.ops)) == Default::default() {
configuration.remove(&opts.package);
}
cargo_update::ops::PackageConfig::write(&configuration, &config_file).map_err(|(e, r)| {
eprintln!("Writing config: {}", e);
r
})?;
}
if let Some(cfg) = configuration.get(&opts.package) {
let mut out = TabWriter::new(stdout());
if let Some(ref t) = cfg.toolchain {
writeln!(out, "Toolchain\t{}", t).unwrap();
}
if let Some(d) = cfg.debug {
writeln!(out, "Debug mode\t{}", d).unwrap();
}
if let Some(ip) = cfg.install_prereleases {
writeln!(out, "Install prereleases\t{}", ip).unwrap();
}
if let Some(el) = cfg.enforce_lock {
writeln!(out, "Enforce lock\t{}", el).unwrap();
}
if let Some(rb) = cfg.respect_binaries {
writeln!(out, "Respect binaries\t{}", rb).unwrap();
}
if let Some(ref tv) = cfg.target_version {
writeln!(out, "Target version\t{}", tv).unwrap();
}
writeln!(out, "Default features\t{}", cfg.default_features).unwrap();
if !cfg.features.is_empty() {
write!(out, "Features").unwrap();
for f in &cfg.features {
writeln!(out, "\t{}", f).unwrap();
}
}
out.flush().unwrap();
} else {
println!("No configuration for package {}.", opts.package);
}
Ok(())
}
| {
let result = actual_main().err().unwrap_or(0);
exit(result);
} | identifier_body |
main-config.rs | extern crate cargo_update;
extern crate tabwriter;
use std::io::{Write, stdout};
use tabwriter::TabWriter;
use std::process::exit;
use std::mem;
fn main() {
let result = actual_main().err().unwrap_or(0);
exit(result);
}
fn actual_main() -> Result<(), i32> {
let mut opts = cargo_update::ConfigOptions::parse();
let config_file = cargo_update::ops::resolve_crates_file(mem::replace(&mut opts.crates_file.1, Default::default())).with_file_name(".install_config.toml");
let mut configuration = cargo_update::ops::PackageConfig::read(&config_file).map_err(|(e, r)| {
eprintln!("Reading config: {}", e);
r
})?;
if !opts.ops.is_empty() {
if *configuration.entry(opts.package.clone())
.and_modify(|cfg| cfg.execute_operations(&opts.ops))
.or_insert_with(|| cargo_update::ops::PackageConfig::from(&opts.ops)) == Default::default() {
configuration.remove(&opts.package);
}
cargo_update::ops::PackageConfig::write(&configuration, &config_file).map_err(|(e, r)| {
eprintln!("Writing config: {}", e);
r
})?;
}
if let Some(cfg) = configuration.get(&opts.package) { | writeln!(out, "Toolchain\t{}", t).unwrap();
}
if let Some(d) = cfg.debug {
writeln!(out, "Debug mode\t{}", d).unwrap();
}
if let Some(ip) = cfg.install_prereleases {
writeln!(out, "Install prereleases\t{}", ip).unwrap();
}
if let Some(el) = cfg.enforce_lock {
writeln!(out, "Enforce lock\t{}", el).unwrap();
}
if let Some(rb) = cfg.respect_binaries {
writeln!(out, "Respect binaries\t{}", rb).unwrap();
}
if let Some(ref tv) = cfg.target_version {
writeln!(out, "Target version\t{}", tv).unwrap();
}
writeln!(out, "Default features\t{}", cfg.default_features).unwrap();
if !cfg.features.is_empty() {
write!(out, "Features").unwrap();
for f in &cfg.features {
writeln!(out, "\t{}", f).unwrap();
}
}
out.flush().unwrap();
} else {
println!("No configuration for package {}.", opts.package);
}
Ok(())
} | let mut out = TabWriter::new(stdout());
if let Some(ref t) = cfg.toolchain { | random_line_split |
PathStore.spec.js | 'use strict';
var test = require('tape');
var rewire = require('rewire');
var api = require('./PathStore.api');
var PathStore = rewire('../../../src/core/PathStore');
var PathUtilsStub = require('../path/Path.stub');
var helpers = require('./PathStore.helpers');
PathStore.__set__('PathUtils', PathUtilsStub);
helpers.setPathStub(PathUtilsStub);
test('PathStore class', function (t) {
t.test('PathStore constructor', function (t) {
t.equal(PathStore.constructor, Function, 'PathStore should be a function');
t.doesNotThrow(function () {
return new PathStore();
}, 'PathStore should be able to be called with new');
t.equal((new PathStore()).constructor, PathStore, 'PathStore should be a constructor function');
var pathStore = new PathStore();
api.forEach(function (method) {
t.ok(
pathStore[method] && pathStore[method].constructor === Function,
'PathStore should have a ' + method + ' method'
);
});
t.end();
});
t.test('.insert method', function (t) {
var pathStore = new PathStore();
var a = new helpers.InsertTester(1, 0, 'a');
t.doesNotThrow(function () {
pathStore.insert('a', a);
}, 'insert should be able to be called with a string and any other argument');
t.equal(
pathStore.get('a'), a,
'insert should insert the given item at the given path' +
' such that the path can be used to look it up with the get method'
);
t.ok(
pathStore.getItems().indexOf(a) > -1,
'insert should insert the given item into the store such' +
' that it can be found in the array returned by the getItems method'
);
[
[2, 0, 'b'],
[2, 1, 'c'],
[2, 2, 'd'],
[3, 6, 'e'],
[1, 4, 'f'],
[2, 4, 'g'],
[6, 0, 'h']
].forEach(function (triple) {
pathStore.insert(triple[2], new helpers.InsertTester(triple[0], triple[1], triple[2]));
});
pathStore.getItems().forEach(function (item, i, items) {
t.equal(
pathStore.get(item.path), item,
'insert should insert the given item at the given path' +
' such that the path can be used to look it up with the get method'
);
t.ok(
pathStore.getItems().indexOf(item) > -1,
'insert should insert the given item into the store' +
' such that it can be found in the array returned by the getItems method'
);
if (items[i + 1]) {
t.ok(
items[i + 1].isAfter(items[i]),
'insert should order items such that they are sorted by depth and ties are broken by index'
);
}
});
t.end();
});
t.test('.remove method', function (t) {
var pathStore = new PathStore();
var index;
Array.apply(null, Array(10)).map(function (_, i) {
return new helpers.InsertTester(i, 0, String.fromCharCode(97 + i));
}).forEach(function (it) {
pathStore.insert(it.path, it);
});
// sanity check
if (pathStore.getItems().length !== 10) throw new Error('PathStore.insert is broken');
function removeItem (i) |
function checkOrder () {
pathStore.getItems().forEach(function (item, i, items) {
if (items[i + 1]) {
t.ok(
items[i + 1].isAfter(items[i]),
'remove should preserve the sort of the items in PathStore'
);
}
});
}
while (pathStore.getItems().length) {
index = (Math.random() * 11)|0;
if (removeItem(index)) checkOrder();
}
t.end();
});
t.end();
});
| {
var ch = String.fromCharCode(i + 97);
var b = pathStore.get(ch);
if (b) {
t.doesNotThrow(function () {
pathStore.remove(ch);
}, 'remove should be able to be called and remove an item by key');
t.equal(pathStore.get(ch), undefined, '.remove should remove the item at the path');
t.equal(
pathStore.getItems().indexOf(b), -1,
'removed items should not be available in the array returned by getItems'
);
return true;
}
return false;
} | identifier_body |
PathStore.spec.js | 'use strict';
var test = require('tape');
var rewire = require('rewire');
var api = require('./PathStore.api');
var PathStore = rewire('../../../src/core/PathStore');
var PathUtilsStub = require('../path/Path.stub');
var helpers = require('./PathStore.helpers');
PathStore.__set__('PathUtils', PathUtilsStub);
helpers.setPathStub(PathUtilsStub);
test('PathStore class', function (t) {
t.test('PathStore constructor', function (t) {
t.equal(PathStore.constructor, Function, 'PathStore should be a function');
t.doesNotThrow(function () {
return new PathStore();
}, 'PathStore should be able to be called with new');
t.equal((new PathStore()).constructor, PathStore, 'PathStore should be a constructor function');
var pathStore = new PathStore();
api.forEach(function (method) {
t.ok(
pathStore[method] && pathStore[method].constructor === Function,
'PathStore should have a ' + method + ' method'
);
});
t.end();
});
t.test('.insert method', function (t) {
var pathStore = new PathStore();
var a = new helpers.InsertTester(1, 0, 'a');
t.doesNotThrow(function () {
pathStore.insert('a', a);
}, 'insert should be able to be called with a string and any other argument');
t.equal(
pathStore.get('a'), a,
'insert should insert the given item at the given path' +
' such that the path can be used to look it up with the get method'
);
t.ok(
pathStore.getItems().indexOf(a) > -1,
'insert should insert the given item into the store such' +
' that it can be found in the array returned by the getItems method'
);
[
[2, 0, 'b'],
[2, 1, 'c'],
[2, 2, 'd'],
[3, 6, 'e'],
[1, 4, 'f'],
[2, 4, 'g'],
[6, 0, 'h']
].forEach(function (triple) {
pathStore.insert(triple[2], new helpers.InsertTester(triple[0], triple[1], triple[2]));
});
pathStore.getItems().forEach(function (item, i, items) {
t.equal(
pathStore.get(item.path), item,
'insert should insert the given item at the given path' +
' such that the path can be used to look it up with the get method'
);
t.ok(
pathStore.getItems().indexOf(item) > -1,
'insert should insert the given item into the store' +
' such that it can be found in the array returned by the getItems method'
);
if (items[i + 1]) {
t.ok(
items[i + 1].isAfter(items[i]),
'insert should order items such that they are sorted by depth and ties are broken by index'
);
}
});
t.end();
});
t.test('.remove method', function (t) {
var pathStore = new PathStore();
var index;
Array.apply(null, Array(10)).map(function (_, i) {
return new helpers.InsertTester(i, 0, String.fromCharCode(97 + i));
}).forEach(function (it) {
pathStore.insert(it.path, it);
});
// sanity check
if (pathStore.getItems().length !== 10) throw new Error('PathStore.insert is broken');
function | (i) {
var ch = String.fromCharCode(i + 97);
var b = pathStore.get(ch);
if (b) {
t.doesNotThrow(function () {
pathStore.remove(ch);
}, 'remove should be able to be called and remove an item by key');
t.equal(pathStore.get(ch), undefined, '.remove should remove the item at the path');
t.equal(
pathStore.getItems().indexOf(b), -1,
'removed items should not be available in the array returned by getItems'
);
return true;
}
return false;
}
function checkOrder () {
pathStore.getItems().forEach(function (item, i, items) {
if (items[i + 1]) {
t.ok(
items[i + 1].isAfter(items[i]),
'remove should preserve the sort of the items in PathStore'
);
}
});
}
while (pathStore.getItems().length) {
index = (Math.random() * 11)|0;
if (removeItem(index)) checkOrder();
}
t.end();
});
t.end();
});
| removeItem | identifier_name |
PathStore.spec.js | 'use strict';
var test = require('tape');
var rewire = require('rewire');
var api = require('./PathStore.api');
var PathStore = rewire('../../../src/core/PathStore');
var PathUtilsStub = require('../path/Path.stub');
var helpers = require('./PathStore.helpers');
PathStore.__set__('PathUtils', PathUtilsStub);
helpers.setPathStub(PathUtilsStub);
test('PathStore class', function (t) {
t.test('PathStore constructor', function (t) {
t.equal(PathStore.constructor, Function, 'PathStore should be a function');
t.doesNotThrow(function () {
return new PathStore();
}, 'PathStore should be able to be called with new');
t.equal((new PathStore()).constructor, PathStore, 'PathStore should be a constructor function');
var pathStore = new PathStore();
api.forEach(function (method) {
t.ok(
pathStore[method] && pathStore[method].constructor === Function,
'PathStore should have a ' + method + ' method'
);
});
t.end();
});
t.test('.insert method', function (t) {
var pathStore = new PathStore();
var a = new helpers.InsertTester(1, 0, 'a');
t.doesNotThrow(function () {
pathStore.insert('a', a);
}, 'insert should be able to be called with a string and any other argument');
t.equal(
pathStore.get('a'), a,
'insert should insert the given item at the given path' +
' such that the path can be used to look it up with the get method'
);
t.ok(
pathStore.getItems().indexOf(a) > -1,
'insert should insert the given item into the store such' +
' that it can be found in the array returned by the getItems method'
);
[
[2, 0, 'b'],
[2, 1, 'c'],
[2, 2, 'd'],
[3, 6, 'e'],
[1, 4, 'f'],
[2, 4, 'g'],
[6, 0, 'h']
].forEach(function (triple) {
pathStore.insert(triple[2], new helpers.InsertTester(triple[0], triple[1], triple[2]));
});
pathStore.getItems().forEach(function (item, i, items) {
t.equal(
pathStore.get(item.path), item,
'insert should insert the given item at the given path' +
' such that the path can be used to look it up with the get method'
);
t.ok(
pathStore.getItems().indexOf(item) > -1,
'insert should insert the given item into the store' +
' such that it can be found in the array returned by the getItems method'
);
if (items[i + 1]) {
t.ok(
items[i + 1].isAfter(items[i]),
'insert should order items such that they are sorted by depth and ties are broken by index'
);
}
});
t.end();
});
t.test('.remove method', function (t) {
var pathStore = new PathStore();
var index;
Array.apply(null, Array(10)).map(function (_, i) {
return new helpers.InsertTester(i, 0, String.fromCharCode(97 + i));
}).forEach(function (it) {
pathStore.insert(it.path, it);
});
// sanity check
if (pathStore.getItems().length !== 10) throw new Error('PathStore.insert is broken');
function removeItem (i) {
var ch = String.fromCharCode(i + 97);
var b = pathStore.get(ch);
if (b) {
t.doesNotThrow(function () {
pathStore.remove(ch);
}, 'remove should be able to be called and remove an item by key');
t.equal(pathStore.get(ch), undefined, '.remove should remove the item at the path');
t.equal(
pathStore.getItems().indexOf(b), -1,
'removed items should not be available in the array returned by getItems'
);
return true;
}
return false; | pathStore.getItems().forEach(function (item, i, items) {
if (items[i + 1]) {
t.ok(
items[i + 1].isAfter(items[i]),
'remove should preserve the sort of the items in PathStore'
);
}
});
}
while (pathStore.getItems().length) {
index = (Math.random() * 11)|0;
if (removeItem(index)) checkOrder();
}
t.end();
});
t.end();
}); | }
function checkOrder () { | random_line_split |
PathStore.spec.js | 'use strict';
var test = require('tape');
var rewire = require('rewire');
var api = require('./PathStore.api');
var PathStore = rewire('../../../src/core/PathStore');
var PathUtilsStub = require('../path/Path.stub');
var helpers = require('./PathStore.helpers');
PathStore.__set__('PathUtils', PathUtilsStub);
helpers.setPathStub(PathUtilsStub);
test('PathStore class', function (t) {
t.test('PathStore constructor', function (t) {
t.equal(PathStore.constructor, Function, 'PathStore should be a function');
t.doesNotThrow(function () {
return new PathStore();
}, 'PathStore should be able to be called with new');
t.equal((new PathStore()).constructor, PathStore, 'PathStore should be a constructor function');
var pathStore = new PathStore();
api.forEach(function (method) {
t.ok(
pathStore[method] && pathStore[method].constructor === Function,
'PathStore should have a ' + method + ' method'
);
});
t.end();
});
t.test('.insert method', function (t) {
var pathStore = new PathStore();
var a = new helpers.InsertTester(1, 0, 'a');
t.doesNotThrow(function () {
pathStore.insert('a', a);
}, 'insert should be able to be called with a string and any other argument');
t.equal(
pathStore.get('a'), a,
'insert should insert the given item at the given path' +
' such that the path can be used to look it up with the get method'
);
t.ok(
pathStore.getItems().indexOf(a) > -1,
'insert should insert the given item into the store such' +
' that it can be found in the array returned by the getItems method'
);
[
[2, 0, 'b'],
[2, 1, 'c'],
[2, 2, 'd'],
[3, 6, 'e'],
[1, 4, 'f'],
[2, 4, 'g'],
[6, 0, 'h']
].forEach(function (triple) {
pathStore.insert(triple[2], new helpers.InsertTester(triple[0], triple[1], triple[2]));
});
pathStore.getItems().forEach(function (item, i, items) {
t.equal(
pathStore.get(item.path), item,
'insert should insert the given item at the given path' +
' such that the path can be used to look it up with the get method'
);
t.ok(
pathStore.getItems().indexOf(item) > -1,
'insert should insert the given item into the store' +
' such that it can be found in the array returned by the getItems method'
);
if (items[i + 1]) {
t.ok(
items[i + 1].isAfter(items[i]),
'insert should order items such that they are sorted by depth and ties are broken by index'
);
}
});
t.end();
});
t.test('.remove method', function (t) {
var pathStore = new PathStore();
var index;
Array.apply(null, Array(10)).map(function (_, i) {
return new helpers.InsertTester(i, 0, String.fromCharCode(97 + i));
}).forEach(function (it) {
pathStore.insert(it.path, it);
});
// sanity check
if (pathStore.getItems().length !== 10) throw new Error('PathStore.insert is broken');
function removeItem (i) {
var ch = String.fromCharCode(i + 97);
var b = pathStore.get(ch);
if (b) {
t.doesNotThrow(function () {
pathStore.remove(ch);
}, 'remove should be able to be called and remove an item by key');
t.equal(pathStore.get(ch), undefined, '.remove should remove the item at the path');
t.equal(
pathStore.getItems().indexOf(b), -1,
'removed items should not be available in the array returned by getItems'
);
return true;
}
return false;
}
function checkOrder () {
pathStore.getItems().forEach(function (item, i, items) {
if (items[i + 1]) |
});
}
while (pathStore.getItems().length) {
index = (Math.random() * 11)|0;
if (removeItem(index)) checkOrder();
}
t.end();
});
t.end();
});
| {
t.ok(
items[i + 1].isAfter(items[i]),
'remove should preserve the sort of the items in PathStore'
);
} | conditional_block |
new-server.test.ts | ///<reference path="../../node_modules/@types/jasmine/index.d.ts"/>
/**
* @license
* Copyright 2016 JBoss 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 {commandTest} from "./_test-utils";
import {Oas30Document, Oas30Operation, Oas30PathItem, Oas30Server} from "oai-ts-core";
import {createNewServerCommand} from "../../src/commands/new-server.command";
describe("New Server (3.0)", () => {
it("New Server (Document)", () => {
commandTest(
"tests/_fixtures/commands/new-server/3.0/new-server-document.before.json",
"tests/_fixtures/commands/new-server/3.0/new-server-document.after.json",
(document: Oas30Document) => {
let server: Oas30Server = document.createServer();
server.url = "https://development.gigantic-server.com/v1";
server.description = "Development server";
return createNewServerCommand(document, null, server);
}
); | "tests/_fixtures/commands/new-server/3.0/new-server-document-exists.before.json",
"tests/_fixtures/commands/new-server/3.0/new-server-document-exists.after.json",
(document: Oas30Document) => {
let server: Oas30Server = document.createServer();
server.url = "https://development.gigantic-server.com/v1";
server.description = "Development server";
return createNewServerCommand(document, null, server);
}
);
});
it("New Server (Path Item)", () => {
commandTest(
"tests/_fixtures/commands/new-server/3.0/new-server-pathItem.before.json",
"tests/_fixtures/commands/new-server/3.0/new-server-pathItem.after.json",
(document: Oas30Document) => {
let pathItem: Oas30PathItem = document.paths.pathItem("/foo") as Oas30PathItem;
let server: Oas30Server = pathItem.createServer();
server.url = "https://development.gigantic-server.com/v1";
server.description = "Development server";
return createNewServerCommand(document, pathItem, server);
}
);
});
it("New Server (Operation)", () => {
commandTest(
"tests/_fixtures/commands/new-server/3.0/new-server-operation.before.json",
"tests/_fixtures/commands/new-server/3.0/new-server-operation.after.json",
(document: Oas30Document) => {
let operation: Oas30Operation = document.paths.pathItem("/foo").get as Oas30Operation;
let server: Oas30Server = operation.createServer();
server.url = "https://development.gigantic-server.com/v1";
server.description = "Development server";
return createNewServerCommand(document, operation, server);
}
);
});
}); | });
it("New Server (Document) [Already Exists]", () => {
commandTest( | random_line_split |
20120430B.py | """
Consider this game: Write 8 blanks on a sheet of paper. Randomly pick a digit 0-9. After seeing the digit, choose one
of the 8 blanks to place that digit in. Randomly choose another digit (with replacement) and then choose one of the 7
remaining blanks to place it in. Repeat until you've filled all 8 blanks. You win if the 8 digits written down are in
order from smallest to largest.
Write a program that plays this game by itself and determines whether it won or not. Run it 1 million times and post
your probability of winning.
Assigning digits to blanks randomly lets you win about 0.02% of the time. Here's a python script that wins about 10.3%
of the time. Can you do better?
import random
def trial():
indices = range(8) # remaining unassigned indices
s = [None] * 8 # the digits in their assigned places
while indices:
d = random.randint(0,9) # choose a random digit
index = indices[int(d*len(indices)/10)] # assign it an index
s[index] = str(d)
indices.remove(index)
return s == sorted(s)
print sum(trial() for _ in range(1000000))
thanks to cosmologicon for the challenge at /r/dailyprogrammer_ideas ..
link [http://www.reddit.com/r/dailyprogrammer_ideas/comments/s30be/intermediate_digitassigning_game/]
"""
import random
import itertools
def | (data):
# print(data)
return all(b >= a for a, b in zip(data, itertools.islice(data, 1, None)))
TRIALS = 1
win = 0
for a in range(TRIALS):
l = [None] * 8
p = list(range(8))
while p:
d = random.randint(0,9)
# i = random.choice(p)
i = int(d * (len(p)) / 10)
print(p[i])
l[p[i]] = d
p.pop(i)
print(l)
if que_sort(l):
win += 1
print('{}/{} - {}%'.format(win, TRIALS, win/TRIALS*100)) | que_sort | identifier_name |
20120430B.py | """
Consider this game: Write 8 blanks on a sheet of paper. Randomly pick a digit 0-9. After seeing the digit, choose one
of the 8 blanks to place that digit in. Randomly choose another digit (with replacement) and then choose one of the 7
remaining blanks to place it in. Repeat until you've filled all 8 blanks. You win if the 8 digits written down are in
order from smallest to largest.
Write a program that plays this game by itself and determines whether it won or not. Run it 1 million times and post
your probability of winning. | Assigning digits to blanks randomly lets you win about 0.02% of the time. Here's a python script that wins about 10.3%
of the time. Can you do better?
import random
def trial():
indices = range(8) # remaining unassigned indices
s = [None] * 8 # the digits in their assigned places
while indices:
d = random.randint(0,9) # choose a random digit
index = indices[int(d*len(indices)/10)] # assign it an index
s[index] = str(d)
indices.remove(index)
return s == sorted(s)
print sum(trial() for _ in range(1000000))
thanks to cosmologicon for the challenge at /r/dailyprogrammer_ideas ..
link [http://www.reddit.com/r/dailyprogrammer_ideas/comments/s30be/intermediate_digitassigning_game/]
"""
import random
import itertools
def que_sort(data):
# print(data)
return all(b >= a for a, b in zip(data, itertools.islice(data, 1, None)))
TRIALS = 1
win = 0
for a in range(TRIALS):
l = [None] * 8
p = list(range(8))
while p:
d = random.randint(0,9)
# i = random.choice(p)
i = int(d * (len(p)) / 10)
print(p[i])
l[p[i]] = d
p.pop(i)
print(l)
if que_sort(l):
win += 1
print('{}/{} - {}%'.format(win, TRIALS, win/TRIALS*100)) | random_line_split | |
20120430B.py | """
Consider this game: Write 8 blanks on a sheet of paper. Randomly pick a digit 0-9. After seeing the digit, choose one
of the 8 blanks to place that digit in. Randomly choose another digit (with replacement) and then choose one of the 7
remaining blanks to place it in. Repeat until you've filled all 8 blanks. You win if the 8 digits written down are in
order from smallest to largest.
Write a program that plays this game by itself and determines whether it won or not. Run it 1 million times and post
your probability of winning.
Assigning digits to blanks randomly lets you win about 0.02% of the time. Here's a python script that wins about 10.3%
of the time. Can you do better?
import random
def trial():
indices = range(8) # remaining unassigned indices
s = [None] * 8 # the digits in their assigned places
while indices:
d = random.randint(0,9) # choose a random digit
index = indices[int(d*len(indices)/10)] # assign it an index
s[index] = str(d)
indices.remove(index)
return s == sorted(s)
print sum(trial() for _ in range(1000000))
thanks to cosmologicon for the challenge at /r/dailyprogrammer_ideas ..
link [http://www.reddit.com/r/dailyprogrammer_ideas/comments/s30be/intermediate_digitassigning_game/]
"""
import random
import itertools
def que_sort(data):
# print(data)
return all(b >= a for a, b in zip(data, itertools.islice(data, 1, None)))
TRIALS = 1
win = 0
for a in range(TRIALS):
l = [None] * 8
p = list(range(8))
while p:
d = random.randint(0,9)
# i = random.choice(p)
i = int(d * (len(p)) / 10)
print(p[i])
l[p[i]] = d
p.pop(i)
print(l)
if que_sort(l):
|
print('{}/{} - {}%'.format(win, TRIALS, win/TRIALS*100)) | win += 1 | conditional_block |
20120430B.py | """
Consider this game: Write 8 blanks on a sheet of paper. Randomly pick a digit 0-9. After seeing the digit, choose one
of the 8 blanks to place that digit in. Randomly choose another digit (with replacement) and then choose one of the 7
remaining blanks to place it in. Repeat until you've filled all 8 blanks. You win if the 8 digits written down are in
order from smallest to largest.
Write a program that plays this game by itself and determines whether it won or not. Run it 1 million times and post
your probability of winning.
Assigning digits to blanks randomly lets you win about 0.02% of the time. Here's a python script that wins about 10.3%
of the time. Can you do better?
import random
def trial():
indices = range(8) # remaining unassigned indices
s = [None] * 8 # the digits in their assigned places
while indices:
d = random.randint(0,9) # choose a random digit
index = indices[int(d*len(indices)/10)] # assign it an index
s[index] = str(d)
indices.remove(index)
return s == sorted(s)
print sum(trial() for _ in range(1000000))
thanks to cosmologicon for the challenge at /r/dailyprogrammer_ideas ..
link [http://www.reddit.com/r/dailyprogrammer_ideas/comments/s30be/intermediate_digitassigning_game/]
"""
import random
import itertools
def que_sort(data):
# print(data)
|
TRIALS = 1
win = 0
for a in range(TRIALS):
l = [None] * 8
p = list(range(8))
while p:
d = random.randint(0,9)
# i = random.choice(p)
i = int(d * (len(p)) / 10)
print(p[i])
l[p[i]] = d
p.pop(i)
print(l)
if que_sort(l):
win += 1
print('{}/{} - {}%'.format(win, TRIALS, win/TRIALS*100)) | return all(b >= a for a, b in zip(data, itertools.islice(data, 1, None))) | identifier_body |
BigDisplayModeConfiguration.test.tsx | /*
* Copyright (C) 2020 Graylog, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* 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
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*/
import * as React from 'react';
import { asElement, fireEvent, render } from 'wrappedTestingLibrary';
import * as Immutable from 'immutable';
import history from 'util/History';
import Routes from 'routing/Routes';
import View, { ViewStateMap } from 'views/logic/views/View';
import Search from 'views/logic/search/Search';
import Query from 'views/logic/queries/Query';
import ViewState from 'views/logic/views/ViewState';
import BigDisplayModeConfiguration from './BigDisplayModeConfiguration';
jest.mock('routing/Routes', () => ({ pluginRoute: jest.fn() }));
const search = Search.create();
const view = View.create()
.toBuilder()
.id('deadbeef')
.type(View.Type.Dashboard)
.search(search)
.build();
const createViewWithQueries = () => {
const queries = [
Query.builder().id('query-id-1').build(),
Query.builder().id('query-id-2').build(),
Query.builder().id('other-query-id').build(),
];
const states: ViewStateMap = Immutable.Map({
'query-id-1': ViewState.create(),
'query-id-2': ViewState.builder().titles(Immutable.fromJS({ tab: { title: 'My awesome Query tab' } })).build(),
'other-query-id': ViewState.create(),
});
const searchWithQueries = search.toBuilder()
.queries(queries)
.build();
return view.toBuilder()
.state(states)
.search(searchWithQueries)
.build();
};
describe('BigDisplayModeConfiguration', () => {
const SUT = (props) => (
<BigDisplayModeConfiguration view={view} {...props} />
);
it('generates markup that matches snapshot', () => {
const { container } = render(<SUT />);
expect(container).toMatchSnapshot();
});
it('disables menu item if `disabled` prop is `true`', () => {
const { getByText, queryByText } = render(<SUT disabled />);
const menuItem = getByText('Full Screen');
fireEvent.submit(menuItem);
expect(queryByText('Configuring Full Screen')).toBeNull();
});
it('opens modal when menu item is clicked', async () => {
const { findByText, getByText } = render(<SUT />);
const menuItem = getByText('Full Screen');
fireEvent.click(menuItem);
await findByText('Configuring Full Screen');
});
it('shows open modal per default if `open` prop is `true`', () => {
const { getByText } = render(<SUT show />);
expect(getByText('Configuring Full Screen')).not.toBeNull();
});
it('shows all query titles in modal', () => {
const viewWithQueries = createViewWithQueries();
const { getByText } = render(<SUT view={viewWithQueries} show />);
expect(getByText('Page#1')).not.toBeNull();
expect(getByText('My awesome Query tab')).not.toBeNull();
expect(getByText('Page#3')).not.toBeNull();
});
it('should not allow strings for the refresh interval', () => {
const { getByLabelText } = render(<SUT show />);
const refreshInterval = asElement(getByLabelText('Refresh Interval'), HTMLInputElement);
fireEvent.change(refreshInterval, { target: { value: 'a string' } });
expect(refreshInterval.value).toBe('');
});
it('should not allow strings for the cycle interval', () => {
const { getByLabelText } = render(<SUT show />);
const cycleInterval = asElement(getByLabelText('Tab cycle interval'), HTMLInputElement);
fireEvent.change(cycleInterval, { target: { value: 'a string' } });
expect(cycleInterval.value).toBe('');
});
describe('redirects to tv mode page', () => {
beforeEach(() => {
history.push = jest.fn();
Routes.pluginRoute = jest.fn(() => (viewId) => `/dashboards/tv/${viewId}`);
});
it('on form submit', () => {
const { getByTestId } = render(<SUT show />);
const form = getByTestId('modal-form');
expect(form).not.toBeNull();
fireEvent.submit(form);
expect(Routes.pluginRoute).toHaveBeenCalledWith('DASHBOARDS_TV_VIEWID');
expect(history.push).toHaveBeenCalledWith('/dashboards/tv/deadbeef?interval=30&refresh=10');
});
it('including changed refresh interval', () => {
const { getByLabelText, getByTestId } = render(<SUT show />);
const refreshInterval = getByLabelText('Refresh Interval');
fireEvent.change(refreshInterval, { target: { value: 42 } });
const form = getByTestId('modal-form');
fireEvent.submit(form);
expect(Routes.pluginRoute).toHaveBeenCalledWith('DASHBOARDS_TV_VIEWID');
expect(history.push).toHaveBeenCalledWith('/dashboards/tv/deadbeef?interval=30&refresh=42');
});
it('including tab cycle interval setting', () => {
const { getByLabelText, getByTestId } = render(<SUT show />);
const cycleInterval = getByLabelText('Tab cycle interval');
fireEvent.change(cycleInterval, { target: { value: 4242 } });
const form = getByTestId('modal-form');
fireEvent.submit(form);
expect(Routes.pluginRoute).toHaveBeenCalledWith('DASHBOARDS_TV_VIEWID');
expect(history.push).toHaveBeenCalledWith('/dashboards/tv/deadbeef?interval=4242&refresh=10');
}); | it('including selected tabs', () => {
const viewWithQueries = createViewWithQueries();
const { getByLabelText, getByTestId } = render(<SUT view={viewWithQueries} show />);
const query1 = getByLabelText('Page#1');
fireEvent.click(query1);
const form = getByTestId('modal-form');
fireEvent.submit(form);
expect(Routes.pluginRoute).toHaveBeenCalledWith('DASHBOARDS_TV_VIEWID');
expect(history.push).toHaveBeenCalledWith('/dashboards/tv/deadbeef?interval=30&refresh=10&tabs=1%2C2');
});
});
}); | random_line_split | |
application_common.ts | import {FORM_BINDINGS} from 'angular2/src/core/forms';
import {bind, Binding, Injector, OpaqueToken} from 'angular2/src/core/di';
import {
NumberWrapper,
Type,
isBlank,
isPresent,
assertionsEnabled,
print,
stringify
} from 'angular2/src/core/facade/lang';
import {BrowserDomAdapter} from 'angular2/src/core/dom/browser_adapter';
import {BrowserGetTestability} from 'angular2/src/core/testability/browser_testability';
import {DOM} from 'angular2/src/core/dom/dom_adapter';
import {ViewLoader} from 'angular2/src/core/render/dom/compiler/view_loader';
import {StyleInliner} from 'angular2/src/core/render/dom/compiler/style_inliner';
import {Promise, PromiseWrapper, PromiseCompleter} from 'angular2/src/core/facade/async';
import {XHR} from 'angular2/src/core/render/xhr';
import {XHRImpl} from 'angular2/src/core/render/xhr_impl';
import {
EventManager,
DomEventsPlugin,
EVENT_MANAGER_PLUGINS
} from 'angular2/src/core/render/dom/events/event_manager';
import {KeyEventsPlugin} from 'angular2/src/core/render/dom/events/key_events';
import {HammerGesturesPlugin} from 'angular2/src/core/render/dom/events/hammer_gestures';
import {AppRootUrl} from 'angular2/src/core/services/app_root_url';
import {AnchorBasedAppRootUrl} from 'angular2/src/core/services/anchor_based_app_root_url';
import {
ComponentRef,
DynamicComponentLoader
} from 'angular2/src/core/compiler/dynamic_component_loader';
import {TestabilityRegistry, Testability} from 'angular2/src/core/testability/testability';
import {Renderer, RenderCompiler} from 'angular2/src/core/render/api';
import {
DomRenderer,
DOCUMENT,
DefaultDomCompiler,
APP_ID_RANDOM_BINDING,
MAX_IN_MEMORY_ELEMENTS_PER_TEMPLATE,
TemplateCloner
} from 'angular2/src/core/render/render';
import {ElementSchemaRegistry} from 'angular2/src/core/render/dom/schema/element_schema_registry';
import {
DomElementSchemaRegistry
} from 'angular2/src/core/render/dom/schema/dom_element_schema_registry';
import {
SharedStylesHost,
DomSharedStylesHost
} from 'angular2/src/core/render/dom/view/shared_styles_host';
import {EXCEPTION_BINDING} from './platform_bindings';
import {AnimationBuilder} from 'angular2/src/animate/animation_builder';
import {BrowserDetails} from 'angular2/src/animate/browser_details';
import {wtfInit} from './profile/wtf_init';
import {platformCommon, PlatformRef, applicationCommonBindings} from './application_ref';
/**
* A default set of bindings which apply only to an Angular application running on
* the UI thread.
*/
export function applicationDomBindings(): Array<Type | Binding | any[]> {
if (isBlank(DOM)) |
return [
bind(DOCUMENT)
.toValue(DOM.defaultDoc()),
EventManager,
new Binding(EVENT_MANAGER_PLUGINS, {toClass: DomEventsPlugin, multi: true}),
new Binding(EVENT_MANAGER_PLUGINS, {toClass: KeyEventsPlugin, multi: true}),
new Binding(EVENT_MANAGER_PLUGINS, {toClass: HammerGesturesPlugin, multi: true}),
DomRenderer,
bind(Renderer).toAlias(DomRenderer),
APP_ID_RANDOM_BINDING,
TemplateCloner,
bind(MAX_IN_MEMORY_ELEMENTS_PER_TEMPLATE).toValue(20),
DefaultDomCompiler,
bind(ElementSchemaRegistry).toValue(new DomElementSchemaRegistry()),
bind(RenderCompiler).toAlias(DefaultDomCompiler),
DomSharedStylesHost,
bind(SharedStylesHost).toAlias(DomSharedStylesHost),
ViewLoader,
EXCEPTION_BINDING,
bind(XHR).toValue(new XHRImpl()),
StyleInliner,
Testability,
AnchorBasedAppRootUrl,
bind(AppRootUrl).toAlias(AnchorBasedAppRootUrl),
BrowserDetails,
AnimationBuilder,
FORM_BINDINGS
];
}
/**
* Initialize the Angular 'platform' on the page.
*
* See {@link PlatformRef} for details on the Angular platform.
*
* # Without specified bindings
*
* If no bindings are specified, `platform`'s behavior depends on whether an existing
* platform exists:
*
* If no platform exists, a new one will be created with the default {@link platformBindings}.
*
* If a platform already exists, it will be returned (regardless of what bindings it
* was created with). This is a convenience feature, allowing for multiple applications
* to be loaded into the same platform without awareness of each other.
*
* # With specified bindings
*
* It is also possible to specify bindings to be made in the new platform. These bindings
* will be shared between all applications on the page. For example, an abstraction for
* the browser cookie jar should be bound at the platform level, because there is only one
* cookie jar regardless of how many applications on the age will be accessing it.
*
* If bindings are specified directly, `platform` will create the Angular platform with
* them if a platform did not exist already. If it did exist, however, an error will be
* thrown.
*
* # DOM Applications
*
* This version of `platform` initializes Angular to run in the UI thread, with direct
* DOM access. Web-worker applications should call `platform` from
* `src/web_workers/worker/application_common` instead.
*/
export function platform(bindings?: Array<Type | Binding | any[]>): PlatformRef {
return platformCommon(bindings, () => {
BrowserDomAdapter.makeCurrent();
wtfInit();
BrowserGetTestability.init();
});
}
/**
* Bootstrapping for Angular applications.
*
* You instantiate an Angular application by explicitly specifying a component to use
* as the root component for your application via the `bootstrap()` method.
*
* ## Simple Example
*
* Assuming this `index.html`:
*
* ```html
* <html>
* <!-- load Angular script tags here. -->
* <body>
* <my-app>loading...</my-app>
* </body>
* </html>
* ```
*
* An application is bootstrapped inside an existing browser DOM, typically `index.html`.
* Unlike Angular 1, Angular 2 does not compile/process bindings in `index.html`. This is
* mainly for security reasons, as well as architectural changes in Angular 2. This means
* that `index.html` can safely be processed using server-side technologies such as
* bindings. Bindings can thus use double-curly `{{ syntax }}` without collision from
* Angular 2 component double-curly `{{ syntax }}`.
*
* We can use this script code:
*
* ```
* @Component({
* selector: 'my-app'
* })
* @View({
* template: 'Hello {{ name }}!'
* })
* class MyApp {
* name:string;
*
* constructor() {
* this.name = 'World';
* }
* }
*
* main() {
* return bootstrap(MyApp);
* }
* ```
*
* When the app developer invokes `bootstrap()` with the root component `MyApp` as its
* argument, Angular performs the following tasks:
*
* 1. It uses the component's `selector` property to locate the DOM element which needs
* to be upgraded into the angular component.
* 2. It creates a new child injector (from the platform injector). Optionally, you can
* also override the injector configuration for an app by invoking `bootstrap` with the
* `componentInjectableBindings` argument.
* 3. It creates a new `Zone` and connects it to the angular application's change detection
* domain instance.
* 4. It creates a shadow DOM on the selected component's host element and loads the
* template into it.
* 5. It instantiates the specified component.
* 6. Finally, Angular performs change detection to apply the initial data bindings for the
* application.
*
*
* ## Instantiating Multiple Applications on a Single Page
*
* There are two ways to do this.
*
* ### Isolated Applications
*
* Angular creates a new application each time that the `bootstrap()` method is invoked.
* When multiple applications are created for a page, Angular treats each application as
* independent within an isolated change detection and `Zone` domain. If you need to share
* data between applications, use the strategy described in the next section, "Applications
* That Share Change Detection."
*
*
* ### Applications That Share Change Detection
*
* If you need to bootstrap multiple applications that share common data, the applications
* must share a common change detection and zone. To do that, create a meta-component that
* lists the application components in its template.
*
* By only invoking the `bootstrap()` method once, with the meta-component as its argument,
* you ensure that only a single change detection zone is created and therefore data can be
* shared across the applications.
*
*
* ## Platform Injector
*
* When working within a browser window, there are many singleton resources: cookies, title,
* location, and others. Angular services that represent these resources must likewise be
* shared across all Angular applications that occupy the same browser window. For this
* reason, Angular creates exactly one global platform injector which stores all shared
* services, and each angular application injector has the platform injector as its parent.
*
* Each application has its own private injector as well. When there are multipl
* applications on a page, Angular treats each application injector's services as private
* to that application.
*
*
* # API
* - `appComponentType`: The root component which should act as the application. This is
* a reference to a `Type` which is annotated with `@Component(...)`.
* - `componentInjectableBindings`: An additional set of bindings that can be added to the
* app injector to override default injection behavior.
* - `errorReporter`: `function(exception:any, stackTrace:string)` a default error reporter
* for unhandled exceptions.
*
* Returns a `Promise` of {@link ComponentRef}.
*/
export function commonBootstrap(appComponentType: /*Type*/ any,
appBindings: Array<Type | Binding | any[]> = null):
Promise<ComponentRef> {
var p = platform();
var bindings = [applicationCommonBindings(), applicationDomBindings()];
if (isPresent(appBindings)) {
bindings.push(appBindings);
}
return p.application(bindings).bootstrap(appComponentType);
}
| {
throw "Must set a root DOM adapter first.";
} | conditional_block |
application_common.ts | import {FORM_BINDINGS} from 'angular2/src/core/forms';
import {bind, Binding, Injector, OpaqueToken} from 'angular2/src/core/di';
import {
NumberWrapper,
Type,
isBlank,
isPresent,
assertionsEnabled,
print,
stringify
} from 'angular2/src/core/facade/lang';
import {BrowserDomAdapter} from 'angular2/src/core/dom/browser_adapter';
import {BrowserGetTestability} from 'angular2/src/core/testability/browser_testability';
import {DOM} from 'angular2/src/core/dom/dom_adapter';
import {ViewLoader} from 'angular2/src/core/render/dom/compiler/view_loader';
import {StyleInliner} from 'angular2/src/core/render/dom/compiler/style_inliner';
import {Promise, PromiseWrapper, PromiseCompleter} from 'angular2/src/core/facade/async';
import {XHR} from 'angular2/src/core/render/xhr';
import {XHRImpl} from 'angular2/src/core/render/xhr_impl';
import {
EventManager,
DomEventsPlugin,
EVENT_MANAGER_PLUGINS
} from 'angular2/src/core/render/dom/events/event_manager';
import {KeyEventsPlugin} from 'angular2/src/core/render/dom/events/key_events';
import {HammerGesturesPlugin} from 'angular2/src/core/render/dom/events/hammer_gestures';
import {AppRootUrl} from 'angular2/src/core/services/app_root_url';
import {AnchorBasedAppRootUrl} from 'angular2/src/core/services/anchor_based_app_root_url';
import {
ComponentRef,
DynamicComponentLoader
} from 'angular2/src/core/compiler/dynamic_component_loader';
import {TestabilityRegistry, Testability} from 'angular2/src/core/testability/testability';
import {Renderer, RenderCompiler} from 'angular2/src/core/render/api';
import {
DomRenderer,
DOCUMENT,
DefaultDomCompiler,
APP_ID_RANDOM_BINDING,
MAX_IN_MEMORY_ELEMENTS_PER_TEMPLATE,
TemplateCloner
} from 'angular2/src/core/render/render';
import {ElementSchemaRegistry} from 'angular2/src/core/render/dom/schema/element_schema_registry';
import {
DomElementSchemaRegistry
} from 'angular2/src/core/render/dom/schema/dom_element_schema_registry';
import {
SharedStylesHost,
DomSharedStylesHost
} from 'angular2/src/core/render/dom/view/shared_styles_host';
import {EXCEPTION_BINDING} from './platform_bindings';
import {AnimationBuilder} from 'angular2/src/animate/animation_builder';
import {BrowserDetails} from 'angular2/src/animate/browser_details';
import {wtfInit} from './profile/wtf_init';
import {platformCommon, PlatformRef, applicationCommonBindings} from './application_ref';
/**
* A default set of bindings which apply only to an Angular application running on
* the UI thread.
*/
export function applicationDomBindings(): Array<Type | Binding | any[]> {
if (isBlank(DOM)) {
throw "Must set a root DOM adapter first.";
}
return [
bind(DOCUMENT)
.toValue(DOM.defaultDoc()),
EventManager,
new Binding(EVENT_MANAGER_PLUGINS, {toClass: DomEventsPlugin, multi: true}),
new Binding(EVENT_MANAGER_PLUGINS, {toClass: KeyEventsPlugin, multi: true}),
new Binding(EVENT_MANAGER_PLUGINS, {toClass: HammerGesturesPlugin, multi: true}),
DomRenderer,
bind(Renderer).toAlias(DomRenderer),
APP_ID_RANDOM_BINDING,
TemplateCloner,
bind(MAX_IN_MEMORY_ELEMENTS_PER_TEMPLATE).toValue(20),
DefaultDomCompiler,
bind(ElementSchemaRegistry).toValue(new DomElementSchemaRegistry()),
bind(RenderCompiler).toAlias(DefaultDomCompiler),
DomSharedStylesHost,
bind(SharedStylesHost).toAlias(DomSharedStylesHost),
ViewLoader,
EXCEPTION_BINDING,
bind(XHR).toValue(new XHRImpl()),
StyleInliner,
Testability,
AnchorBasedAppRootUrl,
bind(AppRootUrl).toAlias(AnchorBasedAppRootUrl),
BrowserDetails,
AnimationBuilder,
FORM_BINDINGS
];
}
/**
* Initialize the Angular 'platform' on the page.
*
* See {@link PlatformRef} for details on the Angular platform.
*
* # Without specified bindings
*
* If no bindings are specified, `platform`'s behavior depends on whether an existing
* platform exists:
*
* If no platform exists, a new one will be created with the default {@link platformBindings}.
*
* If a platform already exists, it will be returned (regardless of what bindings it
* was created with). This is a convenience feature, allowing for multiple applications
* to be loaded into the same platform without awareness of each other.
*
* # With specified bindings
*
* It is also possible to specify bindings to be made in the new platform. These bindings
* will be shared between all applications on the page. For example, an abstraction for
* the browser cookie jar should be bound at the platform level, because there is only one
* cookie jar regardless of how many applications on the age will be accessing it.
*
* If bindings are specified directly, `platform` will create the Angular platform with
* them if a platform did not exist already. If it did exist, however, an error will be
* thrown.
*
* # DOM Applications
*
* This version of `platform` initializes Angular to run in the UI thread, with direct
* DOM access. Web-worker applications should call `platform` from
* `src/web_workers/worker/application_common` instead.
*/
export function platform(bindings?: Array<Type | Binding | any[]>): PlatformRef {
return platformCommon(bindings, () => {
BrowserDomAdapter.makeCurrent();
wtfInit();
BrowserGetTestability.init();
});
}
/**
* Bootstrapping for Angular applications.
*
* You instantiate an Angular application by explicitly specifying a component to use
* as the root component for your application via the `bootstrap()` method.
*
* ## Simple Example
*
* Assuming this `index.html`:
*
* ```html
* <html>
* <!-- load Angular script tags here. -->
* <body>
* <my-app>loading...</my-app>
* </body>
* </html>
* ```
*
* An application is bootstrapped inside an existing browser DOM, typically `index.html`.
* Unlike Angular 1, Angular 2 does not compile/process bindings in `index.html`. This is
* mainly for security reasons, as well as architectural changes in Angular 2. This means
* that `index.html` can safely be processed using server-side technologies such as
* bindings. Bindings can thus use double-curly `{{ syntax }}` without collision from
* Angular 2 component double-curly `{{ syntax }}`.
*
* We can use this script code:
*
* ```
* @Component({
* selector: 'my-app'
* })
* @View({
* template: 'Hello {{ name }}!'
* })
* class MyApp {
* name:string;
*
* constructor() {
* this.name = 'World';
* }
* }
*
* main() {
* return bootstrap(MyApp);
* }
* ```
*
* When the app developer invokes `bootstrap()` with the root component `MyApp` as its
* argument, Angular performs the following tasks:
*
* 1. It uses the component's `selector` property to locate the DOM element which needs
* to be upgraded into the angular component.
* 2. It creates a new child injector (from the platform injector). Optionally, you can
* also override the injector configuration for an app by invoking `bootstrap` with the
* `componentInjectableBindings` argument.
* 3. It creates a new `Zone` and connects it to the angular application's change detection
* domain instance.
* 4. It creates a shadow DOM on the selected component's host element and loads the
* template into it.
* 5. It instantiates the specified component.
* 6. Finally, Angular performs change detection to apply the initial data bindings for the
* application.
*
*
* ## Instantiating Multiple Applications on a Single Page
*
* There are two ways to do this.
*
* ### Isolated Applications
*
* Angular creates a new application each time that the `bootstrap()` method is invoked.
* When multiple applications are created for a page, Angular treats each application as
* independent within an isolated change detection and `Zone` domain. If you need to share
* data between applications, use the strategy described in the next section, "Applications
* That Share Change Detection."
*
*
* ### Applications That Share Change Detection
*
* If you need to bootstrap multiple applications that share common data, the applications
* must share a common change detection and zone. To do that, create a meta-component that
* lists the application components in its template.
*
* By only invoking the `bootstrap()` method once, with the meta-component as its argument,
* you ensure that only a single change detection zone is created and therefore data can be
* shared across the applications.
*
*
* ## Platform Injector
*
* When working within a browser window, there are many singleton resources: cookies, title,
* location, and others. Angular services that represent these resources must likewise be
* shared across all Angular applications that occupy the same browser window. For this
* reason, Angular creates exactly one global platform injector which stores all shared
* services, and each angular application injector has the platform injector as its parent.
*
* Each application has its own private injector as well. When there are multipl
* applications on a page, Angular treats each application injector's services as private
* to that application.
*
*
* # API
* - `appComponentType`: The root component which should act as the application. This is
* a reference to a `Type` which is annotated with `@Component(...)`.
* - `componentInjectableBindings`: An additional set of bindings that can be added to the
* app injector to override default injection behavior.
* - `errorReporter`: `function(exception:any, stackTrace:string)` a default error reporter
* for unhandled exceptions.
*
* Returns a `Promise` of {@link ComponentRef}.
*/
export function commonBootstrap(appComponentType: /*Type*/ any,
appBindings: Array<Type | Binding | any[]> = null):
Promise<ComponentRef> | {
var p = platform();
var bindings = [applicationCommonBindings(), applicationDomBindings()];
if (isPresent(appBindings)) {
bindings.push(appBindings);
}
return p.application(bindings).bootstrap(appComponentType);
} | identifier_body | |
application_common.ts | import {FORM_BINDINGS} from 'angular2/src/core/forms';
import {bind, Binding, Injector, OpaqueToken} from 'angular2/src/core/di';
import {
NumberWrapper,
Type,
isBlank,
isPresent,
assertionsEnabled,
print,
stringify
} from 'angular2/src/core/facade/lang';
import {BrowserDomAdapter} from 'angular2/src/core/dom/browser_adapter';
import {BrowserGetTestability} from 'angular2/src/core/testability/browser_testability';
import {DOM} from 'angular2/src/core/dom/dom_adapter';
import {ViewLoader} from 'angular2/src/core/render/dom/compiler/view_loader';
import {StyleInliner} from 'angular2/src/core/render/dom/compiler/style_inliner';
import {Promise, PromiseWrapper, PromiseCompleter} from 'angular2/src/core/facade/async';
import {XHR} from 'angular2/src/core/render/xhr';
import {XHRImpl} from 'angular2/src/core/render/xhr_impl';
import {
EventManager,
DomEventsPlugin,
EVENT_MANAGER_PLUGINS
} from 'angular2/src/core/render/dom/events/event_manager';
import {KeyEventsPlugin} from 'angular2/src/core/render/dom/events/key_events';
import {HammerGesturesPlugin} from 'angular2/src/core/render/dom/events/hammer_gestures';
import {AppRootUrl} from 'angular2/src/core/services/app_root_url';
import {AnchorBasedAppRootUrl} from 'angular2/src/core/services/anchor_based_app_root_url';
import {
ComponentRef,
DynamicComponentLoader
} from 'angular2/src/core/compiler/dynamic_component_loader';
import {TestabilityRegistry, Testability} from 'angular2/src/core/testability/testability';
import {Renderer, RenderCompiler} from 'angular2/src/core/render/api';
import {
DomRenderer,
DOCUMENT,
DefaultDomCompiler,
APP_ID_RANDOM_BINDING,
MAX_IN_MEMORY_ELEMENTS_PER_TEMPLATE,
TemplateCloner
} from 'angular2/src/core/render/render';
import {ElementSchemaRegistry} from 'angular2/src/core/render/dom/schema/element_schema_registry';
import {
DomElementSchemaRegistry
} from 'angular2/src/core/render/dom/schema/dom_element_schema_registry';
import {
SharedStylesHost,
DomSharedStylesHost
} from 'angular2/src/core/render/dom/view/shared_styles_host';
import {EXCEPTION_BINDING} from './platform_bindings';
import {AnimationBuilder} from 'angular2/src/animate/animation_builder';
import {BrowserDetails} from 'angular2/src/animate/browser_details';
import {wtfInit} from './profile/wtf_init';
import {platformCommon, PlatformRef, applicationCommonBindings} from './application_ref';
/**
* A default set of bindings which apply only to an Angular application running on
* the UI thread.
*/
export function applicationDomBindings(): Array<Type | Binding | any[]> {
if (isBlank(DOM)) {
throw "Must set a root DOM adapter first.";
}
return [
bind(DOCUMENT)
.toValue(DOM.defaultDoc()),
EventManager,
new Binding(EVENT_MANAGER_PLUGINS, {toClass: DomEventsPlugin, multi: true}),
new Binding(EVENT_MANAGER_PLUGINS, {toClass: KeyEventsPlugin, multi: true}),
new Binding(EVENT_MANAGER_PLUGINS, {toClass: HammerGesturesPlugin, multi: true}),
DomRenderer,
bind(Renderer).toAlias(DomRenderer),
APP_ID_RANDOM_BINDING,
TemplateCloner,
bind(MAX_IN_MEMORY_ELEMENTS_PER_TEMPLATE).toValue(20),
DefaultDomCompiler,
bind(ElementSchemaRegistry).toValue(new DomElementSchemaRegistry()),
bind(RenderCompiler).toAlias(DefaultDomCompiler),
DomSharedStylesHost,
bind(SharedStylesHost).toAlias(DomSharedStylesHost),
ViewLoader,
EXCEPTION_BINDING,
bind(XHR).toValue(new XHRImpl()),
StyleInliner,
Testability,
AnchorBasedAppRootUrl,
bind(AppRootUrl).toAlias(AnchorBasedAppRootUrl),
BrowserDetails,
AnimationBuilder,
FORM_BINDINGS
];
}
/**
* Initialize the Angular 'platform' on the page.
*
* See {@link PlatformRef} for details on the Angular platform.
*
* # Without specified bindings
*
* If no bindings are specified, `platform`'s behavior depends on whether an existing
* platform exists:
*
* If no platform exists, a new one will be created with the default {@link platformBindings}.
*
* If a platform already exists, it will be returned (regardless of what bindings it
* was created with). This is a convenience feature, allowing for multiple applications
* to be loaded into the same platform without awareness of each other.
*
* # With specified bindings
*
* It is also possible to specify bindings to be made in the new platform. These bindings
* will be shared between all applications on the page. For example, an abstraction for
* the browser cookie jar should be bound at the platform level, because there is only one
* cookie jar regardless of how many applications on the age will be accessing it.
*
* If bindings are specified directly, `platform` will create the Angular platform with
* them if a platform did not exist already. If it did exist, however, an error will be
* thrown.
*
* # DOM Applications
*
* This version of `platform` initializes Angular to run in the UI thread, with direct
* DOM access. Web-worker applications should call `platform` from
* `src/web_workers/worker/application_common` instead.
*/
export function platform(bindings?: Array<Type | Binding | any[]>): PlatformRef {
return platformCommon(bindings, () => {
BrowserDomAdapter.makeCurrent();
wtfInit();
BrowserGetTestability.init();
});
}
/**
* Bootstrapping for Angular applications.
*
* You instantiate an Angular application by explicitly specifying a component to use
* as the root component for your application via the `bootstrap()` method.
*
* ## Simple Example
*
* Assuming this `index.html`:
*
* ```html
* <html>
* <!-- load Angular script tags here. -->
* <body>
* <my-app>loading...</my-app>
* </body>
* </html>
* ```
*
* An application is bootstrapped inside an existing browser DOM, typically `index.html`.
* Unlike Angular 1, Angular 2 does not compile/process bindings in `index.html`. This is
* mainly for security reasons, as well as architectural changes in Angular 2. This means
* that `index.html` can safely be processed using server-side technologies such as
* bindings. Bindings can thus use double-curly `{{ syntax }}` without collision from
* Angular 2 component double-curly `{{ syntax }}`.
*
* We can use this script code:
*
* ```
* @Component({
* selector: 'my-app'
* })
* @View({
* template: 'Hello {{ name }}!'
* })
* class MyApp {
* name:string;
*
* constructor() {
* this.name = 'World';
* }
* }
*
* main() {
* return bootstrap(MyApp);
* }
* ```
*
* When the app developer invokes `bootstrap()` with the root component `MyApp` as its
* argument, Angular performs the following tasks:
*
* 1. It uses the component's `selector` property to locate the DOM element which needs
* to be upgraded into the angular component.
* 2. It creates a new child injector (from the platform injector). Optionally, you can
* also override the injector configuration for an app by invoking `bootstrap` with the
* `componentInjectableBindings` argument.
* 3. It creates a new `Zone` and connects it to the angular application's change detection
* domain instance.
* 4. It creates a shadow DOM on the selected component's host element and loads the
* template into it.
* 5. It instantiates the specified component.
* 6. Finally, Angular performs change detection to apply the initial data bindings for the
* application.
*
*
* ## Instantiating Multiple Applications on a Single Page
*
* There are two ways to do this.
*
* ### Isolated Applications
*
* Angular creates a new application each time that the `bootstrap()` method is invoked.
* When multiple applications are created for a page, Angular treats each application as
* independent within an isolated change detection and `Zone` domain. If you need to share
* data between applications, use the strategy described in the next section, "Applications
* That Share Change Detection."
*
*
* ### Applications That Share Change Detection
*
* If you need to bootstrap multiple applications that share common data, the applications
* must share a common change detection and zone. To do that, create a meta-component that
* lists the application components in its template.
*
* By only invoking the `bootstrap()` method once, with the meta-component as its argument,
* you ensure that only a single change detection zone is created and therefore data can be
* shared across the applications.
*
*
* ## Platform Injector
*
* When working within a browser window, there are many singleton resources: cookies, title,
* location, and others. Angular services that represent these resources must likewise be
* shared across all Angular applications that occupy the same browser window. For this
* reason, Angular creates exactly one global platform injector which stores all shared
* services, and each angular application injector has the platform injector as its parent.
*
* Each application has its own private injector as well. When there are multipl
* applications on a page, Angular treats each application injector's services as private
* to that application.
*
*
* # API
* - `appComponentType`: The root component which should act as the application. This is
* a reference to a `Type` which is annotated with `@Component(...)`.
* - `componentInjectableBindings`: An additional set of bindings that can be added to the
* app injector to override default injection behavior.
* - `errorReporter`: `function(exception:any, stackTrace:string)` a default error reporter
* for unhandled exceptions.
*
* Returns a `Promise` of {@link ComponentRef}.
*/
export function | (appComponentType: /*Type*/ any,
appBindings: Array<Type | Binding | any[]> = null):
Promise<ComponentRef> {
var p = platform();
var bindings = [applicationCommonBindings(), applicationDomBindings()];
if (isPresent(appBindings)) {
bindings.push(appBindings);
}
return p.application(bindings).bootstrap(appComponentType);
}
| commonBootstrap | identifier_name |
application_common.ts | import {FORM_BINDINGS} from 'angular2/src/core/forms';
import {bind, Binding, Injector, OpaqueToken} from 'angular2/src/core/di';
import {
NumberWrapper,
Type,
isBlank,
isPresent,
assertionsEnabled,
print,
stringify
} from 'angular2/src/core/facade/lang';
import {BrowserDomAdapter} from 'angular2/src/core/dom/browser_adapter';
import {BrowserGetTestability} from 'angular2/src/core/testability/browser_testability';
import {DOM} from 'angular2/src/core/dom/dom_adapter';
import {ViewLoader} from 'angular2/src/core/render/dom/compiler/view_loader';
import {StyleInliner} from 'angular2/src/core/render/dom/compiler/style_inliner';
import {Promise, PromiseWrapper, PromiseCompleter} from 'angular2/src/core/facade/async';
import {XHR} from 'angular2/src/core/render/xhr';
import {XHRImpl} from 'angular2/src/core/render/xhr_impl';
import {
EventManager,
DomEventsPlugin,
EVENT_MANAGER_PLUGINS
} from 'angular2/src/core/render/dom/events/event_manager';
import {KeyEventsPlugin} from 'angular2/src/core/render/dom/events/key_events';
import {HammerGesturesPlugin} from 'angular2/src/core/render/dom/events/hammer_gestures';
import {AppRootUrl} from 'angular2/src/core/services/app_root_url';
import {AnchorBasedAppRootUrl} from 'angular2/src/core/services/anchor_based_app_root_url';
import {
ComponentRef,
DynamicComponentLoader
} from 'angular2/src/core/compiler/dynamic_component_loader';
import {TestabilityRegistry, Testability} from 'angular2/src/core/testability/testability';
import {Renderer, RenderCompiler} from 'angular2/src/core/render/api';
import {
DomRenderer,
DOCUMENT,
DefaultDomCompiler,
APP_ID_RANDOM_BINDING,
MAX_IN_MEMORY_ELEMENTS_PER_TEMPLATE,
TemplateCloner
} from 'angular2/src/core/render/render';
import {ElementSchemaRegistry} from 'angular2/src/core/render/dom/schema/element_schema_registry';
import {
DomElementSchemaRegistry
} from 'angular2/src/core/render/dom/schema/dom_element_schema_registry';
import {
SharedStylesHost,
DomSharedStylesHost
} from 'angular2/src/core/render/dom/view/shared_styles_host';
import {EXCEPTION_BINDING} from './platform_bindings';
import {AnimationBuilder} from 'angular2/src/animate/animation_builder';
import {BrowserDetails} from 'angular2/src/animate/browser_details';
import {wtfInit} from './profile/wtf_init';
import {platformCommon, PlatformRef, applicationCommonBindings} from './application_ref';
/**
* A default set of bindings which apply only to an Angular application running on
* the UI thread.
*/
export function applicationDomBindings(): Array<Type | Binding | any[]> {
if (isBlank(DOM)) {
throw "Must set a root DOM adapter first.";
}
return [
bind(DOCUMENT)
.toValue(DOM.defaultDoc()),
EventManager,
new Binding(EVENT_MANAGER_PLUGINS, {toClass: DomEventsPlugin, multi: true}),
new Binding(EVENT_MANAGER_PLUGINS, {toClass: KeyEventsPlugin, multi: true}),
new Binding(EVENT_MANAGER_PLUGINS, {toClass: HammerGesturesPlugin, multi: true}),
DomRenderer,
bind(Renderer).toAlias(DomRenderer),
APP_ID_RANDOM_BINDING,
TemplateCloner,
bind(MAX_IN_MEMORY_ELEMENTS_PER_TEMPLATE).toValue(20),
DefaultDomCompiler,
bind(ElementSchemaRegistry).toValue(new DomElementSchemaRegistry()),
bind(RenderCompiler).toAlias(DefaultDomCompiler),
DomSharedStylesHost,
bind(SharedStylesHost).toAlias(DomSharedStylesHost),
ViewLoader,
EXCEPTION_BINDING,
bind(XHR).toValue(new XHRImpl()),
StyleInliner,
Testability,
AnchorBasedAppRootUrl,
bind(AppRootUrl).toAlias(AnchorBasedAppRootUrl),
BrowserDetails,
AnimationBuilder,
FORM_BINDINGS
];
}
/**
* Initialize the Angular 'platform' on the page.
*
* See {@link PlatformRef} for details on the Angular platform.
*
* # Without specified bindings
*
* If no bindings are specified, `platform`'s behavior depends on whether an existing
* platform exists:
*
* If no platform exists, a new one will be created with the default {@link platformBindings}.
*
* If a platform already exists, it will be returned (regardless of what bindings it
* was created with). This is a convenience feature, allowing for multiple applications
* to be loaded into the same platform without awareness of each other.
*
* # With specified bindings
*
* It is also possible to specify bindings to be made in the new platform. These bindings
* will be shared between all applications on the page. For example, an abstraction for
* the browser cookie jar should be bound at the platform level, because there is only one
* cookie jar regardless of how many applications on the age will be accessing it.
*
* If bindings are specified directly, `platform` will create the Angular platform with
* them if a platform did not exist already. If it did exist, however, an error will be
* thrown.
*
* # DOM Applications
*
* This version of `platform` initializes Angular to run in the UI thread, with direct
* DOM access. Web-worker applications should call `platform` from
* `src/web_workers/worker/application_common` instead.
*/
export function platform(bindings?: Array<Type | Binding | any[]>): PlatformRef {
return platformCommon(bindings, () => {
BrowserDomAdapter.makeCurrent();
wtfInit();
BrowserGetTestability.init();
});
}
/**
* Bootstrapping for Angular applications.
* | *
* ## Simple Example
*
* Assuming this `index.html`:
*
* ```html
* <html>
* <!-- load Angular script tags here. -->
* <body>
* <my-app>loading...</my-app>
* </body>
* </html>
* ```
*
* An application is bootstrapped inside an existing browser DOM, typically `index.html`.
* Unlike Angular 1, Angular 2 does not compile/process bindings in `index.html`. This is
* mainly for security reasons, as well as architectural changes in Angular 2. This means
* that `index.html` can safely be processed using server-side technologies such as
* bindings. Bindings can thus use double-curly `{{ syntax }}` without collision from
* Angular 2 component double-curly `{{ syntax }}`.
*
* We can use this script code:
*
* ```
* @Component({
* selector: 'my-app'
* })
* @View({
* template: 'Hello {{ name }}!'
* })
* class MyApp {
* name:string;
*
* constructor() {
* this.name = 'World';
* }
* }
*
* main() {
* return bootstrap(MyApp);
* }
* ```
*
* When the app developer invokes `bootstrap()` with the root component `MyApp` as its
* argument, Angular performs the following tasks:
*
* 1. It uses the component's `selector` property to locate the DOM element which needs
* to be upgraded into the angular component.
* 2. It creates a new child injector (from the platform injector). Optionally, you can
* also override the injector configuration for an app by invoking `bootstrap` with the
* `componentInjectableBindings` argument.
* 3. It creates a new `Zone` and connects it to the angular application's change detection
* domain instance.
* 4. It creates a shadow DOM on the selected component's host element and loads the
* template into it.
* 5. It instantiates the specified component.
* 6. Finally, Angular performs change detection to apply the initial data bindings for the
* application.
*
*
* ## Instantiating Multiple Applications on a Single Page
*
* There are two ways to do this.
*
* ### Isolated Applications
*
* Angular creates a new application each time that the `bootstrap()` method is invoked.
* When multiple applications are created for a page, Angular treats each application as
* independent within an isolated change detection and `Zone` domain. If you need to share
* data between applications, use the strategy described in the next section, "Applications
* That Share Change Detection."
*
*
* ### Applications That Share Change Detection
*
* If you need to bootstrap multiple applications that share common data, the applications
* must share a common change detection and zone. To do that, create a meta-component that
* lists the application components in its template.
*
* By only invoking the `bootstrap()` method once, with the meta-component as its argument,
* you ensure that only a single change detection zone is created and therefore data can be
* shared across the applications.
*
*
* ## Platform Injector
*
* When working within a browser window, there are many singleton resources: cookies, title,
* location, and others. Angular services that represent these resources must likewise be
* shared across all Angular applications that occupy the same browser window. For this
* reason, Angular creates exactly one global platform injector which stores all shared
* services, and each angular application injector has the platform injector as its parent.
*
* Each application has its own private injector as well. When there are multipl
* applications on a page, Angular treats each application injector's services as private
* to that application.
*
*
* # API
* - `appComponentType`: The root component which should act as the application. This is
* a reference to a `Type` which is annotated with `@Component(...)`.
* - `componentInjectableBindings`: An additional set of bindings that can be added to the
* app injector to override default injection behavior.
* - `errorReporter`: `function(exception:any, stackTrace:string)` a default error reporter
* for unhandled exceptions.
*
* Returns a `Promise` of {@link ComponentRef}.
*/
export function commonBootstrap(appComponentType: /*Type*/ any,
appBindings: Array<Type | Binding | any[]> = null):
Promise<ComponentRef> {
var p = platform();
var bindings = [applicationCommonBindings(), applicationDomBindings()];
if (isPresent(appBindings)) {
bindings.push(appBindings);
}
return p.application(bindings).bootstrap(appComponentType);
} | * You instantiate an Angular application by explicitly specifying a component to use
* as the root component for your application via the `bootstrap()` method. | random_line_split |
ckeditor_link_tags.py | import importlib
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist
from ckeditor_link import conf
from django import template
from django.template.defaultfilters import stringfilter
try:
module_name, class_name = conf.CKEDITOR_LINK_MODEL.rsplit(".", 1)
my_module = importlib.import_module(module_name)
ckeditor_link_class = getattr(my_module, class_name, None)
except ImportError:
ckeditor_link_class = None
register = template.Library()
@register.filter
@stringfilter
def ckeditor_link_add_links(html):
# lxml is not a dependency, but needed for this tag.
| from lxml.html import fragment_fromstring, tostring
if not ckeditor_link_class:
# TODO: use some log thing, or rais ImproperlyConfigured!
if settings.DEBUG:
msg = "Warning: CKEDITOR_LINK_MODEL (%s) could not be imported!?" % (conf.CKEDITOR_LINK_MODEL, )
raise ImproperlyConfigured(msg)
return html
fragment = fragment_fromstring("<div>" + html + "</div>")
links = fragment.cssselect('a')
for link in links:
if link.get('data-ckeditor-link', None):
link.attrib.pop('data-ckeditor-link')
kwargs = {}
dummy_link = ckeditor_link_class()
for key, value in link.items():
if key.startswith('data-'):
new_key = key.replace('data-', '', 1)
# DEPRECATED: use CKEDITOR_LINK_ATTR_MODIFIERS setting!
if new_key == 'page_2':
new_key = 'cms_page' # backward compat, for 0.2.0
if new_key == 'cms_page_2':
new_key = 'cms_page'
# until here
if hasattr(dummy_link, new_key):
if hasattr(dummy_link, new_key + "_id"):
# set fk directly
new_key = new_key + "_id"
if not value:
value = None
kwargs[new_key] = value
link.attrib.pop(key)
for key, formatted_string in conf.CKEDITOR_LINK_ATTR_MODIFIERS.items():
try:
kwargs[key] = formatted_string.format(**kwargs)
except KeyError:
# this is an option, we dont know at all how our link is/was built (ages ago)
pass
try:
# this can go wrong with fk and the like
real_link = ckeditor_link_class(**kwargs)
link.set('href', real_link.get_link())
if getattr(real_link, 'get_link_target', None):
link.set('target', real_link.get_link_target())
if getattr(real_link, 'get_link_style', None):
link.set('class', real_link.get_link_style())
if getattr(real_link, 'get_link_attrs', None):
for attr, value in real_link.get_link_attrs().items():
link.set(attr, value)
except (ValueError, ObjectDoesNotExist):
continue
# arf: http://makble.com/python-why-lxml-etree-tostring-method-returns-bytes
# beautifulsoup to the rescue!
return tostring(fragment, encoding='unicode') | identifier_body | |
ckeditor_link_tags.py | import importlib
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist
from ckeditor_link import conf
from django import template
from django.template.defaultfilters import stringfilter
try:
module_name, class_name = conf.CKEDITOR_LINK_MODEL.rsplit(".", 1)
my_module = importlib.import_module(module_name)
ckeditor_link_class = getattr(my_module, class_name, None)
except ImportError:
ckeditor_link_class = None
register = template.Library()
@register.filter
@stringfilter
def ckeditor_link_add_links(html):
# lxml is not a dependency, but needed for this tag.
from lxml.html import fragment_fromstring, tostring
if not ckeditor_link_class:
# TODO: use some log thing, or rais ImproperlyConfigured!
if settings.DEBUG:
msg = "Warning: CKEDITOR_LINK_MODEL (%s) could not be imported!?" % (conf.CKEDITOR_LINK_MODEL, )
raise ImproperlyConfigured(msg)
return html
fragment = fragment_fromstring("<div>" + html + "</div>")
links = fragment.cssselect('a')
for link in links:
if link.get('data-ckeditor-link', None):
link.attrib.pop('data-ckeditor-link')
kwargs = {}
dummy_link = ckeditor_link_class()
for key, value in link.items():
if key.startswith('data-'):
new_key = key.replace('data-', '', 1)
# DEPRECATED: use CKEDITOR_LINK_ATTR_MODIFIERS setting!
if new_key == 'page_2':
new_key = 'cms_page' # backward compat, for 0.2.0
if new_key == 'cms_page_2':
new_key = 'cms_page'
# until here
if hasattr(dummy_link, new_key):
if hasattr(dummy_link, new_key + "_id"):
# set fk directly
new_key = new_key + "_id"
if not value:
value = None
kwargs[new_key] = value
link.attrib.pop(key)
for key, formatted_string in conf.CKEDITOR_LINK_ATTR_MODIFIERS.items():
try:
kwargs[key] = formatted_string.format(**kwargs)
except KeyError:
# this is an option, we dont know at all how our link is/was built (ages ago)
pass
try:
# this can go wrong with fk and the like
real_link = ckeditor_link_class(**kwargs)
link.set('href', real_link.get_link())
if getattr(real_link, 'get_link_target', None):
link.set('target', real_link.get_link_target())
if getattr(real_link, 'get_link_style', None):
link.set('class', real_link.get_link_style())
if getattr(real_link, 'get_link_attrs', None):
for attr, value in real_link.get_link_attrs().items():
link.set(attr, value)
except (ValueError, ObjectDoesNotExist):
continue | # arf: http://makble.com/python-why-lxml-etree-tostring-method-returns-bytes
# beautifulsoup to the rescue!
return tostring(fragment, encoding='unicode') | random_line_split | |
ckeditor_link_tags.py | import importlib
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist
from ckeditor_link import conf
from django import template
from django.template.defaultfilters import stringfilter
try:
module_name, class_name = conf.CKEDITOR_LINK_MODEL.rsplit(".", 1)
my_module = importlib.import_module(module_name)
ckeditor_link_class = getattr(my_module, class_name, None)
except ImportError:
ckeditor_link_class = None
register = template.Library()
@register.filter
@stringfilter
def | (html):
# lxml is not a dependency, but needed for this tag.
from lxml.html import fragment_fromstring, tostring
if not ckeditor_link_class:
# TODO: use some log thing, or rais ImproperlyConfigured!
if settings.DEBUG:
msg = "Warning: CKEDITOR_LINK_MODEL (%s) could not be imported!?" % (conf.CKEDITOR_LINK_MODEL, )
raise ImproperlyConfigured(msg)
return html
fragment = fragment_fromstring("<div>" + html + "</div>")
links = fragment.cssselect('a')
for link in links:
if link.get('data-ckeditor-link', None):
link.attrib.pop('data-ckeditor-link')
kwargs = {}
dummy_link = ckeditor_link_class()
for key, value in link.items():
if key.startswith('data-'):
new_key = key.replace('data-', '', 1)
# DEPRECATED: use CKEDITOR_LINK_ATTR_MODIFIERS setting!
if new_key == 'page_2':
new_key = 'cms_page' # backward compat, for 0.2.0
if new_key == 'cms_page_2':
new_key = 'cms_page'
# until here
if hasattr(dummy_link, new_key):
if hasattr(dummy_link, new_key + "_id"):
# set fk directly
new_key = new_key + "_id"
if not value:
value = None
kwargs[new_key] = value
link.attrib.pop(key)
for key, formatted_string in conf.CKEDITOR_LINK_ATTR_MODIFIERS.items():
try:
kwargs[key] = formatted_string.format(**kwargs)
except KeyError:
# this is an option, we dont know at all how our link is/was built (ages ago)
pass
try:
# this can go wrong with fk and the like
real_link = ckeditor_link_class(**kwargs)
link.set('href', real_link.get_link())
if getattr(real_link, 'get_link_target', None):
link.set('target', real_link.get_link_target())
if getattr(real_link, 'get_link_style', None):
link.set('class', real_link.get_link_style())
if getattr(real_link, 'get_link_attrs', None):
for attr, value in real_link.get_link_attrs().items():
link.set(attr, value)
except (ValueError, ObjectDoesNotExist):
continue
# arf: http://makble.com/python-why-lxml-etree-tostring-method-returns-bytes
# beautifulsoup to the rescue!
return tostring(fragment, encoding='unicode')
| ckeditor_link_add_links | identifier_name |
ckeditor_link_tags.py | import importlib
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist
from ckeditor_link import conf
from django import template
from django.template.defaultfilters import stringfilter
try:
module_name, class_name = conf.CKEDITOR_LINK_MODEL.rsplit(".", 1)
my_module = importlib.import_module(module_name)
ckeditor_link_class = getattr(my_module, class_name, None)
except ImportError:
ckeditor_link_class = None
register = template.Library()
@register.filter
@stringfilter
def ckeditor_link_add_links(html):
# lxml is not a dependency, but needed for this tag.
from lxml.html import fragment_fromstring, tostring
if not ckeditor_link_class:
# TODO: use some log thing, or rais ImproperlyConfigured!
|
fragment = fragment_fromstring("<div>" + html + "</div>")
links = fragment.cssselect('a')
for link in links:
if link.get('data-ckeditor-link', None):
link.attrib.pop('data-ckeditor-link')
kwargs = {}
dummy_link = ckeditor_link_class()
for key, value in link.items():
if key.startswith('data-'):
new_key = key.replace('data-', '', 1)
# DEPRECATED: use CKEDITOR_LINK_ATTR_MODIFIERS setting!
if new_key == 'page_2':
new_key = 'cms_page' # backward compat, for 0.2.0
if new_key == 'cms_page_2':
new_key = 'cms_page'
# until here
if hasattr(dummy_link, new_key):
if hasattr(dummy_link, new_key + "_id"):
# set fk directly
new_key = new_key + "_id"
if not value:
value = None
kwargs[new_key] = value
link.attrib.pop(key)
for key, formatted_string in conf.CKEDITOR_LINK_ATTR_MODIFIERS.items():
try:
kwargs[key] = formatted_string.format(**kwargs)
except KeyError:
# this is an option, we dont know at all how our link is/was built (ages ago)
pass
try:
# this can go wrong with fk and the like
real_link = ckeditor_link_class(**kwargs)
link.set('href', real_link.get_link())
if getattr(real_link, 'get_link_target', None):
link.set('target', real_link.get_link_target())
if getattr(real_link, 'get_link_style', None):
link.set('class', real_link.get_link_style())
if getattr(real_link, 'get_link_attrs', None):
for attr, value in real_link.get_link_attrs().items():
link.set(attr, value)
except (ValueError, ObjectDoesNotExist):
continue
# arf: http://makble.com/python-why-lxml-etree-tostring-method-returns-bytes
# beautifulsoup to the rescue!
return tostring(fragment, encoding='unicode')
| if settings.DEBUG:
msg = "Warning: CKEDITOR_LINK_MODEL (%s) could not be imported!?" % (conf.CKEDITOR_LINK_MODEL, )
raise ImproperlyConfigured(msg)
return html | conditional_block |
factory.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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.
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
use trie::TrieFactory;
use evm::Factory as EvmFactory;
use account_db::Factory as AccountFactory;
/// Collection of factories.
#[derive(Default, Clone)]
pub struct | {
/// factory for evm.
pub vm: EvmFactory,
/// factory for tries.
pub trie: TrieFactory,
/// factory for account databases.
pub accountdb: AccountFactory,
}
| Factories | identifier_name |
factory.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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.
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
use trie::TrieFactory; | pub struct Factories {
/// factory for evm.
pub vm: EvmFactory,
/// factory for tries.
pub trie: TrieFactory,
/// factory for account databases.
pub accountdb: AccountFactory,
} | use evm::Factory as EvmFactory;
use account_db::Factory as AccountFactory;
/// Collection of factories.
#[derive(Default, Clone)] | random_line_split |
SuggestionThreadObjectFactorySpec.ts | // Copyright 2018 The Oppia 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.
/**
* @fileoverview Unit tests for SuggestionThreadObjectFactory.
*/
// TODO(#7222): Remove the following block of unnnecessary imports once
// SuggestionThreadObjectFactory.ts is upgraded to Angular 8.
import { SuggestionObjectFactory } from
'domain/suggestion/SuggestionObjectFactory.ts';
// ^^^ This block is to be removed.
require('domain/suggestion/SuggestionThreadObjectFactory.ts');
describe('Suggestion thread object factory', function() {
beforeEach(function() {
angular.mock.module('oppia');
});
beforeEach(angular.mock.module('oppia', function($provide) {
$provide.value('SuggestionObjectFactory', new SuggestionObjectFactory());
}));
var SuggestionThreadObjectFactory = null;
var suggestionObjectFactory = null;
beforeEach(angular.mock.inject(function($injector) {
SuggestionThreadObjectFactory = $injector.get(
'SuggestionThreadObjectFactory');
suggestionObjectFactory = $injector.get('SuggestionObjectFactory');
}));
it('should create a new suggestion thread from a backend dict.', function() {
var suggestionThreadBackendDict = {
last_updated: 1000,
original_author_username: 'author',
status: 'accepted',
subject: 'sample subject',
summary: 'sample summary',
message_count: 10,
state_name: 'state 1', | var suggestionBackendDict = {
suggestion_id: 'exploration.exp1.thread1',
suggestion_type: 'edit_exploration_state_content',
target_type: 'exploration',
target_id: 'exp1',
target_version_at_submission: 1,
status: 'accepted',
author_name: 'author',
change: {
cmd: 'edit_state_property',
property_name: 'content',
state_name: 'state_1',
new_value: {
html: 'new suggestion content'
},
old_value: {
html: 'old suggestion content'
}
},
last_updated: 1000
};
var suggestionThread = SuggestionThreadObjectFactory.createFromBackendDicts(
suggestionThreadBackendDict, suggestionBackendDict);
expect(suggestionThread.status).toEqual('accepted');
expect(suggestionThread.subject).toEqual('sample subject');
expect(suggestionThread.summary).toEqual('sample summary');
expect(suggestionThread.originalAuthorName).toEqual('author');
expect(suggestionThread.lastUpdated).toEqual(1000);
expect(suggestionThread.messageCount).toEqual(10);
expect(suggestionThread.threadId).toEqual('exploration.exp1.thread1');
expect(suggestionThread.suggestion.suggestionType).toEqual(
'edit_exploration_state_content');
expect(suggestionThread.suggestion.targetType).toEqual('exploration');
expect(suggestionThread.suggestion.targetId).toEqual('exp1');
expect(suggestionThread.suggestion.suggestionId).toEqual(
'exploration.exp1.thread1');
expect(suggestionThread.suggestion.status).toEqual('accepted');
expect(suggestionThread.suggestion.authorName).toEqual('author');
expect(suggestionThread.suggestion.newValue.html).toEqual(
'new suggestion content');
expect(suggestionThread.suggestion.oldValue.html).toEqual(
'old suggestion content');
expect(suggestionThread.suggestion.lastUpdated).toEqual(1000);
expect(suggestionThread.suggestion.getThreadId()).toEqual(
'exploration.exp1.thread1');
expect(suggestionThread.isSuggestionThread()).toEqual(true);
expect(suggestionThread.isSuggestionHandled()).toEqual(true);
suggestionThread.suggestion.status = 'review';
expect(suggestionThread.isSuggestionHandled()).toEqual(false);
expect(suggestionThread.getSuggestionStatus()).toEqual('review');
expect(suggestionThread.getSuggestionStateName()).toEqual('state_1');
expect(suggestionThread.getReplacementHtmlFromSuggestion()).toEqual(
'new suggestion content');
var messages = [{
text: 'message1'
}, {
text: 'message2'
}];
suggestionThread.setMessages(messages);
expect(suggestionThread.messages).toEqual(messages);
});
}); | thread_id: 'exploration.exp1.thread1'
};
| random_line_split |
ReactNativeFiber.js | /**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactNativeFiber
* @flow
*/
'use strict';
import type { Element } from 'React';
import type { Fiber } from 'ReactFiber';
import type { ReactNodeList } from 'ReactTypes';
import type { ReactNativeBaseComponentViewConfig } from 'ReactNativeViewConfigRegistry';
const NativeMethodsMixin = require('NativeMethodsMixin');
const ReactFiberReconciler = require('ReactFiberReconciler');
const ReactGenericBatching = require('ReactGenericBatching');
const ReactNativeAttributePayload = require('ReactNativeAttributePayload');
const ReactNativeComponentTree = require('ReactNativeComponentTree');
const ReactNativeInjection = require('ReactNativeInjection');
const ReactNativeTagHandles = require('ReactNativeTagHandles');
const ReactNativeViewConfigRegistry = require('ReactNativeViewConfigRegistry');
const ReactPortal = require('ReactPortal');
const UIManager = require('UIManager');
const deepFreezeAndThrowOnMutationInDev = require('deepFreezeAndThrowOnMutationInDev');
const emptyObject = require('emptyObject');
const findNodeHandle = require('findNodeHandle');
const invariant = require('invariant');
const { injectInternals } = require('ReactFiberDevToolsHook');
const {
precacheFiberNode,
uncacheFiberNode,
updateFiberProps,
} = ReactNativeComponentTree;
ReactNativeInjection.inject();
type Container = number;
type Instance = {
_children: Array<Instance | number>,
_nativeTag: number,
viewConfig: ReactNativeBaseComponentViewConfig,
};
type Props = Object;
type TextInstance = number;
function NativeHostComponent(tag, viewConfig) {
this._nativeTag = tag;
this._children = [];
this.viewConfig = viewConfig;
}
Object.assign(NativeHostComponent.prototype, NativeMethodsMixin);
function recursivelyUncacheFiberNode(node : Instance | TextInstance) {
if (typeof node === 'number') | else {
uncacheFiberNode((node : any)._nativeTag);
(node : any)._children.forEach(recursivelyUncacheFiberNode);
}
}
const NativeRenderer = ReactFiberReconciler({
appendChild(
parentInstance : Instance | Container,
child : Instance | TextInstance
) : void {
if (typeof parentInstance === 'number') {
// Root container
UIManager.setChildren(
parentInstance, // containerTag
[(child : any)._nativeTag] // reactTags
);
} else {
const children = parentInstance._children;
children.push(child);
UIManager.manageChildren(
parentInstance._nativeTag, // containerTag
[], // moveFromIndices
[], // moveToIndices
[(child : any)._nativeTag], // addChildReactTags
[children.length - 1], // addAtIndices
[], // removeAtIndices
);
}
},
appendInitialChild(parentInstance : Instance, child : Instance | TextInstance) : void {
parentInstance._children.push(child);
},
commitTextUpdate(
textInstance : TextInstance,
oldText : string,
newText : string
) : void {
UIManager.updateView(
textInstance, // reactTag
'RCTRawText', // viewName
{text: newText}, // props
);
},
commitMount(
instance : Instance,
type : string,
newProps : Props,
internalInstanceHandle : Object
) : void {
// Noop
},
commitUpdate(
instance : Instance,
updatePayloadTODO : Object,
type : string,
oldProps : Props,
newProps : Props,
internalInstanceHandle : Object
) : void {
const viewConfig = instance.viewConfig;
updateFiberProps(instance._nativeTag, newProps);
const updatePayload = ReactNativeAttributePayload.diff(
oldProps,
newProps,
viewConfig.validAttributes
);
UIManager.updateView(
(instance : any)._nativeTag, // reactTag
viewConfig.uiViewClassName, // viewName
updatePayload, // props
);
},
createInstance(
type : string,
props : Props,
rootContainerInstance : Container,
hostContext : {||},
internalInstanceHandle : Object
) : Instance {
const tag = ReactNativeTagHandles.allocateTag();
const viewConfig = ReactNativeViewConfigRegistry.get(type);
if (__DEV__) {
for (let key in viewConfig.validAttributes) {
if (props.hasOwnProperty(key)) {
deepFreezeAndThrowOnMutationInDev(props[key]);
}
}
}
const updatePayload = ReactNativeAttributePayload.create(
props,
viewConfig.validAttributes
);
UIManager.createView(
tag, // reactTag
viewConfig.uiViewClassName, // viewName
rootContainerInstance, // rootTag
updatePayload, // props
);
const component = new NativeHostComponent(tag, viewConfig);
precacheFiberNode(internalInstanceHandle, tag);
updateFiberProps(tag, props);
return component;
},
createTextInstance(
text : string,
rootContainerInstance : Container,
hostContext : {||},
internalInstanceHandle : Object,
) : TextInstance {
const tag = ReactNativeTagHandles.allocateTag();
UIManager.createView(
tag, // reactTag
'RCTRawText', // viewName
rootContainerInstance, // rootTag
{text: text} // props
);
precacheFiberNode(internalInstanceHandle, tag);
return tag;
},
finalizeInitialChildren(
parentInstance : Instance,
type : string,
props : Props,
rootContainerInstance : Container,
) : boolean {
// Don't send a no-op message over the bridge.
if (parentInstance._children.length === 0) {
return false;
}
// Map from child objects to native tags.
// Either way we need to pass a copy of the Array to prevent it from being frozen.
const nativeTags = parentInstance._children.map(
(child) => typeof child === 'number'
? child // Leaf node (eg text)
: child._nativeTag
);
UIManager.setChildren(
parentInstance._nativeTag, // containerTag
nativeTags // reactTags
);
return false;
},
getRootHostContext() : {||} {
return emptyObject;
},
getChildHostContext() : {||} {
return emptyObject;
},
getPublicInstance(instance) {
return instance;
},
insertBefore(
parentInstance : Instance | Container,
child : Instance | TextInstance,
beforeChild : Instance | TextInstance
) : void {
// TODO (bvaughn): Remove this check when...
// We create a wrapper object for the container in ReactNative render()
// Or we refactor to remove wrapper objects entirely.
// For more info on pros/cons see PR #8560 description.
invariant(
typeof parentInstance !== 'number',
'Container does not support insertBefore operation',
);
const children = (parentInstance : any)._children;
const beforeChildIndex = children.indexOf(beforeChild);
const index = children.indexOf(child);
// Move existing child or add new child?
if (index >= 0) {
children.splice(index, 1);
children.splice(beforeChildIndex, 0, child);
UIManager.manageChildren(
(parentInstance : any)._nativeTag, // containerID
[index], // moveFromIndices
[beforeChildIndex], // moveToIndices
[], // addChildReactTags
[], // addAtIndices
[], // removeAtIndices
);
} else {
children.splice(beforeChildIndex, 0, child);
UIManager.manageChildren(
(parentInstance : any)._nativeTag, // containerID
[], // moveFromIndices
[], // moveToIndices
[(child : any)._nativeTag], // addChildReactTags
[beforeChildIndex], // addAtIndices
[], // removeAtIndices
);
}
},
prepareForCommit() : void {
// Noop
},
prepareUpdate(
instance : Instance,
type : string,
oldProps : Props,
newProps : Props,
rootContainerInstance : Container,
hostContext : {||}
) : null | Object {
return emptyObject;
},
removeChild(
parentInstance : Instance | Container,
child : Instance | TextInstance
) : void {
recursivelyUncacheFiberNode(child);
if (typeof parentInstance === 'number') {
UIManager.manageChildren(
parentInstance, // containerID
[], // moveFromIndices
[], // moveToIndices
[], // addChildReactTags
[], // addAtIndices
[0], // removeAtIndices
);
} else {
const children = parentInstance._children;
const index = children.indexOf(child);
children.splice(index, 1);
UIManager.manageChildren(
parentInstance._nativeTag, // containerID
[], // moveFromIndices
[], // moveToIndices
[], // addChildReactTags
[], // addAtIndices
[index], // removeAtIndices
);
}
},
resetAfterCommit() : void {
// Noop
},
resetTextContent(instance : Instance) : void {
// Noop
},
scheduleAnimationCallback: global.requestAnimationFrame,
scheduleDeferredCallback: global.requestIdleCallback,
shouldSetTextContent(props : Props) : boolean {
// TODO (bvaughn) Revisit this decision.
// Always returning false simplifies the createInstance() implementation,
// But creates an additional child Fiber for raw text children.
// No additional native views are created though.
// It's not clear to me which is better so I'm deferring for now.
// More context @ github.com/facebook/react/pull/8560#discussion_r92111303
return false;
},
useSyncScheduling: true,
});
ReactGenericBatching.injection.injectFiberBatchedUpdates(
NativeRenderer.batchedUpdates
);
const roots = new Map();
findNodeHandle.injection.injectFindNode(
(fiber: Fiber) => {
const instance: any = NativeRenderer.findHostInstance(fiber);
return instance ? instance._nativeTag : null;
}
);
findNodeHandle.injection.injectFindRootNodeID(
(instance) => instance._nativeTag
);
const ReactNative = {
findNodeHandle,
render(element : Element<any>, containerTag : any, callback: ?Function) {
let root = roots.get(containerTag);
if (!root) {
// TODO (bvaughn): If we decide to keep the wrapper component,
// We could create a wrapper for containerTag as well to reduce special casing.
root = NativeRenderer.createContainer(containerTag);
roots.set(containerTag, root);
}
NativeRenderer.updateContainer(element, root, null, callback);
return NativeRenderer.getPublicRootInstance(root);
},
unmountComponentAtNode(containerTag : number) {
const root = roots.get(containerTag);
if (root) {
// TODO: Is it safe to reset this now or should I wait since this unmount could be deferred?
NativeRenderer.updateContainer(null, root, null, () => {
roots.delete(containerTag);
});
}
},
unmountComponentAtNodeAndRemoveContainer(containerTag: number) {
ReactNative.unmountComponentAtNode(containerTag);
// Call back into native to remove all of the subviews from this container
UIManager.removeRootView(containerTag);
},
unstable_createPortal(children: ReactNodeList, containerTag : number, key : ?string = null) {
return ReactPortal.createPortal(children, containerTag, null, key);
},
unstable_batchedUpdates: ReactGenericBatching.batchedUpdates,
};
if (typeof injectInternals === 'function') {
injectInternals({
findFiberByHostInstance: ReactNativeComponentTree.getClosestInstanceFromNode,
findHostInstanceByFiber: NativeRenderer.findHostInstance,
});
}
module.exports = ReactNative;
| { // Leaf node (eg text)
uncacheFiberNode(node);
} | conditional_block |
ReactNativeFiber.js | /**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactNativeFiber
* @flow
*/
'use strict';
import type { Element } from 'React';
import type { Fiber } from 'ReactFiber';
import type { ReactNodeList } from 'ReactTypes';
import type { ReactNativeBaseComponentViewConfig } from 'ReactNativeViewConfigRegistry';
const NativeMethodsMixin = require('NativeMethodsMixin');
const ReactFiberReconciler = require('ReactFiberReconciler');
const ReactGenericBatching = require('ReactGenericBatching');
const ReactNativeAttributePayload = require('ReactNativeAttributePayload');
const ReactNativeComponentTree = require('ReactNativeComponentTree');
const ReactNativeInjection = require('ReactNativeInjection');
const ReactNativeTagHandles = require('ReactNativeTagHandles');
const ReactNativeViewConfigRegistry = require('ReactNativeViewConfigRegistry');
const ReactPortal = require('ReactPortal');
const UIManager = require('UIManager');
const deepFreezeAndThrowOnMutationInDev = require('deepFreezeAndThrowOnMutationInDev');
const emptyObject = require('emptyObject');
const findNodeHandle = require('findNodeHandle');
const invariant = require('invariant');
const { injectInternals } = require('ReactFiberDevToolsHook');
const {
precacheFiberNode,
uncacheFiberNode,
updateFiberProps,
} = ReactNativeComponentTree;
ReactNativeInjection.inject();
type Container = number;
type Instance = {
_children: Array<Instance | number>,
_nativeTag: number,
viewConfig: ReactNativeBaseComponentViewConfig,
};
type Props = Object;
type TextInstance = number;
function NativeHostComponent(tag, viewConfig) |
Object.assign(NativeHostComponent.prototype, NativeMethodsMixin);
function recursivelyUncacheFiberNode(node : Instance | TextInstance) {
if (typeof node === 'number') { // Leaf node (eg text)
uncacheFiberNode(node);
} else {
uncacheFiberNode((node : any)._nativeTag);
(node : any)._children.forEach(recursivelyUncacheFiberNode);
}
}
const NativeRenderer = ReactFiberReconciler({
appendChild(
parentInstance : Instance | Container,
child : Instance | TextInstance
) : void {
if (typeof parentInstance === 'number') {
// Root container
UIManager.setChildren(
parentInstance, // containerTag
[(child : any)._nativeTag] // reactTags
);
} else {
const children = parentInstance._children;
children.push(child);
UIManager.manageChildren(
parentInstance._nativeTag, // containerTag
[], // moveFromIndices
[], // moveToIndices
[(child : any)._nativeTag], // addChildReactTags
[children.length - 1], // addAtIndices
[], // removeAtIndices
);
}
},
appendInitialChild(parentInstance : Instance, child : Instance | TextInstance) : void {
parentInstance._children.push(child);
},
commitTextUpdate(
textInstance : TextInstance,
oldText : string,
newText : string
) : void {
UIManager.updateView(
textInstance, // reactTag
'RCTRawText', // viewName
{text: newText}, // props
);
},
commitMount(
instance : Instance,
type : string,
newProps : Props,
internalInstanceHandle : Object
) : void {
// Noop
},
commitUpdate(
instance : Instance,
updatePayloadTODO : Object,
type : string,
oldProps : Props,
newProps : Props,
internalInstanceHandle : Object
) : void {
const viewConfig = instance.viewConfig;
updateFiberProps(instance._nativeTag, newProps);
const updatePayload = ReactNativeAttributePayload.diff(
oldProps,
newProps,
viewConfig.validAttributes
);
UIManager.updateView(
(instance : any)._nativeTag, // reactTag
viewConfig.uiViewClassName, // viewName
updatePayload, // props
);
},
createInstance(
type : string,
props : Props,
rootContainerInstance : Container,
hostContext : {||},
internalInstanceHandle : Object
) : Instance {
const tag = ReactNativeTagHandles.allocateTag();
const viewConfig = ReactNativeViewConfigRegistry.get(type);
if (__DEV__) {
for (let key in viewConfig.validAttributes) {
if (props.hasOwnProperty(key)) {
deepFreezeAndThrowOnMutationInDev(props[key]);
}
}
}
const updatePayload = ReactNativeAttributePayload.create(
props,
viewConfig.validAttributes
);
UIManager.createView(
tag, // reactTag
viewConfig.uiViewClassName, // viewName
rootContainerInstance, // rootTag
updatePayload, // props
);
const component = new NativeHostComponent(tag, viewConfig);
precacheFiberNode(internalInstanceHandle, tag);
updateFiberProps(tag, props);
return component;
},
createTextInstance(
text : string,
rootContainerInstance : Container,
hostContext : {||},
internalInstanceHandle : Object,
) : TextInstance {
const tag = ReactNativeTagHandles.allocateTag();
UIManager.createView(
tag, // reactTag
'RCTRawText', // viewName
rootContainerInstance, // rootTag
{text: text} // props
);
precacheFiberNode(internalInstanceHandle, tag);
return tag;
},
finalizeInitialChildren(
parentInstance : Instance,
type : string,
props : Props,
rootContainerInstance : Container,
) : boolean {
// Don't send a no-op message over the bridge.
if (parentInstance._children.length === 0) {
return false;
}
// Map from child objects to native tags.
// Either way we need to pass a copy of the Array to prevent it from being frozen.
const nativeTags = parentInstance._children.map(
(child) => typeof child === 'number'
? child // Leaf node (eg text)
: child._nativeTag
);
UIManager.setChildren(
parentInstance._nativeTag, // containerTag
nativeTags // reactTags
);
return false;
},
getRootHostContext() : {||} {
return emptyObject;
},
getChildHostContext() : {||} {
return emptyObject;
},
getPublicInstance(instance) {
return instance;
},
insertBefore(
parentInstance : Instance | Container,
child : Instance | TextInstance,
beforeChild : Instance | TextInstance
) : void {
// TODO (bvaughn): Remove this check when...
// We create a wrapper object for the container in ReactNative render()
// Or we refactor to remove wrapper objects entirely.
// For more info on pros/cons see PR #8560 description.
invariant(
typeof parentInstance !== 'number',
'Container does not support insertBefore operation',
);
const children = (parentInstance : any)._children;
const beforeChildIndex = children.indexOf(beforeChild);
const index = children.indexOf(child);
// Move existing child or add new child?
if (index >= 0) {
children.splice(index, 1);
children.splice(beforeChildIndex, 0, child);
UIManager.manageChildren(
(parentInstance : any)._nativeTag, // containerID
[index], // moveFromIndices
[beforeChildIndex], // moveToIndices
[], // addChildReactTags
[], // addAtIndices
[], // removeAtIndices
);
} else {
children.splice(beforeChildIndex, 0, child);
UIManager.manageChildren(
(parentInstance : any)._nativeTag, // containerID
[], // moveFromIndices
[], // moveToIndices
[(child : any)._nativeTag], // addChildReactTags
[beforeChildIndex], // addAtIndices
[], // removeAtIndices
);
}
},
prepareForCommit() : void {
// Noop
},
prepareUpdate(
instance : Instance,
type : string,
oldProps : Props,
newProps : Props,
rootContainerInstance : Container,
hostContext : {||}
) : null | Object {
return emptyObject;
},
removeChild(
parentInstance : Instance | Container,
child : Instance | TextInstance
) : void {
recursivelyUncacheFiberNode(child);
if (typeof parentInstance === 'number') {
UIManager.manageChildren(
parentInstance, // containerID
[], // moveFromIndices
[], // moveToIndices
[], // addChildReactTags
[], // addAtIndices
[0], // removeAtIndices
);
} else {
const children = parentInstance._children;
const index = children.indexOf(child);
children.splice(index, 1);
UIManager.manageChildren(
parentInstance._nativeTag, // containerID
[], // moveFromIndices
[], // moveToIndices
[], // addChildReactTags
[], // addAtIndices
[index], // removeAtIndices
);
}
},
resetAfterCommit() : void {
// Noop
},
resetTextContent(instance : Instance) : void {
// Noop
},
scheduleAnimationCallback: global.requestAnimationFrame,
scheduleDeferredCallback: global.requestIdleCallback,
shouldSetTextContent(props : Props) : boolean {
// TODO (bvaughn) Revisit this decision.
// Always returning false simplifies the createInstance() implementation,
// But creates an additional child Fiber for raw text children.
// No additional native views are created though.
// It's not clear to me which is better so I'm deferring for now.
// More context @ github.com/facebook/react/pull/8560#discussion_r92111303
return false;
},
useSyncScheduling: true,
});
ReactGenericBatching.injection.injectFiberBatchedUpdates(
NativeRenderer.batchedUpdates
);
const roots = new Map();
findNodeHandle.injection.injectFindNode(
(fiber: Fiber) => {
const instance: any = NativeRenderer.findHostInstance(fiber);
return instance ? instance._nativeTag : null;
}
);
findNodeHandle.injection.injectFindRootNodeID(
(instance) => instance._nativeTag
);
const ReactNative = {
findNodeHandle,
render(element : Element<any>, containerTag : any, callback: ?Function) {
let root = roots.get(containerTag);
if (!root) {
// TODO (bvaughn): If we decide to keep the wrapper component,
// We could create a wrapper for containerTag as well to reduce special casing.
root = NativeRenderer.createContainer(containerTag);
roots.set(containerTag, root);
}
NativeRenderer.updateContainer(element, root, null, callback);
return NativeRenderer.getPublicRootInstance(root);
},
unmountComponentAtNode(containerTag : number) {
const root = roots.get(containerTag);
if (root) {
// TODO: Is it safe to reset this now or should I wait since this unmount could be deferred?
NativeRenderer.updateContainer(null, root, null, () => {
roots.delete(containerTag);
});
}
},
unmountComponentAtNodeAndRemoveContainer(containerTag: number) {
ReactNative.unmountComponentAtNode(containerTag);
// Call back into native to remove all of the subviews from this container
UIManager.removeRootView(containerTag);
},
unstable_createPortal(children: ReactNodeList, containerTag : number, key : ?string = null) {
return ReactPortal.createPortal(children, containerTag, null, key);
},
unstable_batchedUpdates: ReactGenericBatching.batchedUpdates,
};
if (typeof injectInternals === 'function') {
injectInternals({
findFiberByHostInstance: ReactNativeComponentTree.getClosestInstanceFromNode,
findHostInstanceByFiber: NativeRenderer.findHostInstance,
});
}
module.exports = ReactNative;
| {
this._nativeTag = tag;
this._children = [];
this.viewConfig = viewConfig;
} | identifier_body |
ReactNativeFiber.js | /**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactNativeFiber
* @flow
*/
'use strict';
import type { Element } from 'React';
import type { Fiber } from 'ReactFiber';
import type { ReactNodeList } from 'ReactTypes';
import type { ReactNativeBaseComponentViewConfig } from 'ReactNativeViewConfigRegistry';
const NativeMethodsMixin = require('NativeMethodsMixin');
const ReactFiberReconciler = require('ReactFiberReconciler');
const ReactGenericBatching = require('ReactGenericBatching');
const ReactNativeAttributePayload = require('ReactNativeAttributePayload');
const ReactNativeComponentTree = require('ReactNativeComponentTree');
const ReactNativeInjection = require('ReactNativeInjection');
const ReactNativeTagHandles = require('ReactNativeTagHandles');
const ReactNativeViewConfigRegistry = require('ReactNativeViewConfigRegistry');
const ReactPortal = require('ReactPortal');
const UIManager = require('UIManager');
const deepFreezeAndThrowOnMutationInDev = require('deepFreezeAndThrowOnMutationInDev');
const emptyObject = require('emptyObject');
const findNodeHandle = require('findNodeHandle');
const invariant = require('invariant');
const { injectInternals } = require('ReactFiberDevToolsHook');
const {
precacheFiberNode,
uncacheFiberNode,
updateFiberProps,
} = ReactNativeComponentTree;
ReactNativeInjection.inject();
type Container = number;
type Instance = {
_children: Array<Instance | number>,
_nativeTag: number,
viewConfig: ReactNativeBaseComponentViewConfig,
};
type Props = Object;
type TextInstance = number;
function NativeHostComponent(tag, viewConfig) {
this._nativeTag = tag;
this._children = [];
this.viewConfig = viewConfig;
}
Object.assign(NativeHostComponent.prototype, NativeMethodsMixin);
function recursivelyUncacheFiberNode(node : Instance | TextInstance) {
if (typeof node === 'number') { // Leaf node (eg text)
uncacheFiberNode(node);
} else {
uncacheFiberNode((node : any)._nativeTag);
(node : any)._children.forEach(recursivelyUncacheFiberNode);
}
}
const NativeRenderer = ReactFiberReconciler({
appendChild(
parentInstance : Instance | Container,
child : Instance | TextInstance
) : void {
if (typeof parentInstance === 'number') {
// Root container
UIManager.setChildren(
parentInstance, // containerTag
[(child : any)._nativeTag] // reactTags
);
} else {
const children = parentInstance._children;
children.push(child);
UIManager.manageChildren(
parentInstance._nativeTag, // containerTag
[], // moveFromIndices
[], // moveToIndices
[(child : any)._nativeTag], // addChildReactTags
[children.length - 1], // addAtIndices
[], // removeAtIndices
);
}
},
appendInitialChild(parentInstance : Instance, child : Instance | TextInstance) : void {
parentInstance._children.push(child);
},
commitTextUpdate(
textInstance : TextInstance,
oldText : string,
newText : string
) : void {
UIManager.updateView(
textInstance, // reactTag
'RCTRawText', // viewName
{text: newText}, // props
);
},
commitMount(
instance : Instance,
type : string,
newProps : Props,
internalInstanceHandle : Object
) : void {
// Noop
},
commitUpdate(
instance : Instance,
updatePayloadTODO : Object,
type : string,
oldProps : Props,
newProps : Props,
internalInstanceHandle : Object
) : void {
const viewConfig = instance.viewConfig;
updateFiberProps(instance._nativeTag, newProps);
const updatePayload = ReactNativeAttributePayload.diff(
oldProps,
newProps,
viewConfig.validAttributes
);
UIManager.updateView(
(instance : any)._nativeTag, // reactTag
viewConfig.uiViewClassName, // viewName
updatePayload, // props
);
},
createInstance(
type : string,
props : Props,
rootContainerInstance : Container,
hostContext : {||},
internalInstanceHandle : Object
) : Instance {
const tag = ReactNativeTagHandles.allocateTag();
const viewConfig = ReactNativeViewConfigRegistry.get(type);
if (__DEV__) {
for (let key in viewConfig.validAttributes) {
if (props.hasOwnProperty(key)) {
deepFreezeAndThrowOnMutationInDev(props[key]);
}
}
}
const updatePayload = ReactNativeAttributePayload.create(
props,
viewConfig.validAttributes
);
UIManager.createView(
tag, // reactTag
viewConfig.uiViewClassName, // viewName
rootContainerInstance, // rootTag
updatePayload, // props
);
const component = new NativeHostComponent(tag, viewConfig);
precacheFiberNode(internalInstanceHandle, tag);
updateFiberProps(tag, props);
return component;
},
createTextInstance(
text : string,
rootContainerInstance : Container,
hostContext : {||},
internalInstanceHandle : Object,
) : TextInstance {
const tag = ReactNativeTagHandles.allocateTag();
UIManager.createView(
tag, // reactTag
'RCTRawText', // viewName
rootContainerInstance, // rootTag
{text: text} // props
);
precacheFiberNode(internalInstanceHandle, tag);
return tag;
},
finalizeInitialChildren(
parentInstance : Instance,
type : string,
props : Props,
rootContainerInstance : Container,
) : boolean {
// Don't send a no-op message over the bridge.
if (parentInstance._children.length === 0) {
return false;
}
// Map from child objects to native tags.
// Either way we need to pass a copy of the Array to prevent it from being frozen.
const nativeTags = parentInstance._children.map(
(child) => typeof child === 'number'
? child // Leaf node (eg text)
: child._nativeTag
);
UIManager.setChildren(
parentInstance._nativeTag, // containerTag
nativeTags // reactTags
);
return false;
},
getRootHostContext() : {||} {
return emptyObject;
},
getChildHostContext() : {||} {
return emptyObject;
},
getPublicInstance(instance) {
return instance;
},
insertBefore(
parentInstance : Instance | Container,
child : Instance | TextInstance,
beforeChild : Instance | TextInstance
) : void {
// TODO (bvaughn): Remove this check when...
// We create a wrapper object for the container in ReactNative render()
// Or we refactor to remove wrapper objects entirely.
// For more info on pros/cons see PR #8560 description.
invariant(
typeof parentInstance !== 'number',
'Container does not support insertBefore operation',
);
const children = (parentInstance : any)._children;
const beforeChildIndex = children.indexOf(beforeChild);
const index = children.indexOf(child);
// Move existing child or add new child?
if (index >= 0) {
children.splice(index, 1);
children.splice(beforeChildIndex, 0, child);
UIManager.manageChildren(
(parentInstance : any)._nativeTag, // containerID
[index], // moveFromIndices
[beforeChildIndex], // moveToIndices
[], // addChildReactTags
[], // addAtIndices
[], // removeAtIndices
);
} else {
children.splice(beforeChildIndex, 0, child);
UIManager.manageChildren(
(parentInstance : any)._nativeTag, // containerID
[], // moveFromIndices
[], // moveToIndices
[(child : any)._nativeTag], // addChildReactTags
[beforeChildIndex], // addAtIndices
[], // removeAtIndices
);
}
},
prepareForCommit() : void {
// Noop
},
prepareUpdate(
instance : Instance,
type : string,
oldProps : Props,
newProps : Props,
rootContainerInstance : Container,
hostContext : {||}
) : null | Object {
return emptyObject;
},
removeChild(
parentInstance : Instance | Container,
child : Instance | TextInstance
) : void {
recursivelyUncacheFiberNode(child);
if (typeof parentInstance === 'number') {
UIManager.manageChildren(
parentInstance, // containerID
[], // moveFromIndices
[], // moveToIndices
[], // addChildReactTags
[], // addAtIndices
[0], // removeAtIndices
);
} else {
const children = parentInstance._children;
const index = children.indexOf(child);
children.splice(index, 1);
UIManager.manageChildren(
parentInstance._nativeTag, // containerID
[], // moveFromIndices
[], // moveToIndices
[], // addChildReactTags
[], // addAtIndices
[index], // removeAtIndices
);
}
},
resetAfterCommit() : void {
// Noop
},
resetTextContent(instance : Instance) : void {
// Noop
},
scheduleAnimationCallback: global.requestAnimationFrame,
scheduleDeferredCallback: global.requestIdleCallback,
shouldSetTextContent(props : Props) : boolean {
// TODO (bvaughn) Revisit this decision.
// Always returning false simplifies the createInstance() implementation,
// But creates an additional child Fiber for raw text children.
// No additional native views are created though.
// It's not clear to me which is better so I'm deferring for now.
// More context @ github.com/facebook/react/pull/8560#discussion_r92111303
return false;
},
useSyncScheduling: true,
});
ReactGenericBatching.injection.injectFiberBatchedUpdates(
NativeRenderer.batchedUpdates
);
const roots = new Map();
findNodeHandle.injection.injectFindNode(
(fiber: Fiber) => {
const instance: any = NativeRenderer.findHostInstance(fiber);
return instance ? instance._nativeTag : null;
}
);
findNodeHandle.injection.injectFindRootNodeID(
(instance) => instance._nativeTag
);
const ReactNative = {
findNodeHandle,
render(element : Element<any>, containerTag : any, callback: ?Function) {
let root = roots.get(containerTag);
if (!root) {
// TODO (bvaughn): If we decide to keep the wrapper component,
// We could create a wrapper for containerTag as well to reduce special casing.
root = NativeRenderer.createContainer(containerTag);
roots.set(containerTag, root);
}
NativeRenderer.updateContainer(element, root, null, callback);
return NativeRenderer.getPublicRootInstance(root);
},
unmountComponentAtNode(containerTag : number) {
const root = roots.get(containerTag);
if (root) {
// TODO: Is it safe to reset this now or should I wait since this unmount could be deferred?
NativeRenderer.updateContainer(null, root, null, () => {
roots.delete(containerTag);
});
}
},
unmountComponentAtNodeAndRemoveContainer(containerTag: number) {
ReactNative.unmountComponentAtNode(containerTag);
// Call back into native to remove all of the subviews from this container
UIManager.removeRootView(containerTag);
},
unstable_createPortal(children: ReactNodeList, containerTag : number, key : ?string = null) {
return ReactPortal.createPortal(children, containerTag, null, key);
},
unstable_batchedUpdates: ReactGenericBatching.batchedUpdates,
};
if (typeof injectInternals === 'function') {
injectInternals({ | findHostInstanceByFiber: NativeRenderer.findHostInstance,
});
}
module.exports = ReactNative; | findFiberByHostInstance: ReactNativeComponentTree.getClosestInstanceFromNode, | random_line_split |
ReactNativeFiber.js | /**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactNativeFiber
* @flow
*/
'use strict';
import type { Element } from 'React';
import type { Fiber } from 'ReactFiber';
import type { ReactNodeList } from 'ReactTypes';
import type { ReactNativeBaseComponentViewConfig } from 'ReactNativeViewConfigRegistry';
const NativeMethodsMixin = require('NativeMethodsMixin');
const ReactFiberReconciler = require('ReactFiberReconciler');
const ReactGenericBatching = require('ReactGenericBatching');
const ReactNativeAttributePayload = require('ReactNativeAttributePayload');
const ReactNativeComponentTree = require('ReactNativeComponentTree');
const ReactNativeInjection = require('ReactNativeInjection');
const ReactNativeTagHandles = require('ReactNativeTagHandles');
const ReactNativeViewConfigRegistry = require('ReactNativeViewConfigRegistry');
const ReactPortal = require('ReactPortal');
const UIManager = require('UIManager');
const deepFreezeAndThrowOnMutationInDev = require('deepFreezeAndThrowOnMutationInDev');
const emptyObject = require('emptyObject');
const findNodeHandle = require('findNodeHandle');
const invariant = require('invariant');
const { injectInternals } = require('ReactFiberDevToolsHook');
const {
precacheFiberNode,
uncacheFiberNode,
updateFiberProps,
} = ReactNativeComponentTree;
ReactNativeInjection.inject();
type Container = number;
type Instance = {
_children: Array<Instance | number>,
_nativeTag: number,
viewConfig: ReactNativeBaseComponentViewConfig,
};
type Props = Object;
type TextInstance = number;
function NativeHostComponent(tag, viewConfig) {
this._nativeTag = tag;
this._children = [];
this.viewConfig = viewConfig;
}
Object.assign(NativeHostComponent.prototype, NativeMethodsMixin);
function | (node : Instance | TextInstance) {
if (typeof node === 'number') { // Leaf node (eg text)
uncacheFiberNode(node);
} else {
uncacheFiberNode((node : any)._nativeTag);
(node : any)._children.forEach(recursivelyUncacheFiberNode);
}
}
const NativeRenderer = ReactFiberReconciler({
appendChild(
parentInstance : Instance | Container,
child : Instance | TextInstance
) : void {
if (typeof parentInstance === 'number') {
// Root container
UIManager.setChildren(
parentInstance, // containerTag
[(child : any)._nativeTag] // reactTags
);
} else {
const children = parentInstance._children;
children.push(child);
UIManager.manageChildren(
parentInstance._nativeTag, // containerTag
[], // moveFromIndices
[], // moveToIndices
[(child : any)._nativeTag], // addChildReactTags
[children.length - 1], // addAtIndices
[], // removeAtIndices
);
}
},
appendInitialChild(parentInstance : Instance, child : Instance | TextInstance) : void {
parentInstance._children.push(child);
},
commitTextUpdate(
textInstance : TextInstance,
oldText : string,
newText : string
) : void {
UIManager.updateView(
textInstance, // reactTag
'RCTRawText', // viewName
{text: newText}, // props
);
},
commitMount(
instance : Instance,
type : string,
newProps : Props,
internalInstanceHandle : Object
) : void {
// Noop
},
commitUpdate(
instance : Instance,
updatePayloadTODO : Object,
type : string,
oldProps : Props,
newProps : Props,
internalInstanceHandle : Object
) : void {
const viewConfig = instance.viewConfig;
updateFiberProps(instance._nativeTag, newProps);
const updatePayload = ReactNativeAttributePayload.diff(
oldProps,
newProps,
viewConfig.validAttributes
);
UIManager.updateView(
(instance : any)._nativeTag, // reactTag
viewConfig.uiViewClassName, // viewName
updatePayload, // props
);
},
createInstance(
type : string,
props : Props,
rootContainerInstance : Container,
hostContext : {||},
internalInstanceHandle : Object
) : Instance {
const tag = ReactNativeTagHandles.allocateTag();
const viewConfig = ReactNativeViewConfigRegistry.get(type);
if (__DEV__) {
for (let key in viewConfig.validAttributes) {
if (props.hasOwnProperty(key)) {
deepFreezeAndThrowOnMutationInDev(props[key]);
}
}
}
const updatePayload = ReactNativeAttributePayload.create(
props,
viewConfig.validAttributes
);
UIManager.createView(
tag, // reactTag
viewConfig.uiViewClassName, // viewName
rootContainerInstance, // rootTag
updatePayload, // props
);
const component = new NativeHostComponent(tag, viewConfig);
precacheFiberNode(internalInstanceHandle, tag);
updateFiberProps(tag, props);
return component;
},
createTextInstance(
text : string,
rootContainerInstance : Container,
hostContext : {||},
internalInstanceHandle : Object,
) : TextInstance {
const tag = ReactNativeTagHandles.allocateTag();
UIManager.createView(
tag, // reactTag
'RCTRawText', // viewName
rootContainerInstance, // rootTag
{text: text} // props
);
precacheFiberNode(internalInstanceHandle, tag);
return tag;
},
finalizeInitialChildren(
parentInstance : Instance,
type : string,
props : Props,
rootContainerInstance : Container,
) : boolean {
// Don't send a no-op message over the bridge.
if (parentInstance._children.length === 0) {
return false;
}
// Map from child objects to native tags.
// Either way we need to pass a copy of the Array to prevent it from being frozen.
const nativeTags = parentInstance._children.map(
(child) => typeof child === 'number'
? child // Leaf node (eg text)
: child._nativeTag
);
UIManager.setChildren(
parentInstance._nativeTag, // containerTag
nativeTags // reactTags
);
return false;
},
getRootHostContext() : {||} {
return emptyObject;
},
getChildHostContext() : {||} {
return emptyObject;
},
getPublicInstance(instance) {
return instance;
},
insertBefore(
parentInstance : Instance | Container,
child : Instance | TextInstance,
beforeChild : Instance | TextInstance
) : void {
// TODO (bvaughn): Remove this check when...
// We create a wrapper object for the container in ReactNative render()
// Or we refactor to remove wrapper objects entirely.
// For more info on pros/cons see PR #8560 description.
invariant(
typeof parentInstance !== 'number',
'Container does not support insertBefore operation',
);
const children = (parentInstance : any)._children;
const beforeChildIndex = children.indexOf(beforeChild);
const index = children.indexOf(child);
// Move existing child or add new child?
if (index >= 0) {
children.splice(index, 1);
children.splice(beforeChildIndex, 0, child);
UIManager.manageChildren(
(parentInstance : any)._nativeTag, // containerID
[index], // moveFromIndices
[beforeChildIndex], // moveToIndices
[], // addChildReactTags
[], // addAtIndices
[], // removeAtIndices
);
} else {
children.splice(beforeChildIndex, 0, child);
UIManager.manageChildren(
(parentInstance : any)._nativeTag, // containerID
[], // moveFromIndices
[], // moveToIndices
[(child : any)._nativeTag], // addChildReactTags
[beforeChildIndex], // addAtIndices
[], // removeAtIndices
);
}
},
prepareForCommit() : void {
// Noop
},
prepareUpdate(
instance : Instance,
type : string,
oldProps : Props,
newProps : Props,
rootContainerInstance : Container,
hostContext : {||}
) : null | Object {
return emptyObject;
},
removeChild(
parentInstance : Instance | Container,
child : Instance | TextInstance
) : void {
recursivelyUncacheFiberNode(child);
if (typeof parentInstance === 'number') {
UIManager.manageChildren(
parentInstance, // containerID
[], // moveFromIndices
[], // moveToIndices
[], // addChildReactTags
[], // addAtIndices
[0], // removeAtIndices
);
} else {
const children = parentInstance._children;
const index = children.indexOf(child);
children.splice(index, 1);
UIManager.manageChildren(
parentInstance._nativeTag, // containerID
[], // moveFromIndices
[], // moveToIndices
[], // addChildReactTags
[], // addAtIndices
[index], // removeAtIndices
);
}
},
resetAfterCommit() : void {
// Noop
},
resetTextContent(instance : Instance) : void {
// Noop
},
scheduleAnimationCallback: global.requestAnimationFrame,
scheduleDeferredCallback: global.requestIdleCallback,
shouldSetTextContent(props : Props) : boolean {
// TODO (bvaughn) Revisit this decision.
// Always returning false simplifies the createInstance() implementation,
// But creates an additional child Fiber for raw text children.
// No additional native views are created though.
// It's not clear to me which is better so I'm deferring for now.
// More context @ github.com/facebook/react/pull/8560#discussion_r92111303
return false;
},
useSyncScheduling: true,
});
ReactGenericBatching.injection.injectFiberBatchedUpdates(
NativeRenderer.batchedUpdates
);
const roots = new Map();
findNodeHandle.injection.injectFindNode(
(fiber: Fiber) => {
const instance: any = NativeRenderer.findHostInstance(fiber);
return instance ? instance._nativeTag : null;
}
);
findNodeHandle.injection.injectFindRootNodeID(
(instance) => instance._nativeTag
);
const ReactNative = {
findNodeHandle,
render(element : Element<any>, containerTag : any, callback: ?Function) {
let root = roots.get(containerTag);
if (!root) {
// TODO (bvaughn): If we decide to keep the wrapper component,
// We could create a wrapper for containerTag as well to reduce special casing.
root = NativeRenderer.createContainer(containerTag);
roots.set(containerTag, root);
}
NativeRenderer.updateContainer(element, root, null, callback);
return NativeRenderer.getPublicRootInstance(root);
},
unmountComponentAtNode(containerTag : number) {
const root = roots.get(containerTag);
if (root) {
// TODO: Is it safe to reset this now or should I wait since this unmount could be deferred?
NativeRenderer.updateContainer(null, root, null, () => {
roots.delete(containerTag);
});
}
},
unmountComponentAtNodeAndRemoveContainer(containerTag: number) {
ReactNative.unmountComponentAtNode(containerTag);
// Call back into native to remove all of the subviews from this container
UIManager.removeRootView(containerTag);
},
unstable_createPortal(children: ReactNodeList, containerTag : number, key : ?string = null) {
return ReactPortal.createPortal(children, containerTag, null, key);
},
unstable_batchedUpdates: ReactGenericBatching.batchedUpdates,
};
if (typeof injectInternals === 'function') {
injectInternals({
findFiberByHostInstance: ReactNativeComponentTree.getClosestInstanceFromNode,
findHostInstanceByFiber: NativeRenderer.findHostInstance,
});
}
module.exports = ReactNative;
| recursivelyUncacheFiberNode | identifier_name |
subcontractOperationDefinitionForm.component.ts | import { Component, ViewEncapsulation, Input } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { ActivatedRoute, Params, Router } from '@angular/router';
import {
FormGroup,
AbstractControl,
FormBuilder,
Validators
} from '@angular/forms';
import { SharedService } from '../../../../services/shared.service';
import { SubcontractOperationDefinitionService } from '../../subcontractOperationDefinition.service';
import { ItemService } from '../../../item/item.service';
import 'rxjs/add/operator/take';
import { ProductTypeService } from '../../../productType/productType.service';
import { OperationTypeService } from '../../../operationType/operationType.service';
@Component({
selector: 'subcontract-operation-definition-form',
encapsulation: ViewEncapsulation.None,
styleUrls: ['./subcontractOperationDefinitionForm.scss'],
templateUrl: './subcontractOperationDefinitionForm.html'
})
export class SubcontractOperationDefinitionForm {
JSON: any = JSON;
public formGroup: FormGroup;
subcontractOperationDefinition: any = {};
subscription: Subscription;
itemList = [];
item: any;
subcontractOperationDefinitionType: any;
operationType: any;
productType: any;
productTypeList = [];
operationTypeList = [];
constructor(
protected service: SubcontractOperationDefinitionService,
private route: ActivatedRoute,
private router: Router,
fb: FormBuilder,
private itemService: ItemService,
private productTypeService: ProductTypeService,
private operationTypeService: OperationTypeService,
private sharedService: SharedService
) {
this.formGroup = fb.group({
id: '',
description: '',
item: [this.item, Validators.required],
operationType: [this.operationType, Validators.required],
productType: [this.productType, Validators.required]
});
}
getItemList(): void {
this.itemService
.getCombo()
.subscribe(itemList => (this.itemList = itemList));
}
getProductTypeList(): void {
this.productTypeService
.getCombo()
.subscribe(productTypeList => (this.productTypeList = productTypeList));
}
getOperationTypeList(): void {
this.operationTypeService
.getCombo()
.subscribe(
operationTypeList => (this.operationTypeList = operationTypeList)
);
}
ngOnInit(): void {
this.getItemList();
this.getOperationTypeList();
this.getProductTypeList();
this.route.params.subscribe((params: Params) => {
let id = params['id'];
id = id === undefined ? '0' : id;
if (id !== '0') {
this.service
.get(+id)
.take(1)
.subscribe(data => {
this.loadForm(data);
});
}
});
}
refresh(): void {
this.getItemList();
this.getOperationTypeList();
this.getProductTypeList();
}
loadForm(data: any) {
if (data != null) |
this.formGroup.patchValue(this.subcontractOperationDefinition, {
onlySelf: true
});
this.item = this.subcontractOperationDefinition.item;
}
public onSubmit(values: any, event: Event): void {
event.preventDefault();
console.log(values);
this.service.save(values).subscribe(data => {
this.sharedService.addMessage({
severity: 'info',
summary: 'Success',
detail: 'Operation Success'
});
this.resetForm();
this.router.navigate(['/pages/subcontractOperationDefinition/form/']);
});
}
public resetForm() {
this.formGroup.reset();
}
/*================== ItemFilter ===================*/
filteredItemList: any[];
filterItemList(event) {
let query = event.query.toLowerCase();
this.filteredItemList = [];
for (let i = 0; i < this.itemList.length; i++) {
let item = this.itemList[i];
if (item.display.toLowerCase().indexOf(query) >= 0) {
this.filteredItemList.push(item);
}
}
}
onItemSelect(event: any) {}
/*================== ItemFilter ===================*/
/*================== OperationTypeFilter ===================*/
filteredOperationTypeList: any[];
filterOperationTypeList(event) {
let query = event.query.toLowerCase();
this.filteredOperationTypeList = [];
for (let i = 0; i < this.operationTypeList.length; i++) {
let operationType = this.operationTypeList[i];
if (operationType.display.toLowerCase().indexOf(query) >= 0) {
this.filteredOperationTypeList.push(operationType);
}
}
}
onOperationTypeSelect(event: any) {}
/*================== OperationTypeFilter ===================*/
/*================== ProductTypeFilter ===================*/
filteredProductTypeList: any[];
filterProductTypeList(event) {
let query = event.query.toLowerCase();
this.filteredProductTypeList = [];
for (let i = 0; i < this.productTypeList.length; i++) {
let productType = this.productTypeList[i];
if (productType.display.toLowerCase().indexOf(query) >= 0) {
this.filteredProductTypeList.push(productType);
}
}
}
onProductTypeSelect(event: any) {}
/*================== ProductTypeFilter ===================*/
}
| {
this.subcontractOperationDefinition = data;
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.