text
stringlengths
2
1.04M
meta
dict
require 'intercom/service/base_service' require 'intercom/api_operations/load' require 'intercom/api_operations/list' require 'intercom/api_operations/find' require 'intercom/api_operations/find_all' require 'intercom/api_operations/save' require 'intercom/api_operations/scroll' require 'intercom/api_operations/convert' require 'intercom/api_operations/archive' require 'intercom/api_operations/request_hard_delete' require 'intercom/deprecated_leads_collection_proxy' module Intercom module Service class Lead < BaseService include ApiOperations::Load include ApiOperations::List include ApiOperations::Find include ApiOperations::FindAll include ApiOperations::Save include ApiOperations::Scroll include ApiOperations::Convert include ApiOperations::Archive include ApiOperations::RequestHardDelete def collection_proxy_class Intercom::DeprecatedLeadsCollectionProxy end def collection_class Intercom::Lead end def collection_name 'contacts' end end end end
{ "content_hash": "2be9878fcb36037b53778baa9e07d4c8", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 53, "avg_line_length": 28, "alnum_prop": 0.7426739926739927, "repo_name": "intercom/intercom-ruby", "id": "7c243e9f50e6ad1e151a6a7d69900755a56c416b", "size": "1123", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/intercom/service/lead.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "197203" } ], "symlink_target": "" }
define([ "dojo/_base/array", // array.forEach "dojo/dom", // dom.isDescendant "dojo/_base/lang", // lang.isArray "dojo/topic", // publish "dojo/_base/window", // win.doc win.doc.selection win.global win.global.getSelection win.withGlobal "../focus", "../main" // for exporting symbols to dijit ], function(array, dom, lang, topic, win, focus, dijit){ // module: // dijit/_base/focus var exports = { // summary: // Deprecated module to monitor currently focused node and stack of currently focused widgets. // New code should access dijit/focus directly. // _curFocus: DomNode // Currently focused item on screen _curFocus: null, // _prevFocus: DomNode // Previously focused item on screen _prevFocus: null, isCollapsed: function(){ // summary: // Returns true if there is no text selected return dijit.getBookmark().isCollapsed; }, getBookmark: function(){ // summary: // Retrieves a bookmark that can be used with moveToBookmark to return to the same range var bm, rg, tg, sel = win.doc.selection, cf = focus.curNode; if(win.global.getSelection){ //W3C Range API for selections. sel = win.global.getSelection(); if(sel){ if(sel.isCollapsed){ tg = cf? cf.tagName : ""; if(tg){ //Create a fake rangelike item to restore selections. tg = tg.toLowerCase(); if(tg == "textarea" || (tg == "input" && (!cf.type || cf.type.toLowerCase() == "text"))){ sel = { start: cf.selectionStart, end: cf.selectionEnd, node: cf, pRange: true }; return {isCollapsed: (sel.end <= sel.start), mark: sel}; //Object. } } bm = {isCollapsed:true}; if(sel.rangeCount){ bm.mark = sel.getRangeAt(0).cloneRange(); } }else{ rg = sel.getRangeAt(0); bm = {isCollapsed: false, mark: rg.cloneRange()}; } } }else if(sel){ // If the current focus was a input of some sort and no selection, don't bother saving // a native bookmark. This is because it causes issues with dialog/page selection restore. // So, we need to create psuedo bookmarks to work with. tg = cf ? cf.tagName : ""; tg = tg.toLowerCase(); if(cf && tg && (tg == "button" || tg == "textarea" || tg == "input")){ if(sel.type && sel.type.toLowerCase() == "none"){ return { isCollapsed: true, mark: null } }else{ rg = sel.createRange(); return { isCollapsed: rg.text && rg.text.length?false:true, mark: { range: rg, pRange: true } }; } } bm = {}; //'IE' way for selections. try{ // createRange() throws exception when dojo in iframe //and nothing selected, see #9632 rg = sel.createRange(); bm.isCollapsed = !(sel.type == 'Text' ? rg.htmlText.length : rg.length); }catch(e){ bm.isCollapsed = true; return bm; } if(sel.type.toUpperCase() == 'CONTROL'){ if(rg.length){ bm.mark=[]; var i=0,len=rg.length; while(i<len){ bm.mark.push(rg.item(i++)); } }else{ bm.isCollapsed = true; bm.mark = null; } }else{ bm.mark = rg.getBookmark(); } }else{ console.warn("No idea how to store the current selection for this browser!"); } return bm; // Object }, moveToBookmark: function(/*Object*/ bookmark){ // summary: // Moves current selection to a bookmark // bookmark: // This should be a returned object from dijit.getBookmark() var _doc = win.doc, mark = bookmark.mark; if(mark){ if(win.global.getSelection){ //W3C Rangi API (FF, WebKit, Opera, etc) var sel = win.global.getSelection(); if(sel && sel.removeAllRanges){ if(mark.pRange){ var n = mark.node; n.selectionStart = mark.start; n.selectionEnd = mark.end; }else{ sel.removeAllRanges(); sel.addRange(mark); } }else{ console.warn("No idea how to restore selection for this browser!"); } }else if(_doc.selection && mark){ //'IE' way. var rg; if(mark.pRange){ rg = mark.range; }else if(lang.isArray(mark)){ rg = _doc.body.createControlRange(); //rg.addElement does not have call/apply method, so can not call it directly //rg is not available in "range.addElement(item)", so can't use that either array.forEach(mark, function(n){ rg.addElement(n); }); }else{ rg = _doc.body.createTextRange(); rg.moveToBookmark(mark); } rg.select(); } } }, getFocus: function(/*Widget?*/ menu, /*Window?*/ openedForWindow){ // summary: // Called as getFocus(), this returns an Object showing the current focus // and selected text. // // Called as getFocus(widget), where widget is a (widget representing) a button // that was just pressed, it returns where focus was before that button // was pressed. (Pressing the button may have either shifted focus to the button, // or removed focus altogether.) In this case the selected text is not returned, // since it can't be accurately determined. // // menu: dijit/_WidgetBase|{domNode: DomNode} structure // The button that was just pressed. If focus has disappeared or moved // to this button, returns the previous focus. In this case the bookmark // information is already lost, and null is returned. // // openedForWindow: // iframe in which menu was opened // // returns: // A handle to restore focus/selection, to be passed to `dijit.focus` var node = !focus.curNode || (menu && dom.isDescendant(focus.curNode, menu.domNode)) ? dijit._prevFocus : focus.curNode; return { node: node, bookmark: node && (node == focus.curNode) && win.withGlobal(openedForWindow || win.global, dijit.getBookmark), openedForWindow: openedForWindow }; // Object }, // _activeStack: dijit/_WidgetBase[] // List of currently active widgets (focused widget and it's ancestors) _activeStack: [], registerIframe: function(/*DomNode*/ iframe){ // summary: // Registers listeners on the specified iframe so that any click // or focus event on that iframe (or anything in it) is reported // as a focus/click event on the `<iframe>` itself. // description: // Currently only used by editor. // returns: // Handle to pass to unregisterIframe() return focus.registerIframe(iframe); }, unregisterIframe: function(/*Object*/ handle){ // summary: // Unregisters listeners on the specified iframe created by registerIframe. // After calling be sure to delete or null out the handle itself. // handle: // Handle returned by registerIframe() handle && handle.remove(); }, registerWin: function(/*Window?*/targetWindow, /*DomNode?*/ effectiveNode){ // summary: // Registers listeners on the specified window (either the main // window or an iframe's window) to detect when the user has clicked somewhere // or focused somewhere. // description: // Users should call registerIframe() instead of this method. // targetWindow: // If specified this is the window associated with the iframe, // i.e. iframe.contentWindow. // effectiveNode: // If specified, report any focus events inside targetWindow as // an event on effectiveNode, rather than on evt.target. // returns: // Handle to pass to unregisterWin() return focus.registerWin(targetWindow, effectiveNode); }, unregisterWin: function(/*Handle*/ handle){ // summary: // Unregisters listeners on the specified window (either the main // window or an iframe's window) according to handle returned from registerWin(). // After calling be sure to delete or null out the handle itself. handle && handle.remove(); } }; // Override focus singleton's focus function so that dijit.focus() // has backwards compatible behavior of restoring selection (although // probably no one is using that). focus.focus = function(/*Object|DomNode */ handle){ // summary: // Sets the focused node and the selection according to argument. // To set focus to an iframe's content, pass in the iframe itself. // handle: // object returned by get(), or a DomNode if(!handle){ return; } var node = "node" in handle ? handle.node : handle, // because handle is either DomNode or a composite object bookmark = handle.bookmark, openedForWindow = handle.openedForWindow, collapsed = bookmark ? bookmark.isCollapsed : false; // Set the focus // Note that for iframe's we need to use the <iframe> to follow the parentNode chain, // but we need to set focus to iframe.contentWindow if(node){ var focusNode = (node.tagName.toLowerCase() == "iframe") ? node.contentWindow : node; if(focusNode && focusNode.focus){ try{ // Gecko throws sometimes if setting focus is impossible, // node not displayed or something like that focusNode.focus(); }catch(e){/*quiet*/} } focus._onFocusNode(node); } // set the selection // do not need to restore if current selection is not empty // (use keyboard to select a menu item) or if previous selection was collapsed // as it may cause focus shift (Esp in IE). if(bookmark && win.withGlobal(openedForWindow || win.global, dijit.isCollapsed) && !collapsed){ if(openedForWindow){ openedForWindow.focus(); } try{ win.withGlobal(openedForWindow || win.global, dijit.moveToBookmark, null, [bookmark]); }catch(e2){ /*squelch IE internal error, see http://trac.dojotoolkit.org/ticket/1984 */ } } }; // For back compatibility, monitor changes to focused node and active widget stack, // publishing events and copying changes from focus manager variables into dijit (top level) variables focus.watch("curNode", function(name, oldVal, newVal){ dijit._curFocus = newVal; dijit._prevFocus = oldVal; if(newVal){ topic.publish("focusNode", newVal); // publish } }); focus.watch("activeStack", function(name, oldVal, newVal){ dijit._activeStack = newVal; }); focus.on("widget-blur", function(widget, by){ topic.publish("widgetBlur", widget, by); // publish }); focus.on("widget-focus", function(widget, by){ topic.publish("widgetFocus", widget, by); // publish }); lang.mixin(dijit, exports); /*===== return exports; =====*/ return dijit; // for back compat :-( });
{ "content_hash": "29deef16cc01366422640519db04ddfd", "timestamp": "", "source": "github", "line_count": 323, "max_line_length": 123, "avg_line_length": 32.56656346749226, "alnum_prop": 0.6392242608612986, "repo_name": "aguadev/aguadev", "id": "304d6626867c9a84db42f01fa4dab67c35e80941", "size": "10519", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "html/dojo-1.8.3/dijit/_base/focus.js", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "63213" }, { "name": "Assembly", "bytes": "2811185" }, { "name": "Awk", "bytes": "1651" }, { "name": "C", "bytes": "17157035" }, { "name": "C++", "bytes": "16652335" }, { "name": "CSS", "bytes": "7295053" }, { "name": "D", "bytes": "38703" }, { "name": "Emacs Lisp", "bytes": "14719" }, { "name": "Java", "bytes": "664579" }, { "name": "JavaScript", "bytes": "74379284" }, { "name": "Lua", "bytes": "37481" }, { "name": "Objective-C", "bytes": "62279" }, { "name": "PHP", "bytes": "1497773" }, { "name": "Perl", "bytes": "13076601" }, { "name": "Puppet", "bytes": "4423" }, { "name": "Python", "bytes": "2466246" }, { "name": "R", "bytes": "2216" }, { "name": "Ruby", "bytes": "11167" }, { "name": "Scheme", "bytes": "14853" }, { "name": "Shell", "bytes": "327744" }, { "name": "TeX", "bytes": "4217" }, { "name": "XQuery", "bytes": "2397" }, { "name": "XSLT", "bytes": "255596" }, { "name": "eC", "bytes": "5079" } ], "symlink_target": "" }
@interface DCPaymentAlert()<DCPasswordDelegate> @property (nonatomic, strong) UIButton *closeBtn; @property (nonatomic, strong) UILabel *titleLabel, *line, *detailLabel, *amountLabel; @property (nonatomic, strong) DCPwdTextField *inputView; @end @implementation DCPaymentAlert - (void)completeInput:(NSString *)pwd{ } - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { self.layer.masksToBounds = YES; self.layer.cornerRadius = 5.; self.backgroundColor = [UIColor colorWithWhite:1. alpha:.9]; [self drawView]; } return self; } - (void)drawView { _titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, self.bounds.size.width, TITLE_HEIGHT)]; _titleLabel.textAlignment = NSTextAlignmentCenter; _titleLabel.textColor = [UIColor darkGrayColor]; _titleLabel.font = [UIFont systemFontOfSize:17]; [self addSubview:_titleLabel]; _closeBtn = [UIButton buttonWithType:UIButtonTypeCustom]; [_closeBtn setFrame:CGRectMake(0, 0, TITLE_HEIGHT, TITLE_HEIGHT)]; [_closeBtn setTitle:@"╳" forState:UIControlStateNormal]; [_closeBtn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal]; [_closeBtn addTarget:self action:@selector(closeView) forControlEvents:UIControlEventTouchUpInside]; _closeBtn.titleLabel.font = [UIFont systemFontOfSize:15]; [self addSubview:_closeBtn]; _line = [[UILabel alloc]initWithFrame:CGRectMake(0, TITLE_HEIGHT, self.bounds.size.width, .5f)]; _line.backgroundColor = [UIColor lightGrayColor]; [self addSubview:_line]; _detailLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, TITLE_HEIGHT+15, self.bounds.size.width-30, 20)]; _detailLabel.textAlignment = NSTextAlignmentCenter; _detailLabel.textColor = [UIColor darkGrayColor]; _detailLabel.font = [UIFont systemFontOfSize:16]; [self addSubview:_detailLabel]; _amountLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, TITLE_HEIGHT*2, self.bounds.size.width-30, 25)]; _amountLabel.textAlignment = NSTextAlignmentCenter; _amountLabel.textColor = [UIColor darkGrayColor]; _amountLabel.font = [UIFont systemFontOfSize:33]; [self addSubview:_amountLabel]; _inputView = [[DCPwdTextField alloc]initWithFrame:CGRectMake(15, self.frame.size.height-(self.frame.size.width-30)/6-15, self.frame.size.width-30, (self.frame.size.width-30)/6)]; _inputView.layer.borderWidth = 1.f; _inputView.layer.borderColor = [UIColor colorWithRed:.9 green:.9 blue:.9 alpha:1.].CGColor; _inputView.delegate = self; [self addSubview:_inputView]; } - (void)closeView { } #pragma mark - set - (void)setTitle:(NSString *)title { if (_title != title) { _title = title; _titleLabel.text = _title; } } - (void)setDetail:(NSString *)detail { if (_detail != detail) { _detail = detail; _detailLabel.text = _detail; } } - (void)setAmount:(CGFloat)amount { if (_amount != amount) { _amount = amount; _amountLabel.text = [NSString stringWithFormat:@"¥%.2f ",amount]; } } @end // 版权属于原作者 // http://code4app.com (cn) http://code4app.net (en) // 发布代码于最专业的源码分享网站: Code4App.com
{ "content_hash": "86a15ea5a57722e9f64aa05a4c5acd92", "timestamp": "", "source": "github", "line_count": 99, "max_line_length": 182, "avg_line_length": 32.92929292929293, "alnum_prop": 0.6877300613496933, "repo_name": "guojianfeng01/MNPayDemo", "id": "af2393747b5d8bdeb2c530127649d067c461627c", "size": "3555", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "WSPayDemo/WSPayDemo/Pay/secretAlert/DCPaymentAlert.m", "mode": "33261", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "484038" }, { "name": "Ruby", "bytes": "177" }, { "name": "Shell", "bytes": "8385" } ], "symlink_target": "" }
namespace { const int kPaddingVertical = 19; class DateDefaultView : public views::View, public views::ButtonListener { public: explicit DateDefaultView(ash::user::LoginStatus login) : help_(NULL), shutdown_(NULL), lock_(NULL) { SetLayoutManager(new views::FillLayout); ash::internal::tray::DateView* date_view = new ash::internal::tray::DateView(); date_view->set_border(views::Border::CreateEmptyBorder(kPaddingVertical, ash::kTrayPopupPaddingHorizontal, 0, 0)); ash::internal::SpecialPopupRow* view = new ash::internal::SpecialPopupRow(); view->SetContent(date_view); AddChildView(view); if (login == ash::user::LOGGED_IN_LOCKED || login == ash::user::LOGGED_IN_NONE) return; date_view->SetActionable(true); help_ = new ash::internal::TrayPopupHeaderButton(this, IDR_AURA_UBER_TRAY_HELP, IDR_AURA_UBER_TRAY_HELP, IDR_AURA_UBER_TRAY_HELP_HOVER, IDR_AURA_UBER_TRAY_HELP_HOVER, IDS_ASH_STATUS_TRAY_HELP); view->AddButton(help_); if (login != ash::user::LOGGED_IN_LOCKED && login != ash::user::LOGGED_IN_KIOSK) { shutdown_ = new ash::internal::TrayPopupHeaderButton(this, IDR_AURA_UBER_TRAY_SHUTDOWN, IDR_AURA_UBER_TRAY_SHUTDOWN, IDR_AURA_UBER_TRAY_SHUTDOWN_HOVER, IDR_AURA_UBER_TRAY_SHUTDOWN_HOVER, IDS_ASH_STATUS_TRAY_SHUTDOWN); view->AddButton(shutdown_); } if (ash::Shell::GetInstance()->CanLockScreen()) { lock_ = new ash::internal::TrayPopupHeaderButton(this, IDR_AURA_UBER_TRAY_LOCKSCREEN, IDR_AURA_UBER_TRAY_LOCKSCREEN, IDR_AURA_UBER_TRAY_LOCKSCREEN_HOVER, IDR_AURA_UBER_TRAY_LOCKSCREEN_HOVER, IDS_ASH_STATUS_TRAY_LOCK); view->AddButton(lock_); } } virtual ~DateDefaultView() {} private: // Overridden from views::ButtonListener. virtual void ButtonPressed(views::Button* sender, const ui::Event& event) OVERRIDE { ash::SystemTrayDelegate* tray = ash::Shell::GetInstance()->tray_delegate(); if (sender == help_) tray->ShowHelp(); else if (sender == shutdown_) tray->ShutDown(); else if (sender == lock_) tray->RequestLockScreen(); else NOTREACHED(); } ash::internal::TrayPopupHeaderButton* help_; ash::internal::TrayPopupHeaderButton* shutdown_; ash::internal::TrayPopupHeaderButton* lock_; DISALLOW_COPY_AND_ASSIGN(DateDefaultView); }; } // namespace namespace ash { namespace internal { TrayDate::TrayDate(SystemTray* system_tray) : SystemTrayItem(system_tray), time_tray_(NULL) { } TrayDate::~TrayDate() { } views::View* TrayDate::CreateTrayView(user::LoginStatus status) { CHECK(time_tray_ == NULL); ClockLayout clock_layout = system_tray()->shelf_alignment() == SHELF_ALIGNMENT_BOTTOM ? HORIZONTAL_CLOCK : VERTICAL_CLOCK; time_tray_ = new tray::TimeView(clock_layout); views::View* view = new TrayItemView(this); view->AddChildView(time_tray_); return view; } views::View* TrayDate::CreateDefaultView(user::LoginStatus status) { return new DateDefaultView(status); } views::View* TrayDate::CreateDetailedView(user::LoginStatus status) { return NULL; } void TrayDate::DestroyTrayView() { time_tray_ = NULL; } void TrayDate::DestroyDefaultView() { } void TrayDate::DestroyDetailedView() { } void TrayDate::UpdateAfterLoginStatusChange(user::LoginStatus status) { } void TrayDate::UpdateAfterShelfAlignmentChange(ShelfAlignment alignment) { if (time_tray_) { ClockLayout clock_layout = alignment == SHELF_ALIGNMENT_BOTTOM ? HORIZONTAL_CLOCK : VERTICAL_CLOCK; time_tray_->UpdateClockLayout(clock_layout); } } void TrayDate::OnDateFormatChanged() { if (time_tray_) time_tray_->UpdateTimeFormat(); } void TrayDate::Refresh() { if (time_tray_) time_tray_->UpdateText(); } } // namespace internal } // namespace ash
{ "content_hash": "a46b2ac177d46fd7aafedfd3eff76c0d", "timestamp": "", "source": "github", "line_count": 148, "max_line_length": 80, "avg_line_length": 27.304054054054053, "alnum_prop": 0.6552833457065083, "repo_name": "leighpauls/k2cro4", "id": "47945994f830016c5e84b6cc1b3147d306d733ed", "size": "5379", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ash/system/date/tray_date.cc", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "3062" }, { "name": "AppleScript", "bytes": "25392" }, { "name": "Arduino", "bytes": "464" }, { "name": "Assembly", "bytes": "68131038" }, { "name": "C", "bytes": "242794338" }, { "name": "C#", "bytes": "11024" }, { "name": "C++", "bytes": "353525184" }, { "name": "Common Lisp", "bytes": "3721" }, { "name": "D", "bytes": "1931" }, { "name": "Emacs Lisp", "bytes": "1639" }, { "name": "F#", "bytes": "4992" }, { "name": "FORTRAN", "bytes": "10404" }, { "name": "Java", "bytes": "3845159" }, { "name": "JavaScript", "bytes": "39146656" }, { "name": "Lua", "bytes": "13768" }, { "name": "Matlab", "bytes": "22373" }, { "name": "Objective-C", "bytes": "21887598" }, { "name": "PHP", "bytes": "2344144" }, { "name": "Perl", "bytes": "49033099" }, { "name": "Prolog", "bytes": "2926122" }, { "name": "Python", "bytes": "39863959" }, { "name": "R", "bytes": "262" }, { "name": "Racket", "bytes": "359" }, { "name": "Ruby", "bytes": "304063" }, { "name": "Scheme", "bytes": "14853" }, { "name": "Shell", "bytes": "9195117" }, { "name": "Tcl", "bytes": "1919771" }, { "name": "Verilog", "bytes": "3092" }, { "name": "Visual Basic", "bytes": "1430" }, { "name": "eC", "bytes": "5079" } ], "symlink_target": "" }
package v1 import ( time "time" monitoringv1 "github.com/coreos/prometheus-operator/pkg/apis/monitoring/v1" internalinterfaces "github.com/coreos/prometheus-operator/pkg/client/informers/externalversions/internalinterfaces" v1 "github.com/coreos/prometheus-operator/pkg/client/listers/monitoring/v1" versioned "github.com/coreos/prometheus-operator/pkg/client/versioned" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" watch "k8s.io/apimachinery/pkg/watch" cache "k8s.io/client-go/tools/cache" ) // AlertmanagerInformer provides access to a shared informer and lister for // Alertmanagers. type AlertmanagerInformer interface { Informer() cache.SharedIndexInformer Lister() v1.AlertmanagerLister } type alertmanagerInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc namespace string } // NewAlertmanagerInformer constructs a new informer for Alertmanager type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. func NewAlertmanagerInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewFilteredAlertmanagerInformer(client, namespace, resyncPeriod, indexers, nil) } // NewFilteredAlertmanagerInformer constructs a new informer for Alertmanager type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. func NewFilteredAlertmanagerInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { return cache.NewSharedIndexInformer( &cache.ListWatch{ ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { tweakListOptions(&options) } return client.MonitoringV1().Alertmanagers(namespace).List(options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } return client.MonitoringV1().Alertmanagers(namespace).Watch(options) }, }, &monitoringv1.Alertmanager{}, resyncPeriod, indexers, ) } func (f *alertmanagerInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { return NewFilteredAlertmanagerInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) } func (f *alertmanagerInformer) Informer() cache.SharedIndexInformer { return f.factory.InformerFor(&monitoringv1.Alertmanager{}, f.defaultInformer) } func (f *alertmanagerInformer) Lister() v1.AlertmanagerLister { return v1.NewAlertmanagerLister(f.Informer().GetIndexer()) }
{ "content_hash": "13067dc83f5d506643348c77ab0b4240", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 221, "avg_line_length": 43.28169014084507, "alnum_prop": 0.8018223234624146, "repo_name": "jescarri/prometheus-operator", "id": "5bac3f1e06fbf92a6ace9a6b0004464cab371ddd", "size": "3731", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pkg/client/informers/externalversions/monitoring/v1/alertmanager.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "1840" }, { "name": "Go", "bytes": "1222048" }, { "name": "Jsonnet", "bytes": "357509" }, { "name": "Makefile", "bytes": "13122" }, { "name": "Shell", "bytes": "11644" } ], "symlink_target": "" }
<?php /** * Configuration file generated by ZFTool * The previous configuration file is stored in application.config.old * * @see https://github.com/zendframework/ZFTool */ return array( 'modules' => array( 'Application', ), 'module_listener_options' => array( 'module_paths' => array( './module', './vendor' ), 'config_glob_paths' => array( 'config/autoload/{,*.}{global,local}.php' ) ) );
{ "content_hash": "8036f61924edd1dfe9e54cbd8461635c", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 70, "avg_line_length": 23.238095238095237, "alnum_prop": 0.5471311475409836, "repo_name": "ppetdotcom/website", "id": "37b1ebeeea8f8c4e40148fc27cc6d7c1969fbebd", "size": "488", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "config/application.config.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "1042" }, { "name": "PHP", "bytes": "16884" } ], "symlink_target": "" }
rem This script builds the audio data needed for ZeldaDS. After running it, from rem the output directory, copy the 'bin files to Game/ZeldaDS/nitrofiles/Audio/ rem and the 'h' files to Game/ZeldaDS/arm9/source/data/ @echo off setlocal make clean make
{ "content_hash": "98a6e79119ba9acd685d250c7180695f", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 80, "avg_line_length": 31.625, "alnum_prop": 0.7865612648221344, "repo_name": "amaiorano/ZeldaDS", "id": "0dc67c6c9e8cb40fc37cd0a90691f060cf070ff1", "size": "253", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Assets/Audio/build_audio.bat", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "311" }, { "name": "C", "bytes": "7054" }, { "name": "C#", "bytes": "131674" }, { "name": "C++", "bytes": "212280" }, { "name": "CSS", "bytes": "5267" }, { "name": "JavaScript", "bytes": "480" }, { "name": "Shell", "bytes": "5522" } ], "symlink_target": "" }
import sys import json import asyncio import argparse from decimal import Decimal from aioconsole import ainput from aiosocks import SocksConnectionError from aiohttp.client_exceptions import ClientConnectorError from pycoin.tx.Tx import Tx import nowallet class WalletDaemon: def __init__(self, _loop): self.loop = _loop self.chain = nowallet.TBTC async def initialize_wallet(self, _salt, _passphrase, bech32, rbf): try: server, port, proto = await nowallet.get_random_server(self.loop) connection = nowallet.Connection(self.loop, server, port, proto) self.wallet = nowallet.Wallet( _salt, _passphrase, connection, self.loop, self.chain) await connection.do_connect() except (SocksConnectionError, ClientConnectorError): self.print_json({ "error": "Make sure Tor is installed and running before using nowalletd." }) sys.exit(1) self.wallet.bech32 = bech32 self.rbf = rbf await self.wallet.discover_all_keys() self.print_history() self.wallet.new_history = False def print_json(self, output): print(json.dumps(output)) def print_history(self, last_only=False): history = [h.as_dict() for h in self.wallet.get_tx_history()] utxos = [u.as_dict() for u in self.wallet.utxos] wallet_info = { "tx_history": history[-1] if last_only else history, "utxos": utxos } self.print_json({"wallet_info": wallet_info}) async def input_loop(self): while True: input_ = await ainput(loop=self.loop) if not input_: continue if input_ == "@end": sys.exit(0) try: obj = json.loads(input_) except json.JSONDecodeError as err: self.print_json({ "error": "{}: {}".format(type(err).__name__, str(err)) }) continue await self.dispatch_input(obj) async def new_history_loop(self): while True: await asyncio.sleep(1) if self.wallet.new_history: self.print_history(last_only=True) self.wallet.new_history = False async def dispatch_input(self, obj): type_ = obj.get("type") if not type_: self.print_json({"error": "Command type was not specified"}) elif type_ == "get_address": self.do_get_address() elif type_ == "get_feerate": await self.do_get_feerate() elif type_ == "get_balance": self.do_get_balance() elif type_ == "get_ypub": self.do_get_ypub() elif type_ == "mktx": await self.do_mktx(obj) elif type_ == "broadcast": await self.do_broadcast(obj) else: self.print_json({"error": "Command type is not supported"}) def do_get_address(self): key = self.wallet.get_next_unused_key() address = self.wallet.get_address(key, addr=True) self.print_json({"address": address}) async def do_get_feerate(self): feerate = await self.wallet.get_fee_estimation() self.print_json({"feerate": feerate}) def do_get_balance(self): balances = { "confirmed": str(self.wallet.balance), "zeroconf": str(self.wallet.zeroconf_balance) } self.print_json({"balance": balances}) def do_get_ypub(self): self.print_json({"ypub": self.wallet.ypub}) async def do_mktx(self, obj): address, amount, coin_per_kb = \ obj.get("address"), Decimal(obj.get("amount")), obj.get("feerate") if not address or not amount or not coin_per_kb: self.print_json({"error": "Command parameters are not correct"}) return tx_hex, chg_vout, decimal_fee, tx_vsize = \ await self.wallet.spend(address, amount, coin_per_kb, rbf=self.rbf, broadcast=False) tx_info = { "tx_hex": tx_hex, "vout": chg_vout, "fee": str(decimal_fee), "vsize": tx_vsize } self.print_json({"tx_info": tx_info}) async def do_broadcast(self, obj): tx_hex, chg_vout = obj.get("tx_hex"), obj.get("vout") if not tx_hex or not chg_vout: self.print_json({"error": "Command parameters are not correct"}) return chg_out = Tx.from_hex(tx_hex).txs_out[chg_vout] txid = await self.wallet.broadcast(tx_hex, chg_out) self.print_json({"txid": txid}) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("salt", help="You must supply a salt to create a wallet.") parser.add_argument("passphrase", help="You must supply a passphrase to create a wallet.") parser.add_argument("--bech32", help="Create a Bech32 wallet.", action="store_true") parser.add_argument("--rbf", help="Mark transactions as replaceable.", action="store_true") args = parser.parse_args() loop = asyncio.get_event_loop() daemon = WalletDaemon(loop) loop.run_until_complete(daemon.initialize_wallet( args.salt, args.passphrase, args.bech32, args.rbf)) tasks = asyncio.gather( asyncio.ensure_future(daemon.wallet.listen_to_addresses()), asyncio.ensure_future(daemon.input_loop()), asyncio.ensure_future(daemon.new_history_loop()) ) # Graceful shutdown code borrowed from: # https://stackoverflow.com/questions/30765606/ # whats-the-correct-way-to-clean-up-after-an-interrupted-event-loop try: # Here `amain(loop)` is the core coroutine that may spawn any # number of tasks sys.exit(loop.run_until_complete(tasks)) except KeyboardInterrupt: # Optionally show a message if the shutdown may take a while print("\nAttempting graceful shutdown, press Ctrl+C again to exit...", flush=True) # Do not show `asyncio.CancelledError` exceptions during shutdown # (a lot of these may be generated, skip this if you prefer to see them) def shutdown_exception_handler(_loop, context): if "exception" not in context \ or not isinstance(context["exception"], asyncio.CancelledError): _loop.default_exception_handler(context) loop.set_exception_handler(shutdown_exception_handler) # Handle shutdown gracefully by waiting for all tasks to be cancelled tasks = asyncio.gather(*asyncio.Task.all_tasks(loop=loop), loop=loop, return_exceptions=True) tasks.add_done_callback(lambda t: loop.stop()) tasks.cancel() # Keep the event loop running until it is either destroyed or all # tasks have really terminated while not tasks.done() and not loop.is_closed(): loop.run_forever() finally: loop.close()
{ "content_hash": "62724c46220afa82dd7ea0a887733f63", "timestamp": "", "source": "github", "line_count": 192, "max_line_length": 96, "avg_line_length": 36.817708333333336, "alnum_prop": 0.5931532041307116, "repo_name": "metamarcdw/nowallet", "id": "78bf7e4e9b60f27bb0fd80f78118a045e0f721be", "size": "7069", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "nowalletd.py", "mode": "33188", "license": "mit", "language": [ { "name": "Makefile", "bytes": "905" }, { "name": "Python", "bytes": "104686" } ], "symlink_target": "" }
FreeVoteBot =========== A vote bot for #freecode on irc.rizon.net
{ "content_hash": "431a2939e3d2c080c207c780a01d38b2", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 41, "avg_line_length": 16.75, "alnum_prop": 0.6417910447761194, "repo_name": "freecode/FreeVoteBot", "id": "4c7f2b9d2df11fbe5022c2c458ca2fa833407999", "size": "67", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "90853" }, { "name": "Python", "bytes": "358" }, { "name": "Shell", "bytes": "400" } ], "symlink_target": "" }
package es.lnsd.citikey.core.datasource.realm.mappers; import android.support.annotation.NonNull; import es.lnsd.citikey.core.datasource.realm.RealmMapper; import es.lnsd.citikey.core.datasource.realm.entities.BeaconRealm; import es.lnsd.citikey.core.datasource.realm.entities.PathRealm; import es.lnsd.citikey.core.datasource.realm.entities.RoomRealm; import es.lnsd.citikey.core.model.Beacon; import es.lnsd.citikey.core.model.Path; import es.lnsd.citikey.core.model.Room; import io.realm.Realm; public class PathMapper { private PathRealmToPath realmToPathMapper; private PathToPathRealm pathToRealmMapper; public PathMapper(Realm realm) { this.realmToPathMapper = new PathRealmToPath(); this.pathToRealmMapper = new PathToPathRealm(realm); } public Path map(@NonNull PathRealm pathRealm) { return realmToPathMapper.map(pathRealm); } public PathRealm map(@NonNull Path path) { return pathToRealmMapper.map(path); } public Path copy(@NonNull PathRealm pathRealm, @NonNull Path path) { return realmToPathMapper.copy(pathRealm, path); } public PathRealm copy(@NonNull Path path, @NonNull PathRealm pathRealm) { return pathToRealmMapper.copy(path, pathRealm); } //region Static inner classes public static class PathRealmToPath implements RealmMapper<PathRealm, Path> { private final RoomMapper.RoomRealmToRoom roomMapper; private final BeaconMapper.BeaconRealmToBeacon beacoMapper; public PathRealmToPath() { // TODO: Inject dependency via constructor this.roomMapper = new RoomMapper.RoomRealmToRoom(); this.beacoMapper = new BeaconMapper.BeaconRealmToBeacon(); } @Override public Path map(@NonNull PathRealm pathRealm) { Path path = new Path(); path.setId(pathRealm.getId()); copy(pathRealm, path); Room room = roomMapper.map(pathRealm.getRoom()); path.setRoom(room); Beacon beacon = beacoMapper.map(pathRealm.getBeacon()); path.setBeacon(beacon); return path; } @Override public Path copy(@NonNull PathRealm pathRealm, @NonNull Path path) { path.setId(pathRealm.getId()); path.setPathUri(pathRealm.getPathUri()); return path; } } public static class PathToPathRealm implements RealmMapper<Path, PathRealm> { private final Realm realm; private final RoomMapper.RoomToRoomRealm roomMapper; private final BeaconMapper.BeaconToBeaconRealm beaconMapper; public PathToPathRealm(Realm realm) { this.realm = realm; // TODO: Inject dependency via constructor this.roomMapper = new RoomMapper.RoomToRoomRealm(realm); this.beaconMapper = new BeaconMapper.BeaconToBeaconRealm(realm); } @Override public PathRealm map(@NonNull Path path) { // create plant realm object and set id PathRealm pathRealm = realm.createObject(PathRealm.class); pathRealm.setId(path.getId()); // copy values which should be updated copy(path, pathRealm); // create room realm object and set id RoomRealm roomRealm = realm.createObject(RoomRealm.class); roomRealm.setId(path.getRoom().getId()); // copy value which should be updated roomMapper.copy(path.getRoom(), roomRealm); pathRealm.setRoom(roomRealm); // create beacon realm object and set id BeaconRealm beaconRealm = realm.createObject(BeaconRealm.class); beaconRealm.setId(path.getBeacon().getId()); // copy value which should be updated beaconMapper.copy(path.getBeacon(), beaconRealm); pathRealm.setBeacon(beaconRealm); return pathRealm; } @Override public PathRealm copy(@NonNull Path path, @NonNull PathRealm pathRealm) { pathRealm.setId(path.getId()); pathRealm.setPathUri(path.getPathUri()); return pathRealm; } } //endregion }
{ "content_hash": "bb1ab7808c19f0b23bac0a0b02b5e1c2", "timestamp": "", "source": "github", "line_count": 134, "max_line_length": 81, "avg_line_length": 31.73134328358209, "alnum_prop": 0.6538099717779868, "repo_name": "Citikey/citikey-android", "id": "e13305d1d770d46a3f71c2e08594c181f492b10e", "size": "4410", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "data/src/main/java/es/lnsd/citikey/core/datasource/realm/mappers/PathMapper.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "223975" } ], "symlink_target": "" }
@font-face { font-family: 'setareh'; src: url('setareh.eot'); /* IE9 Compat Modes */ src: url('setareh.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */ url('setareh.woff2') format('woff2'), /* Modern Browsers */ url('setareh.woff') format('woff'), /* Modern Browsers */ url('setareh.ttf') format('truetype'), /* Safari, Android, iOS */ url('setareh.svg') format('svg'); /* Legacy iOS */ font-weight: normal; font-style: normal; }
{ "content_hash": "f3a8ff13b87787af894392ceefd6396a", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 77, "avg_line_length": 32.2, "alnum_prop": 0.5942028985507246, "repo_name": "neacodin/fontchi", "id": "0017155ad2a7f14be6940e2bfdbeb7c2ea7c43e3", "size": "572", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/fonts-pack/setareh/bold/style.css", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "42261" }, { "name": "HTML", "bytes": "11171" }, { "name": "JavaScript", "bytes": "9334" } ], "symlink_target": "" }
namespace { FX_BOOL _IsIgnoreSpaceCharacter(FX_WCHAR curChar) { if (curChar < 255) { return FALSE; } if ((curChar >= 0x0600 && curChar <= 0x06FF) || (curChar >= 0xFE70 && curChar <= 0xFEFF) || (curChar >= 0xFB50 && curChar <= 0xFDFF) || (curChar >= 0x0400 && curChar <= 0x04FF) || (curChar >= 0x0500 && curChar <= 0x052F) || (curChar >= 0xA640 && curChar <= 0xA69F) || (curChar >= 0x2DE0 && curChar <= 0x2DFF) || curChar == 8467 || (curChar >= 0x2000 && curChar <= 0x206F)) { return FALSE; } return TRUE; } FX_FLOAT _NormalizeThreshold(FX_FLOAT threshold) { if (threshold < 300) { return threshold / 2.0f; } if (threshold < 500) { return threshold / 4.0f; } if (threshold < 700) { return threshold / 5.0f; } return threshold / 6.0f; } FX_FLOAT _CalculateBaseSpace(const CPDF_TextObject* pTextObj, const CFX_AffineMatrix& matrix) { FX_FLOAT baseSpace = 0.0; const int nItems = pTextObj->CountItems(); if (pTextObj->m_TextState.GetObject()->m_CharSpace && nItems >= 3) { FX_BOOL bAllChar = TRUE; FX_FLOAT spacing = matrix.TransformDistance( pTextObj->m_TextState.GetObject()->m_CharSpace); baseSpace = spacing; for (int i = 0; i < nItems; i++) { CPDF_TextObjectItem item; pTextObj->GetItemInfo(i, &item); if (item.m_CharCode == (FX_DWORD)-1) { FX_FLOAT fontsize_h = pTextObj->m_TextState.GetFontSizeH(); FX_FLOAT kerning = -fontsize_h * item.m_OriginX / 1000; baseSpace = std::min(baseSpace, kerning + spacing); bAllChar = FALSE; } } if (baseSpace < 0.0 || (nItems == 3 && !bAllChar)) { baseSpace = 0.0; } } return baseSpace; } } // namespace CPDFText_ParseOptions::CPDFText_ParseOptions() : m_bGetCharCodeOnly(FALSE), m_bNormalizeObjs(TRUE), m_bOutputHyphen(FALSE) {} IPDF_TextPage* IPDF_TextPage::CreateTextPage(const CPDF_Page* pPage, int flags) { return new CPDF_TextPage(pPage, flags); } IPDF_TextPageFind* IPDF_TextPageFind::CreatePageFind( const IPDF_TextPage* pTextPage) { return pTextPage ? new CPDF_TextPageFind(pTextPage) : nullptr; } IPDF_LinkExtract* IPDF_LinkExtract::CreateLinkExtract() { return new CPDF_LinkExtract(); } #define TEXT_BLANK_CHAR L' ' #define TEXT_LINEFEED_CHAR L'\n' #define TEXT_RETURN_CHAR L'\r' #define TEXT_EMPTY L"" #define TEXT_BLANK L" " #define TEXT_RETURN_LINEFEED L"\r\n" #define TEXT_LINEFEED L"\n" #define TEXT_CHARRATIO_GAPDELTA 0.070 CPDF_TextPage::CPDF_TextPage(const CPDF_Page* pPage, int flags) : m_pPage(pPage), m_charList(512), m_TempCharList(50), m_parserflag(flags), m_pPreTextObj(nullptr), m_bIsParsed(false), m_TextlineDir(-1), m_CurlineRect(0, 0, 0, 0) { m_TextBuf.EstimateSize(0, 10240); pPage->GetDisplayMatrix(m_DisplayMatrix, 0, 0, (int)pPage->GetPageWidth(), (int)pPage->GetPageHeight(), 0); } void CPDF_TextPage::NormalizeObjects(FX_BOOL bNormalize) { m_ParseOptions.m_bNormalizeObjs = bNormalize; } bool CPDF_TextPage::IsControlChar(const PAGECHAR_INFO& charInfo) { switch (charInfo.m_Unicode) { case 0x2: case 0x3: case 0x93: case 0x94: case 0x96: case 0x97: case 0x98: case 0xfffe: return charInfo.m_Flag != FPDFTEXT_CHAR_HYPHEN; default: return false; } } FX_BOOL CPDF_TextPage::ParseTextPage() { m_bIsParsed = false; if (!m_pPage) return FALSE; m_TextBuf.Clear(); m_charList.RemoveAll(); m_pPreTextObj = NULL; ProcessObject(); m_bIsParsed = true; if (!m_ParseOptions.m_bGetCharCodeOnly) { m_CharIndex.RemoveAll(); int nCount = m_charList.GetSize(); if (nCount) { m_CharIndex.Add(0); } for (int i = 0; i < nCount; i++) { int indexSize = m_CharIndex.GetSize(); FX_BOOL bNormal = FALSE; PAGECHAR_INFO charinfo = *(PAGECHAR_INFO*)m_charList.GetAt(i); if (charinfo.m_Flag == FPDFTEXT_CHAR_GENERATED) { bNormal = TRUE; } else if (charinfo.m_Unicode == 0 || IsControlChar(charinfo)) bNormal = FALSE; else { bNormal = TRUE; } if (bNormal) { if (indexSize % 2) { m_CharIndex.Add(1); } else { if (indexSize <= 0) { continue; } m_CharIndex.SetAt(indexSize - 1, m_CharIndex.GetAt(indexSize - 1) + 1); } } else { if (indexSize % 2) { if (indexSize <= 0) { continue; } m_CharIndex.SetAt(indexSize - 1, i + 1); } else { m_CharIndex.Add(i + 1); } } } int indexSize = m_CharIndex.GetSize(); if (indexSize % 2) { m_CharIndex.RemoveAt(indexSize - 1); } } return TRUE; } int CPDF_TextPage::CountChars() const { if (m_ParseOptions.m_bGetCharCodeOnly) { return m_TextBuf.GetSize(); } return m_charList.GetSize(); } int CPDF_TextPage::CharIndexFromTextIndex(int TextIndex) const { int indexSize = m_CharIndex.GetSize(); int count = 0; for (int i = 0; i < indexSize; i += 2) { count += m_CharIndex.GetAt(i + 1); if (count > TextIndex) { return TextIndex - count + m_CharIndex.GetAt(i + 1) + m_CharIndex.GetAt(i); } } return -1; } int CPDF_TextPage::TextIndexFromCharIndex(int CharIndex) const { int indexSize = m_CharIndex.GetSize(); int count = 0; for (int i = 0; i < indexSize; i += 2) { count += m_CharIndex.GetAt(i + 1); if (m_CharIndex.GetAt(i + 1) + m_CharIndex.GetAt(i) > CharIndex) { if (CharIndex - m_CharIndex.GetAt(i) < 0) { return -1; } return CharIndex - m_CharIndex.GetAt(i) + count - m_CharIndex.GetAt(i + 1); } } return -1; } void CPDF_TextPage::GetRectArray(int start, int nCount, CFX_RectArray& rectArray) const { if (m_ParseOptions.m_bGetCharCodeOnly) { return; } if (start < 0 || nCount == 0) { return; } if (!m_bIsParsed) { return; } PAGECHAR_INFO info_curchar; CPDF_TextObject* pCurObj = NULL; CFX_FloatRect rect; int curPos = start; FX_BOOL flagNewRect = TRUE; if (nCount + start > m_charList.GetSize() || nCount == -1) { nCount = m_charList.GetSize() - start; } while (nCount--) { info_curchar = *(PAGECHAR_INFO*)m_charList.GetAt(curPos++); if (info_curchar.m_Flag == FPDFTEXT_CHAR_GENERATED) { continue; } if (info_curchar.m_CharBox.Width() < 0.01 || info_curchar.m_CharBox.Height() < 0.01) { continue; } if (!pCurObj) { pCurObj = info_curchar.m_pTextObj; } if (pCurObj != info_curchar.m_pTextObj) { rectArray.Add(rect); pCurObj = info_curchar.m_pTextObj; flagNewRect = TRUE; } if (flagNewRect) { FX_FLOAT orgX = info_curchar.m_OriginX, orgY = info_curchar.m_OriginY; CFX_AffineMatrix matrix, matrix_reverse; info_curchar.m_pTextObj->GetTextMatrix(&matrix); matrix.Concat(info_curchar.m_Matrix); matrix_reverse.SetReverse(matrix); matrix_reverse.Transform(orgX, orgY); rect.left = info_curchar.m_CharBox.left; rect.right = info_curchar.m_CharBox.right; if (pCurObj->GetFont()->GetTypeDescent()) { rect.bottom = orgY + pCurObj->GetFont()->GetTypeDescent() * pCurObj->GetFontSize() / 1000; FX_FLOAT xPosTemp = orgX; matrix.Transform(xPosTemp, rect.bottom); } else { rect.bottom = info_curchar.m_CharBox.bottom; } if (pCurObj->GetFont()->GetTypeAscent()) { rect.top = orgY + pCurObj->GetFont()->GetTypeAscent() * pCurObj->GetFontSize() / 1000; FX_FLOAT xPosTemp = orgX + GetCharWidth(info_curchar.m_CharCode, pCurObj->GetFont()) * pCurObj->GetFontSize() / 1000; matrix.Transform(xPosTemp, rect.top); } else { rect.top = info_curchar.m_CharBox.top; } flagNewRect = FALSE; rect = info_curchar.m_CharBox; rect.Normalize(); } else { info_curchar.m_CharBox.Normalize(); if (rect.left > info_curchar.m_CharBox.left) { rect.left = info_curchar.m_CharBox.left; } if (rect.right < info_curchar.m_CharBox.right) { rect.right = info_curchar.m_CharBox.right; } if (rect.top < info_curchar.m_CharBox.top) { rect.top = info_curchar.m_CharBox.top; } if (rect.bottom > info_curchar.m_CharBox.bottom) { rect.bottom = info_curchar.m_CharBox.bottom; } } } rectArray.Add(rect); return; } int CPDF_TextPage::GetIndexAtPos(CPDF_Point point, FX_FLOAT xTolerance, FX_FLOAT yTolerance) const { if (m_ParseOptions.m_bGetCharCodeOnly || !m_bIsParsed) return -3; int pos = 0; int NearPos = -1; double xdif = 5000, ydif = 5000; while (pos < m_charList.GetSize()) { PAGECHAR_INFO charinfo = *(PAGECHAR_INFO*)(m_charList.GetAt(pos)); CFX_FloatRect charrect = charinfo.m_CharBox; if (charrect.Contains(point.x, point.y)) { break; } if (xTolerance > 0 || yTolerance > 0) { CFX_FloatRect charRectExt; charrect.Normalize(); charRectExt.left = charrect.left - xTolerance / 2; charRectExt.right = charrect.right + xTolerance / 2; charRectExt.top = charrect.top + yTolerance / 2; charRectExt.bottom = charrect.bottom - yTolerance / 2; if (charRectExt.Contains(point.x, point.y)) { double curXdif, curYdif; curXdif = FXSYS_fabs(point.x - charrect.left) < FXSYS_fabs(point.x - charrect.right) ? FXSYS_fabs(point.x - charrect.left) : FXSYS_fabs(point.x - charrect.right); curYdif = FXSYS_fabs(point.y - charrect.bottom) < FXSYS_fabs(point.y - charrect.top) ? FXSYS_fabs(point.y - charrect.bottom) : FXSYS_fabs(point.y - charrect.top); if (curYdif + curXdif < xdif + ydif) { ydif = curYdif; xdif = curXdif; NearPos = pos; } } } ++pos; } if (pos >= m_charList.GetSize()) { pos = NearPos; } return pos; } CFX_WideString CPDF_TextPage::GetTextByRect(const CFX_FloatRect& rect) const { CFX_WideString strText; if (m_ParseOptions.m_bGetCharCodeOnly || !m_bIsParsed) return strText; int nCount = m_charList.GetSize(); int pos = 0; FX_FLOAT posy = 0; FX_BOOL IsContainPreChar = FALSE; FX_BOOL ISAddLineFeed = FALSE; while (pos < nCount) { PAGECHAR_INFO charinfo = *(PAGECHAR_INFO*)m_charList.GetAt(pos++); if (IsRectIntersect(rect, charinfo.m_CharBox)) { if (FXSYS_fabs(posy - charinfo.m_OriginY) > 0 && !IsContainPreChar && ISAddLineFeed) { posy = charinfo.m_OriginY; if (strText.GetLength() > 0) { strText += L"\r\n"; } } IsContainPreChar = TRUE; ISAddLineFeed = FALSE; if (charinfo.m_Unicode) { strText += charinfo.m_Unicode; } } else if (charinfo.m_Unicode == 32) { if (IsContainPreChar && charinfo.m_Unicode) { strText += charinfo.m_Unicode; IsContainPreChar = FALSE; ISAddLineFeed = FALSE; } } else { IsContainPreChar = FALSE; ISAddLineFeed = TRUE; } } return strText; } void CPDF_TextPage::GetRectsArrayByRect(const CFX_FloatRect& rect, CFX_RectArray& resRectArray) const { if (m_ParseOptions.m_bGetCharCodeOnly || !m_bIsParsed) return; CFX_FloatRect curRect; FX_BOOL flagNewRect = TRUE; CPDF_TextObject* pCurObj = NULL; int nCount = m_charList.GetSize(); int pos = 0; while (pos < nCount) { PAGECHAR_INFO info_curchar = *(PAGECHAR_INFO*)m_charList.GetAt(pos++); if (info_curchar.m_Flag == FPDFTEXT_CHAR_GENERATED) { continue; } if (IsRectIntersect(rect, info_curchar.m_CharBox)) { if (!pCurObj) { pCurObj = info_curchar.m_pTextObj; } if (pCurObj != info_curchar.m_pTextObj) { resRectArray.Add(curRect); pCurObj = info_curchar.m_pTextObj; flagNewRect = TRUE; } if (flagNewRect) { curRect = info_curchar.m_CharBox; flagNewRect = FALSE; curRect.Normalize(); } else { info_curchar.m_CharBox.Normalize(); if (curRect.left > info_curchar.m_CharBox.left) { curRect.left = info_curchar.m_CharBox.left; } if (curRect.right < info_curchar.m_CharBox.right) { curRect.right = info_curchar.m_CharBox.right; } if (curRect.top < info_curchar.m_CharBox.top) { curRect.top = info_curchar.m_CharBox.top; } if (curRect.bottom > info_curchar.m_CharBox.bottom) { curRect.bottom = info_curchar.m_CharBox.bottom; } } } } resRectArray.Add(curRect); return; } int CPDF_TextPage::GetIndexAtPos(FX_FLOAT x, FX_FLOAT y, FX_FLOAT xTolerance, FX_FLOAT yTolerance) const { if (m_ParseOptions.m_bGetCharCodeOnly) { return -3; } CPDF_Point point(x, y); return GetIndexAtPos(point, xTolerance, yTolerance); } void CPDF_TextPage::GetCharInfo(int index, FPDF_CHAR_INFO& info) const { if (m_ParseOptions.m_bGetCharCodeOnly || !m_bIsParsed) return; if (index < 0 || index >= m_charList.GetSize()) return; PAGECHAR_INFO charinfo; charinfo = *(PAGECHAR_INFO*)m_charList.GetAt(index); info.m_Charcode = charinfo.m_CharCode; info.m_OriginX = charinfo.m_OriginX; info.m_OriginY = charinfo.m_OriginY; info.m_Unicode = charinfo.m_Unicode; info.m_Flag = charinfo.m_Flag; info.m_CharBox = charinfo.m_CharBox; info.m_pTextObj = charinfo.m_pTextObj; if (charinfo.m_pTextObj && charinfo.m_pTextObj->GetFont()) { info.m_FontSize = charinfo.m_pTextObj->GetFontSize(); } info.m_Matrix.Copy(charinfo.m_Matrix); return; } void CPDF_TextPage::CheckMarkedContentObject(int32_t& start, int32_t& nCount) const { PAGECHAR_INFO charinfo = *(PAGECHAR_INFO*)m_charList.GetAt(start); PAGECHAR_INFO charinfo2 = *(PAGECHAR_INFO*)m_charList.GetAt(start + nCount - 1); if (FPDFTEXT_CHAR_PIECE != charinfo.m_Flag && FPDFTEXT_CHAR_PIECE != charinfo2.m_Flag) { return; } if (FPDFTEXT_CHAR_PIECE == charinfo.m_Flag) { PAGECHAR_INFO charinfo1 = charinfo; int startIndex = start; while (FPDFTEXT_CHAR_PIECE == charinfo1.m_Flag && charinfo1.m_Index == charinfo.m_Index) { startIndex--; if (startIndex < 0) { break; } charinfo1 = *(PAGECHAR_INFO*)m_charList.GetAt(startIndex); } startIndex++; start = startIndex; } if (FPDFTEXT_CHAR_PIECE == charinfo2.m_Flag) { PAGECHAR_INFO charinfo3 = charinfo2; int endIndex = start + nCount - 1; while (FPDFTEXT_CHAR_PIECE == charinfo3.m_Flag && charinfo3.m_Index == charinfo2.m_Index) { endIndex++; if (endIndex >= m_charList.GetSize()) { break; } charinfo3 = *(PAGECHAR_INFO*)m_charList.GetAt(endIndex); } endIndex--; nCount = endIndex - start + 1; } } CFX_WideString CPDF_TextPage::GetPageText(int start, int nCount) const { if (!m_bIsParsed || nCount == 0) return L""; if (start < 0) start = 0; if (nCount == -1) { nCount = m_charList.GetSize() - start; return m_TextBuf.GetWideString().Mid(start, m_TextBuf.GetWideString().GetLength()); } if (nCount <= 0 || m_charList.GetSize() <= 0) { return L""; } if (nCount + start > m_charList.GetSize() - 1) { nCount = m_charList.GetSize() - start; } if (nCount <= 0) { return L""; } CheckMarkedContentObject(start, nCount); int startindex = 0; PAGECHAR_INFO charinfo = *(PAGECHAR_INFO*)m_charList.GetAt(start); int startOffset = 0; while (charinfo.m_Index == -1) { startOffset++; if (startOffset > nCount || start + startOffset >= m_charList.GetSize()) { return L""; } charinfo = *(PAGECHAR_INFO*)m_charList.GetAt(start + startOffset); } startindex = charinfo.m_Index; charinfo = *(PAGECHAR_INFO*)m_charList.GetAt(start + nCount - 1); int nCountOffset = 0; while (charinfo.m_Index == -1) { nCountOffset++; if (nCountOffset >= nCount) { return L""; } charinfo = *(PAGECHAR_INFO*)m_charList.GetAt(start + nCount - nCountOffset - 1); } nCount = start + nCount - nCountOffset - startindex; if (nCount <= 0) { return L""; } return m_TextBuf.GetWideString().Mid(startindex, nCount); } int CPDF_TextPage::CountRects(int start, int nCount) { if (m_ParseOptions.m_bGetCharCodeOnly || !m_bIsParsed || start < 0) return -1; if (nCount == -1 || nCount + start > m_charList.GetSize()) { nCount = m_charList.GetSize() - start; } m_SelRects.RemoveAll(); GetRectArray(start, nCount, m_SelRects); return m_SelRects.GetSize(); } void CPDF_TextPage::GetRect(int rectIndex, FX_FLOAT& left, FX_FLOAT& top, FX_FLOAT& right, FX_FLOAT& bottom) const { if (m_ParseOptions.m_bGetCharCodeOnly || !m_bIsParsed) return; if (rectIndex < 0 || rectIndex >= m_SelRects.GetSize()) return; left = m_SelRects.GetAt(rectIndex).left; top = m_SelRects.GetAt(rectIndex).top; right = m_SelRects.GetAt(rectIndex).right; bottom = m_SelRects.GetAt(rectIndex).bottom; } FX_BOOL CPDF_TextPage::GetBaselineRotate(int start, int end, int& Rotate) { if (m_ParseOptions.m_bGetCharCodeOnly) { return FALSE; } if (end == start) { return FALSE; } FX_FLOAT dx, dy; FPDF_CHAR_INFO info1, info2; GetCharInfo(start, info1); GetCharInfo(end, info2); while (info2.m_CharBox.Width() == 0 || info2.m_CharBox.Height() == 0) { end--; if (end <= start) { return FALSE; } GetCharInfo(end, info2); } dx = (info2.m_OriginX - info1.m_OriginX); dy = (info2.m_OriginY - info1.m_OriginY); if (dx == 0) { if (dy > 0) { Rotate = 90; } else if (dy < 0) { Rotate = 270; } else { Rotate = 0; } } else { float a = FXSYS_atan2(dy, dx); Rotate = (int)(a * 180 / FX_PI + 0.5); } if (Rotate < 0) { Rotate = -Rotate; } else if (Rotate > 0) { Rotate = 360 - Rotate; } return TRUE; } FX_BOOL CPDF_TextPage::GetBaselineRotate(const CFX_FloatRect& rect, int& Rotate) { if (m_ParseOptions.m_bGetCharCodeOnly) { return FALSE; } int start, end, count, n = CountBoundedSegments(rect.left, rect.top, rect.right, rect.bottom, TRUE); if (n < 1) { return FALSE; } if (n > 1) { GetBoundedSegment(n - 1, start, count); end = start + count - 1; GetBoundedSegment(0, start, count); } else { GetBoundedSegment(0, start, count); end = start + count - 1; } return GetBaselineRotate(start, end, Rotate); } FX_BOOL CPDF_TextPage::GetBaselineRotate(int rectIndex, int& Rotate) { if (m_ParseOptions.m_bGetCharCodeOnly || !m_bIsParsed) return FALSE; if (rectIndex < 0 || rectIndex > m_SelRects.GetSize()) return FALSE; CFX_FloatRect rect = m_SelRects.GetAt(rectIndex); return GetBaselineRotate(rect, Rotate); } int CPDF_TextPage::CountBoundedSegments(FX_FLOAT left, FX_FLOAT top, FX_FLOAT right, FX_FLOAT bottom, FX_BOOL bContains) { if (m_ParseOptions.m_bGetCharCodeOnly) return -1; m_Segment.RemoveAll(); if (!m_bIsParsed) return -1; CFX_FloatRect rect(left, bottom, right, top); rect.Normalize(); int nCount = m_charList.GetSize(); int pos = 0; FPDF_SEGMENT segment; segment.m_Start = 0; segment.m_nCount = 0; int segmentStatus = 0; FX_BOOL IsContainPreChar = FALSE; while (pos < nCount) { PAGECHAR_INFO charinfo = *(PAGECHAR_INFO*)m_charList.GetAt(pos); if (bContains && rect.Contains(charinfo.m_CharBox)) { if (segmentStatus == 0 || segmentStatus == 2) { segment.m_Start = pos; segment.m_nCount = 1; segmentStatus = 1; } else if (segmentStatus == 1) { segment.m_nCount++; } IsContainPreChar = TRUE; } else if (!bContains && (IsRectIntersect(rect, charinfo.m_CharBox) || rect.Contains(charinfo.m_OriginX, charinfo.m_OriginY))) { if (segmentStatus == 0 || segmentStatus == 2) { segment.m_Start = pos; segment.m_nCount = 1; segmentStatus = 1; } else if (segmentStatus == 1) { segment.m_nCount++; } IsContainPreChar = TRUE; } else if (charinfo.m_Unicode == 32) { if (IsContainPreChar == TRUE) { if (segmentStatus == 0 || segmentStatus == 2) { segment.m_Start = pos; segment.m_nCount = 1; segmentStatus = 1; } else if (segmentStatus == 1) { segment.m_nCount++; } IsContainPreChar = FALSE; } else { if (segmentStatus == 1) { segmentStatus = 2; m_Segment.Add(segment); segment.m_Start = 0; segment.m_nCount = 0; } } } else { if (segmentStatus == 1) { segmentStatus = 2; m_Segment.Add(segment); segment.m_Start = 0; segment.m_nCount = 0; } IsContainPreChar = FALSE; } pos++; } if (segmentStatus == 1) { segmentStatus = 2; m_Segment.Add(segment); segment.m_Start = 0; segment.m_nCount = 0; } return m_Segment.GetSize(); } void CPDF_TextPage::GetBoundedSegment(int index, int& start, int& count) const { if (m_ParseOptions.m_bGetCharCodeOnly) { return; } if (index < 0 || index >= m_Segment.GetSize()) { return; } start = m_Segment.GetAt(index).m_Start; count = m_Segment.GetAt(index).m_nCount; } int CPDF_TextPage::GetWordBreak(int index, int direction) const { if (m_ParseOptions.m_bGetCharCodeOnly || !m_bIsParsed) return -1; if (direction != FPDFTEXT_LEFT && direction != FPDFTEXT_RIGHT) return -1; if (index < 0 || index >= m_charList.GetSize()) return -1; PAGECHAR_INFO charinfo; charinfo = *(PAGECHAR_INFO*)m_charList.GetAt(index); if (charinfo.m_Index == -1 || charinfo.m_Flag == FPDFTEXT_CHAR_GENERATED) { return index; } if (!IsLetter(charinfo.m_Unicode)) { return index; } int breakPos = index; if (direction == FPDFTEXT_LEFT) { while (--breakPos > 0) { charinfo = *(PAGECHAR_INFO*)m_charList.GetAt(breakPos); if (!IsLetter(charinfo.m_Unicode)) { return breakPos; } } } else if (direction == FPDFTEXT_RIGHT) { while (++breakPos < m_charList.GetSize()) { charinfo = *(PAGECHAR_INFO*)m_charList.GetAt(breakPos); if (!IsLetter(charinfo.m_Unicode)) { return breakPos; } } } return breakPos; } int32_t CPDF_TextPage::FindTextlineFlowDirection() { if (!m_pPage) { return -1; } const int32_t nPageWidth = (int32_t)((CPDF_Page*)m_pPage)->GetPageWidth(); const int32_t nPageHeight = (int32_t)((CPDF_Page*)m_pPage)->GetPageHeight(); CFX_ByteArray nHorizontalMask; if (!nHorizontalMask.SetSize(nPageWidth)) { return -1; } uint8_t* pDataH = nHorizontalMask.GetData(); CFX_ByteArray nVerticalMask; if (!nVerticalMask.SetSize(nPageHeight)) { return -1; } uint8_t* pDataV = nVerticalMask.GetData(); int32_t index = 0; FX_FLOAT fLineHeight = 0.0f; CPDF_PageObject* pPageObj = NULL; FX_POSITION pos = NULL; pos = m_pPage->GetFirstObjectPosition(); if (!pos) { return -1; } while (pos) { pPageObj = m_pPage->GetNextObject(pos); if (NULL == pPageObj) { continue; } if (PDFPAGE_TEXT != pPageObj->m_Type) { continue; } int32_t minH = (int32_t)pPageObj->m_Left < 0 ? 0 : (int32_t)pPageObj->m_Left; int32_t maxH = (int32_t)pPageObj->m_Right > nPageWidth ? nPageWidth : (int32_t)pPageObj->m_Right; int32_t minV = (int32_t)pPageObj->m_Bottom < 0 ? 0 : (int32_t)pPageObj->m_Bottom; int32_t maxV = (int32_t)pPageObj->m_Top > nPageHeight ? nPageHeight : (int32_t)pPageObj->m_Top; if (minH >= maxH || minV >= maxV) { continue; } FXSYS_memset(pDataH + minH, 1, maxH - minH); FXSYS_memset(pDataV + minV, 1, maxV - minV); if (fLineHeight <= 0.0f) { fLineHeight = pPageObj->m_Top - pPageObj->m_Bottom; } pPageObj = NULL; } int32_t nStartH = 0; int32_t nEndH = 0; FX_FLOAT nSumH = 0.0f; for (index = 0; index < nPageWidth; index++) if (1 == nHorizontalMask[index]) { break; } nStartH = index; for (index = nPageWidth; index > 0; index--) if (1 == nHorizontalMask[index - 1]) { break; } nEndH = index; for (index = nStartH; index < nEndH; index++) { nSumH += nHorizontalMask[index]; } nSumH /= nEndH - nStartH; int32_t nStartV = 0; int32_t nEndV = 0; FX_FLOAT nSumV = 0.0f; for (index = 0; index < nPageHeight; index++) if (1 == nVerticalMask[index]) { break; } nStartV = index; for (index = nPageHeight; index > 0; index--) if (1 == nVerticalMask[index - 1]) { break; } nEndV = index; for (index = nStartV; index < nEndV; index++) { nSumV += nVerticalMask[index]; } nSumV /= nEndV - nStartV; if ((nEndV - nStartV) < (int32_t)(2 * fLineHeight)) { return 0; } if ((nEndH - nStartH) < (int32_t)(2 * fLineHeight)) { return 1; } if (nSumH > 0.8f) { return 0; } if (nSumH - nSumV > 0.0f) { return 0; } if (nSumV - nSumH > 0.0f) { return 1; } return -1; } void CPDF_TextPage::ProcessObject() { CPDF_PageObject* pPageObj = NULL; if (!m_pPage) { return; } FX_POSITION pos; pos = m_pPage->GetFirstObjectPosition(); if (!pos) { return; } m_TextlineDir = FindTextlineFlowDirection(); int nCount = 0; while (pos) { pPageObj = m_pPage->GetNextObject(pos); if (pPageObj) { if (pPageObj->m_Type == PDFPAGE_TEXT) { CFX_AffineMatrix matrix; ProcessTextObject((CPDF_TextObject*)pPageObj, matrix, pos); nCount++; } else if (pPageObj->m_Type == PDFPAGE_FORM) { CFX_AffineMatrix formMatrix(1, 0, 0, 1, 0, 0); ProcessFormObject((CPDF_FormObject*)pPageObj, formMatrix); } } pPageObj = NULL; } int count = m_LineObj.GetSize(); for (int i = 0; i < count; i++) { ProcessTextObject(m_LineObj.GetAt(i)); } m_LineObj.RemoveAll(); CloseTempLine(); } void CPDF_TextPage::ProcessFormObject(CPDF_FormObject* pFormObj, const CFX_AffineMatrix& formMatrix) { CPDF_PageObject* pPageObj = NULL; FX_POSITION pos; if (!pFormObj) { return; } pos = pFormObj->m_pForm->GetFirstObjectPosition(); if (!pos) { return; } CFX_AffineMatrix curFormMatrix; curFormMatrix.Copy(pFormObj->m_FormMatrix); curFormMatrix.Concat(formMatrix); while (pos) { pPageObj = pFormObj->m_pForm->GetNextObject(pos); if (pPageObj) { if (pPageObj->m_Type == PDFPAGE_TEXT) { ProcessTextObject((CPDF_TextObject*)pPageObj, curFormMatrix, pos); } else if (pPageObj->m_Type == PDFPAGE_FORM) { ProcessFormObject((CPDF_FormObject*)pPageObj, curFormMatrix); } } pPageObj = NULL; } } int CPDF_TextPage::GetCharWidth(FX_DWORD charCode, CPDF_Font* pFont) const { if (charCode == -1) { return 0; } int w = pFont->GetCharWidthF(charCode); if (w == 0) { CFX_ByteString str; pFont->AppendChar(str, charCode); w = pFont->GetStringWidth(str, 1); if (w == 0) { FX_RECT BBox; pFont->GetCharBBox(charCode, BBox); w = BBox.right - BBox.left; } } return w; } void CPDF_TextPage::OnPiece(CFX_BidiChar* pBidi, CFX_WideString& str) { int32_t start, count; CFX_BidiChar::Direction ret = pBidi->GetBidiInfo(&start, &count); if (ret == CFX_BidiChar::RIGHT) { for (int i = start + count - 1; i >= start; i--) { m_TextBuf.AppendChar(str.GetAt(i)); m_charList.Add(*(PAGECHAR_INFO*)m_TempCharList.GetAt(i)); } } else { int end = start + count; for (int i = start; i < end; i++) { m_TextBuf.AppendChar(str.GetAt(i)); m_charList.Add(*(PAGECHAR_INFO*)m_TempCharList.GetAt(i)); } } } void CPDF_TextPage::AddCharInfoByLRDirection(CFX_WideString& str, int i) { PAGECHAR_INFO Info = *(PAGECHAR_INFO*)m_TempCharList.GetAt(i); FX_WCHAR wChar = str.GetAt(i); if (!IsControlChar(Info)) { Info.m_Index = m_TextBuf.GetLength(); if (wChar >= 0xFB00 && wChar <= 0xFB06) { FX_WCHAR* pDst = NULL; FX_STRSIZE nCount = FX_Unicode_GetNormalization(wChar, pDst); if (nCount >= 1) { pDst = FX_Alloc(FX_WCHAR, nCount); FX_Unicode_GetNormalization(wChar, pDst); for (int nIndex = 0; nIndex < nCount; nIndex++) { PAGECHAR_INFO Info2 = Info; Info2.m_Unicode = pDst[nIndex]; Info2.m_Flag = FPDFTEXT_CHAR_PIECE; m_TextBuf.AppendChar(Info2.m_Unicode); if (!m_ParseOptions.m_bGetCharCodeOnly) { m_charList.Add(Info2); } } FX_Free(pDst); return; } } m_TextBuf.AppendChar(wChar); } else { Info.m_Index = -1; } if (!m_ParseOptions.m_bGetCharCodeOnly) { m_charList.Add(Info); } } void CPDF_TextPage::AddCharInfoByRLDirection(CFX_WideString& str, int i) { PAGECHAR_INFO Info = *(PAGECHAR_INFO*)m_TempCharList.GetAt(i); if (!IsControlChar(Info)) { Info.m_Index = m_TextBuf.GetLength(); FX_WCHAR wChar = FX_GetMirrorChar(str.GetAt(i), TRUE, FALSE); FX_WCHAR* pDst = NULL; FX_STRSIZE nCount = FX_Unicode_GetNormalization(wChar, pDst); if (nCount >= 1) { pDst = FX_Alloc(FX_WCHAR, nCount); FX_Unicode_GetNormalization(wChar, pDst); for (int nIndex = 0; nIndex < nCount; nIndex++) { PAGECHAR_INFO Info2 = Info; Info2.m_Unicode = pDst[nIndex]; Info2.m_Flag = FPDFTEXT_CHAR_PIECE; m_TextBuf.AppendChar(Info2.m_Unicode); if (!m_ParseOptions.m_bGetCharCodeOnly) { m_charList.Add(Info2); } } FX_Free(pDst); return; } Info.m_Unicode = wChar; m_TextBuf.AppendChar(Info.m_Unicode); } else { Info.m_Index = -1; } if (!m_ParseOptions.m_bGetCharCodeOnly) { m_charList.Add(Info); } } void CPDF_TextPage::CloseTempLine() { int count1 = m_TempCharList.GetSize(); if (count1 <= 0) { return; } nonstd::unique_ptr<CFX_BidiChar> pBidiChar(new CFX_BidiChar); CFX_WideString str = m_TempTextBuf.GetWideString(); CFX_WordArray order; FX_BOOL bR2L = FALSE; int32_t start = 0, count = 0; int nR2L = 0, nL2R = 0; FX_BOOL bPrevSpace = FALSE; for (int i = 0; i < str.GetLength(); i++) { if (str.GetAt(i) == 32) { if (bPrevSpace) { m_TempTextBuf.Delete(i, 1); m_TempCharList.Delete(i); str.Delete(i); count1--; i--; continue; } bPrevSpace = TRUE; } else { bPrevSpace = FALSE; } if (pBidiChar->AppendChar(str.GetAt(i))) { CFX_BidiChar::Direction ret = pBidiChar->GetBidiInfo(&start, &count); order.Add(start); order.Add(count); order.Add(ret); if (!bR2L) { if (ret == CFX_BidiChar::RIGHT) { nR2L++; } else if (ret == CFX_BidiChar::LEFT) { nL2R++; } } } } if (pBidiChar->EndChar()) { CFX_BidiChar::Direction ret = pBidiChar->GetBidiInfo(&start, &count); order.Add(start); order.Add(count); order.Add(ret); if (!bR2L) { if (ret == CFX_BidiChar::RIGHT) { nR2L++; } else if (ret == CFX_BidiChar::LEFT) { nL2R++; } } } if (nR2L > 0 && nR2L >= nL2R) { bR2L = TRUE; } if (m_parserflag == FPDFTEXT_RLTB || bR2L) { int count = order.GetSize(); for (int i = count - 1; i > 0; i -= 3) { int ret = order.GetAt(i); int start = order.GetAt(i - 2); int count1 = order.GetAt(i - 1); if (ret == 2 || ret == 0) { for (int j = start + count1 - 1; j >= start; j--) { AddCharInfoByRLDirection(str, j); } } else { int j = i; FX_BOOL bSymbol = FALSE; while (j > 0 && order.GetAt(j) != 2) { bSymbol = !order.GetAt(j); j -= 3; } int end = start + count1; int n = 0; if (bSymbol) { n = j + 6; } else { n = j + 3; } if (n >= i) { for (int m = start; m < end; m++) { AddCharInfoByLRDirection(str, m); } } else { j = i; i = n; for (; n <= j; n += 3) { int start = order.GetAt(n - 2); int count1 = order.GetAt(n - 1); int end = start + count1; for (int m = start; m < end; m++) { AddCharInfoByLRDirection(str, m); } } } } } } else { int count = order.GetSize(); FX_BOOL bL2R = FALSE; for (int i = 0; i < count; i += 3) { int ret = order.GetAt(i + 2); int start = order.GetAt(i); int count1 = order.GetAt(i + 1); if (ret == 2 || (i == 0 && ret == 0 && !bL2R)) { int j = i + 3; while (bR2L && j < count) { if (order.GetAt(j + 2) == 1) { break; } else { j += 3; } } if (j == 3) { i = -3; bL2R = TRUE; continue; } int end = m_TempCharList.GetSize() - 1; if (j < count) { end = order.GetAt(j) - 1; } i = j - 3; for (int n = end; n >= start; n--) { AddCharInfoByRLDirection(str, n); } } else { int end = start + count1; for (int n = start; n < end; n++) { AddCharInfoByLRDirection(str, n); } } } } order.RemoveAll(); m_TempCharList.RemoveAll(); m_TempTextBuf.Delete(0, m_TempTextBuf.GetLength()); } void CPDF_TextPage::ProcessTextObject(CPDF_TextObject* pTextObj, const CFX_AffineMatrix& formMatrix, FX_POSITION ObjPos) { CFX_FloatRect re(pTextObj->m_Left, pTextObj->m_Bottom, pTextObj->m_Right, pTextObj->m_Top); if (FXSYS_fabs(pTextObj->m_Right - pTextObj->m_Left) < 0.01f) { return; } int count = m_LineObj.GetSize(); PDFTEXT_Obj Obj; Obj.m_pTextObj = pTextObj; Obj.m_formMatrix = formMatrix; if (count == 0) { m_LineObj.Add(Obj); return; } if (IsSameAsPreTextObject(pTextObj, ObjPos)) { return; } PDFTEXT_Obj prev_Obj = m_LineObj.GetAt(count - 1); CPDF_TextObjectItem item; int nItem = prev_Obj.m_pTextObj->CountItems(); prev_Obj.m_pTextObj->GetItemInfo(nItem - 1, &item); FX_FLOAT prev_width = GetCharWidth(item.m_CharCode, prev_Obj.m_pTextObj->GetFont()) * prev_Obj.m_pTextObj->GetFontSize() / 1000; CFX_AffineMatrix prev_matrix; prev_Obj.m_pTextObj->GetTextMatrix(&prev_matrix); prev_width = FXSYS_fabs(prev_width); prev_matrix.Concat(prev_Obj.m_formMatrix); prev_width = prev_matrix.TransformDistance(prev_width); pTextObj->GetItemInfo(0, &item); FX_FLOAT this_width = GetCharWidth(item.m_CharCode, pTextObj->GetFont()) * pTextObj->GetFontSize() / 1000; this_width = FXSYS_fabs(this_width); CFX_AffineMatrix this_matrix; pTextObj->GetTextMatrix(&this_matrix); this_width = FXSYS_fabs(this_width); this_matrix.Concat(formMatrix); this_width = this_matrix.TransformDistance(this_width); FX_FLOAT threshold = prev_width > this_width ? prev_width / 4 : this_width / 4; FX_FLOAT prev_x = prev_Obj.m_pTextObj->GetPosX(), prev_y = prev_Obj.m_pTextObj->GetPosY(); prev_Obj.m_formMatrix.Transform(prev_x, prev_y); m_DisplayMatrix.Transform(prev_x, prev_y); FX_FLOAT this_x = pTextObj->GetPosX(), this_y = pTextObj->GetPosY(); formMatrix.Transform(this_x, this_y); m_DisplayMatrix.Transform(this_x, this_y); if (FXSYS_fabs(this_y - prev_y) > threshold * 2) { for (int i = 0; i < count; i++) { ProcessTextObject(m_LineObj.GetAt(i)); } m_LineObj.RemoveAll(); m_LineObj.Add(Obj); return; } int i = 0; if (m_ParseOptions.m_bNormalizeObjs) { for (i = count - 1; i >= 0; i--) { PDFTEXT_Obj prev_Obj = m_LineObj.GetAt(i); CFX_AffineMatrix prev_matrix; prev_Obj.m_pTextObj->GetTextMatrix(&prev_matrix); FX_FLOAT Prev_x = prev_Obj.m_pTextObj->GetPosX(), Prev_y = prev_Obj.m_pTextObj->GetPosY(); prev_Obj.m_formMatrix.Transform(Prev_x, Prev_y); m_DisplayMatrix.Transform(Prev_x, Prev_y); if (this_x >= Prev_x) { if (i == count - 1) { m_LineObj.Add(Obj); } else { m_LineObj.InsertAt(i + 1, Obj); } break; } } if (i < 0) { m_LineObj.InsertAt(0, Obj); } } else { m_LineObj.Add(Obj); } } int32_t CPDF_TextPage::PreMarkedContent(PDFTEXT_Obj Obj) { CPDF_TextObject* pTextObj = Obj.m_pTextObj; CPDF_ContentMarkData* pMarkData = (CPDF_ContentMarkData*)pTextObj->m_ContentMark.GetObject(); if (!pMarkData) { return FPDFTEXT_MC_PASS; } int nContentMark = pMarkData->CountItems(); if (nContentMark < 1) { return FPDFTEXT_MC_PASS; } CFX_WideString actText; FX_BOOL bExist = FALSE; CPDF_Dictionary* pDict = NULL; int n = 0; for (n = 0; n < nContentMark; n++) { CPDF_ContentMarkItem& item = pMarkData->GetItem(n); CFX_ByteString tagStr = (CFX_ByteString)item.GetName(); pDict = (CPDF_Dictionary*)item.GetParam(); CPDF_String* temp = (CPDF_String*)(pDict ? pDict->GetElement(FX_BSTRC("ActualText")) : NULL); if (temp) { bExist = TRUE; actText = temp->GetUnicodeText(); } } if (!bExist) { return FPDFTEXT_MC_PASS; } if (m_pPreTextObj) { if (CPDF_ContentMarkData* pPreMarkData = (CPDF_ContentMarkData*)m_pPreTextObj->m_ContentMark.GetObject()) { if (pPreMarkData->CountItems() == n) { CPDF_ContentMarkItem& item = pPreMarkData->GetItem(n - 1); if (pDict == item.GetParam()) { return FPDFTEXT_MC_DONE; } } } } CPDF_Font* pFont = pTextObj->GetFont(); FX_STRSIZE nItems = actText.GetLength(); if (nItems < 1) { return FPDFTEXT_MC_PASS; } bExist = FALSE; for (FX_STRSIZE i = 0; i < nItems; i++) { FX_WCHAR wChar = actText.GetAt(i); if (-1 == pFont->CharCodeFromUnicode(wChar)) { continue; } else { bExist = TRUE; break; } } if (!bExist) { return FPDFTEXT_MC_PASS; } bExist = FALSE; for (FX_STRSIZE i = 0; i < nItems; i++) { FX_WCHAR wChar = actText.GetAt(i); if ((wChar > 0x80 && wChar < 0xFFFD) || (wChar <= 0x80 && isprint(wChar))) { bExist = TRUE; break; } } if (!bExist) { return FPDFTEXT_MC_DONE; } return FPDFTEXT_MC_DELAY; } void CPDF_TextPage::ProcessMarkedContent(PDFTEXT_Obj Obj) { CPDF_TextObject* pTextObj = Obj.m_pTextObj; CPDF_ContentMarkData* pMarkData = (CPDF_ContentMarkData*)pTextObj->m_ContentMark.GetObject(); if (!pMarkData) { return; } int nContentMark = pMarkData->CountItems(); if (nContentMark < 1) { return; } CFX_WideString actText; CPDF_Dictionary* pDict = NULL; int n = 0; for (n = 0; n < nContentMark; n++) { CPDF_ContentMarkItem& item = pMarkData->GetItem(n); CFX_ByteString tagStr = (CFX_ByteString)item.GetName(); pDict = (CPDF_Dictionary*)item.GetParam(); CPDF_String* temp = (CPDF_String*)(pDict ? pDict->GetElement(FX_BSTRC("ActualText")) : NULL); if (temp) { actText = temp->GetUnicodeText(); } } FX_STRSIZE nItems = actText.GetLength(); if (nItems < 1) { return; } CPDF_Font* pFont = pTextObj->GetFont(); CFX_AffineMatrix formMatrix = Obj.m_formMatrix; CFX_AffineMatrix matrix; pTextObj->GetTextMatrix(&matrix); matrix.Concat(formMatrix); FX_FLOAT fPosX = pTextObj->GetPosX(); FX_FLOAT fPosY = pTextObj->GetPosY(); int nCharInfoIndex = m_TextBuf.GetLength(); CFX_FloatRect charBox; charBox.top = pTextObj->m_Top; charBox.left = pTextObj->m_Left; charBox.right = pTextObj->m_Right; charBox.bottom = pTextObj->m_Bottom; for (FX_STRSIZE k = 0; k < nItems; k++) { FX_WCHAR wChar = actText.GetAt(k); if (wChar <= 0x80 && !isprint(wChar)) { wChar = 0x20; } if (wChar >= 0xFFFD) { continue; } PAGECHAR_INFO charinfo; charinfo.m_OriginX = fPosX; charinfo.m_OriginY = fPosY; charinfo.m_Index = nCharInfoIndex; charinfo.m_Unicode = wChar; charinfo.m_CharCode = pFont->CharCodeFromUnicode(wChar); charinfo.m_Flag = FPDFTEXT_CHAR_PIECE; charinfo.m_pTextObj = pTextObj; charinfo.m_CharBox.top = charBox.top; charinfo.m_CharBox.left = charBox.left; charinfo.m_CharBox.right = charBox.right; charinfo.m_CharBox.bottom = charBox.bottom; charinfo.m_Matrix.Copy(matrix); m_TempTextBuf.AppendChar(wChar); m_TempCharList.Add(charinfo); } } void CPDF_TextPage::FindPreviousTextObject(void) { if (m_TempCharList.GetSize() < 1 && m_charList.GetSize() < 1) { return; } PAGECHAR_INFO preChar; if (m_TempCharList.GetSize() >= 1) { preChar = *(PAGECHAR_INFO*)m_TempCharList.GetAt(m_TempCharList.GetSize() - 1); } else { preChar = *(PAGECHAR_INFO*)m_charList.GetAt(m_charList.GetSize() - 1); } if (preChar.m_pTextObj) { m_pPreTextObj = preChar.m_pTextObj; } } void CPDF_TextPage::ProcessTextObject(PDFTEXT_Obj Obj) { CPDF_TextObject* pTextObj = Obj.m_pTextObj; if (FXSYS_fabs(pTextObj->m_Right - pTextObj->m_Left) < 0.01f) { return; } CFX_AffineMatrix formMatrix = Obj.m_formMatrix; CPDF_Font* pFont = pTextObj->GetFont(); CFX_AffineMatrix matrix; pTextObj->GetTextMatrix(&matrix); matrix.Concat(formMatrix); int32_t bPreMKC = PreMarkedContent(Obj); if (FPDFTEXT_MC_DONE == bPreMKC) { m_pPreTextObj = pTextObj; m_perMatrix.Copy(formMatrix); return; } int result = 0; if (m_pPreTextObj) { result = ProcessInsertObject(pTextObj, formMatrix); if (2 == result) { m_CurlineRect = CFX_FloatRect(Obj.m_pTextObj->m_Left, Obj.m_pTextObj->m_Bottom, Obj.m_pTextObj->m_Right, Obj.m_pTextObj->m_Top); } else { m_CurlineRect.Union( CFX_FloatRect(Obj.m_pTextObj->m_Left, Obj.m_pTextObj->m_Bottom, Obj.m_pTextObj->m_Right, Obj.m_pTextObj->m_Top)); } PAGECHAR_INFO generateChar; if (result == 1) { if (GenerateCharInfo(TEXT_BLANK_CHAR, generateChar)) { if (!formMatrix.IsIdentity()) { generateChar.m_Matrix.Copy(formMatrix); } m_TempTextBuf.AppendChar(TEXT_BLANK_CHAR); m_TempCharList.Add(generateChar); } } else if (result == 2) { CloseTempLine(); if (m_TextBuf.GetSize()) { if (m_ParseOptions.m_bGetCharCodeOnly) { m_TextBuf.AppendChar(TEXT_RETURN_CHAR); m_TextBuf.AppendChar(TEXT_LINEFEED_CHAR); } else { if (GenerateCharInfo(TEXT_RETURN_CHAR, generateChar)) { m_TextBuf.AppendChar(TEXT_RETURN_CHAR); if (!formMatrix.IsIdentity()) { generateChar.m_Matrix.Copy(formMatrix); } m_charList.Add(generateChar); } if (GenerateCharInfo(TEXT_LINEFEED_CHAR, generateChar)) { m_TextBuf.AppendChar(TEXT_LINEFEED_CHAR); if (!formMatrix.IsIdentity()) { generateChar.m_Matrix.Copy(formMatrix); } m_charList.Add(generateChar); } } } } else if (result == 3 && !m_ParseOptions.m_bOutputHyphen) { int32_t nChars = pTextObj->CountChars(); if (nChars == 1) { CPDF_TextObjectItem item; pTextObj->GetCharInfo(0, &item); CFX_WideString wstrItem = pTextObj->GetFont()->UnicodeFromCharCode(item.m_CharCode); if (wstrItem.IsEmpty()) { wstrItem += (FX_WCHAR)item.m_CharCode; } FX_WCHAR curChar = wstrItem.GetAt(0); if (0x2D == curChar || 0xAD == curChar) { return; } } while (m_TempTextBuf.GetSize() > 0 && m_TempTextBuf.GetWideString().GetAt(m_TempTextBuf.GetLength() - 1) == 0x20) { m_TempTextBuf.Delete(m_TempTextBuf.GetLength() - 1, 1); m_TempCharList.Delete(m_TempCharList.GetSize() - 1); } PAGECHAR_INFO* cha = (PAGECHAR_INFO*)m_TempCharList.GetAt(m_TempCharList.GetSize() - 1); m_TempTextBuf.Delete(m_TempTextBuf.GetLength() - 1, 1); cha->m_Unicode = 0x2; cha->m_Flag = FPDFTEXT_CHAR_HYPHEN; m_TempTextBuf.AppendChar(0xfffe); } } else { m_CurlineRect = CFX_FloatRect(Obj.m_pTextObj->m_Left, Obj.m_pTextObj->m_Bottom, Obj.m_pTextObj->m_Right, Obj.m_pTextObj->m_Top); } if (FPDFTEXT_MC_DELAY == bPreMKC) { ProcessMarkedContent(Obj); m_pPreTextObj = pTextObj; m_perMatrix.Copy(formMatrix); return; } m_pPreTextObj = pTextObj; m_perMatrix.Copy(formMatrix); int nItems = pTextObj->CountItems(); FX_FLOAT baseSpace = _CalculateBaseSpace(pTextObj, matrix); const FX_BOOL bR2L = IsRightToLeft(pTextObj, pFont, nItems); const FX_BOOL bIsBidiAndMirrorInverse = bR2L && (matrix.a * matrix.d - matrix.b * matrix.c) < 0; int32_t iBufStartAppend = m_TempTextBuf.GetLength(); int32_t iCharListStartAppend = m_TempCharList.GetSize(); FX_FLOAT spacing = 0; for (int i = 0; i < nItems; i++) { CPDF_TextObjectItem item; PAGECHAR_INFO charinfo; charinfo.m_OriginX = 0; charinfo.m_OriginY = 0; pTextObj->GetItemInfo(i, &item); if (item.m_CharCode == (FX_DWORD)-1) { CFX_WideString str = m_TempTextBuf.GetWideString(); if (str.IsEmpty()) { str = m_TextBuf.GetWideString(); } if (str.IsEmpty() || str.GetAt(str.GetLength() - 1) == TEXT_BLANK_CHAR) { continue; } FX_FLOAT fontsize_h = pTextObj->m_TextState.GetFontSizeH(); spacing = -fontsize_h * item.m_OriginX / 1000; continue; } FX_FLOAT charSpace = pTextObj->m_TextState.GetObject()->m_CharSpace; if (charSpace > 0.001) { spacing += matrix.TransformDistance(charSpace); } else if (charSpace < -0.001) { spacing -= matrix.TransformDistance(FXSYS_fabs(charSpace)); } spacing -= baseSpace; if (spacing && i > 0) { int last_width = 0; FX_FLOAT fontsize_h = pTextObj->m_TextState.GetFontSizeH(); FX_DWORD space_charcode = pFont->CharCodeFromUnicode(' '); FX_FLOAT threshold = 0; if (space_charcode != -1) { threshold = fontsize_h * pFont->GetCharWidthF(space_charcode) / 1000; } if (threshold > fontsize_h / 3) { threshold = 0; } else { threshold /= 2; } if (threshold == 0) { threshold = fontsize_h; int this_width = FXSYS_abs(GetCharWidth(item.m_CharCode, pFont)); threshold = this_width > last_width ? (FX_FLOAT)this_width : (FX_FLOAT)last_width; threshold = _NormalizeThreshold(threshold); threshold = fontsize_h * threshold / 1000; } if (threshold && (spacing && spacing >= threshold)) { charinfo.m_Unicode = TEXT_BLANK_CHAR; charinfo.m_Flag = FPDFTEXT_CHAR_GENERATED; charinfo.m_pTextObj = pTextObj; charinfo.m_Index = m_TextBuf.GetLength(); m_TempTextBuf.AppendChar(TEXT_BLANK_CHAR); charinfo.m_CharCode = -1; charinfo.m_Matrix.Copy(formMatrix); matrix.Transform(item.m_OriginX, item.m_OriginY, charinfo.m_OriginX, charinfo.m_OriginY); charinfo.m_CharBox = CFX_FloatRect(charinfo.m_OriginX, charinfo.m_OriginY, charinfo.m_OriginX, charinfo.m_OriginY); m_TempCharList.Add(charinfo); } if (item.m_CharCode == (FX_DWORD)-1) { continue; } } spacing = 0; CFX_WideString wstrItem = pFont->UnicodeFromCharCode(item.m_CharCode); FX_BOOL bNoUnicode = FALSE; FX_WCHAR wChar = wstrItem.GetAt(0); if ((wstrItem.IsEmpty() || wChar == 0) && item.m_CharCode) { if (wstrItem.IsEmpty()) { wstrItem += (FX_WCHAR)item.m_CharCode; } else { wstrItem.SetAt(0, (FX_WCHAR)item.m_CharCode); } bNoUnicode = TRUE; } charinfo.m_Index = -1; charinfo.m_CharCode = item.m_CharCode; if (bNoUnicode) { charinfo.m_Flag = FPDFTEXT_CHAR_UNUNICODE; } else { charinfo.m_Flag = FPDFTEXT_CHAR_NORMAL; } charinfo.m_pTextObj = pTextObj; charinfo.m_OriginX = 0, charinfo.m_OriginY = 0; matrix.Transform(item.m_OriginX, item.m_OriginY, charinfo.m_OriginX, charinfo.m_OriginY); FX_RECT rect(0, 0, 0, 0); rect.Intersect(0, 0, 0, 0); charinfo.m_pTextObj->GetFont()->GetCharBBox(charinfo.m_CharCode, rect); charinfo.m_CharBox.top = rect.top * pTextObj->GetFontSize() / 1000 + item.m_OriginY; charinfo.m_CharBox.left = rect.left * pTextObj->GetFontSize() / 1000 + item.m_OriginX; charinfo.m_CharBox.right = rect.right * pTextObj->GetFontSize() / 1000 + item.m_OriginX; charinfo.m_CharBox.bottom = rect.bottom * pTextObj->GetFontSize() / 1000 + item.m_OriginY; if (fabsf(charinfo.m_CharBox.top - charinfo.m_CharBox.bottom) < 0.01f) { charinfo.m_CharBox.top = charinfo.m_CharBox.bottom + pTextObj->GetFontSize(); } if (fabsf(charinfo.m_CharBox.right - charinfo.m_CharBox.left) < 0.01f) { charinfo.m_CharBox.right = charinfo.m_CharBox.left + pTextObj->GetCharWidth(charinfo.m_CharCode); } matrix.TransformRect(charinfo.m_CharBox); charinfo.m_Matrix.Copy(matrix); if (wstrItem.IsEmpty()) { charinfo.m_Unicode = 0; m_TempCharList.Add(charinfo); m_TempTextBuf.AppendChar(0xfffe); continue; } else { int nTotal = wstrItem.GetLength(); FX_BOOL bDel = FALSE; const int count = std::min(m_TempCharList.GetSize(), 7); FX_FLOAT threshold = charinfo.m_Matrix.TransformXDistance( (FX_FLOAT)TEXT_CHARRATIO_GAPDELTA * pTextObj->GetFontSize()); for (int n = m_TempCharList.GetSize(); n > m_TempCharList.GetSize() - count; n--) { PAGECHAR_INFO* charinfo1 = (PAGECHAR_INFO*)m_TempCharList.GetAt(n - 1); if (charinfo1->m_CharCode == charinfo.m_CharCode && charinfo1->m_pTextObj->GetFont() == charinfo.m_pTextObj->GetFont() && FXSYS_fabs(charinfo1->m_OriginX - charinfo.m_OriginX) < threshold && FXSYS_fabs(charinfo1->m_OriginY - charinfo.m_OriginY) < threshold) { bDel = TRUE; break; } } if (!bDel) { for (int nIndex = 0; nIndex < nTotal; nIndex++) { charinfo.m_Unicode = wstrItem.GetAt(nIndex); if (charinfo.m_Unicode) { charinfo.m_Index = m_TextBuf.GetLength(); m_TempTextBuf.AppendChar(charinfo.m_Unicode); } else { m_TempTextBuf.AppendChar(0xfffe); } m_TempCharList.Add(charinfo); } } else if (i == 0) { CFX_WideString str = m_TempTextBuf.GetWideString(); if (!str.IsEmpty() && str.GetAt(str.GetLength() - 1) == TEXT_BLANK_CHAR) { m_TempTextBuf.Delete(m_TempTextBuf.GetLength() - 1, 1); m_TempCharList.Delete(m_TempCharList.GetSize() - 1); } } } } if (bIsBidiAndMirrorInverse) { SwapTempTextBuf(iCharListStartAppend, iBufStartAppend); } } void CPDF_TextPage::SwapTempTextBuf(int32_t iCharListStartAppend, int32_t iBufStartAppend) { int32_t i, j; i = iCharListStartAppend; j = m_TempCharList.GetSize() - 1; for (; i < j; i++, j--) { std::swap(m_TempCharList[i], m_TempCharList[j]); std::swap(m_TempCharList[i].m_Index, m_TempCharList[j].m_Index); } FX_WCHAR* pTempBuffer = m_TempTextBuf.GetBuffer(); i = iBufStartAppend; j = m_TempTextBuf.GetLength() - 1; for (; i < j; i++, j--) { std::swap(pTempBuffer[i], pTempBuffer[j]); } } FX_BOOL CPDF_TextPage::IsRightToLeft(const CPDF_TextObject* pTextObj, const CPDF_Font* pFont, int nItems) const { nonstd::unique_ptr<CFX_BidiChar> pBidiChar(new CFX_BidiChar); int32_t nR2L = 0; int32_t nL2R = 0; int32_t start = 0, count = 0; CPDF_TextObjectItem item; for (int32_t i = 0; i < nItems; i++) { pTextObj->GetItemInfo(i, &item); if (item.m_CharCode == (FX_DWORD)-1) { continue; } CFX_WideString wstrItem = pFont->UnicodeFromCharCode(item.m_CharCode); FX_WCHAR wChar = wstrItem.GetAt(0); if ((wstrItem.IsEmpty() || wChar == 0) && item.m_CharCode) { wChar = (FX_WCHAR)item.m_CharCode; } if (!wChar) { continue; } if (pBidiChar->AppendChar(wChar)) { CFX_BidiChar::Direction ret = pBidiChar->GetBidiInfo(&start, &count); if (ret == CFX_BidiChar::RIGHT) { nR2L++; } else if (ret == CFX_BidiChar::LEFT) { nL2R++; } } } if (pBidiChar->EndChar()) { CFX_BidiChar::Direction ret = pBidiChar->GetBidiInfo(&start, &count); if (ret == CFX_BidiChar::RIGHT) { nR2L++; } else if (ret == CFX_BidiChar::LEFT) { nL2R++; } } return (nR2L > 0 && nR2L >= nL2R); } int32_t CPDF_TextPage::GetTextObjectWritingMode( const CPDF_TextObject* pTextObj) { int32_t nChars = pTextObj->CountChars(); if (nChars == 1) { return m_TextlineDir; } CPDF_TextObjectItem first, last; pTextObj->GetCharInfo(0, &first); pTextObj->GetCharInfo(nChars - 1, &last); CFX_Matrix textMatrix; pTextObj->GetTextMatrix(&textMatrix); textMatrix.TransformPoint(first.m_OriginX, first.m_OriginY); textMatrix.TransformPoint(last.m_OriginX, last.m_OriginY); FX_FLOAT dX = FXSYS_fabs(last.m_OriginX - first.m_OriginX); FX_FLOAT dY = FXSYS_fabs(last.m_OriginY - first.m_OriginY); if (dX <= 0.0001f && dY <= 0.0001f) { return -1; } CFX_VectorF v; v.Set(dX, dY); v.Normalize(); if (v.y <= 0.0872f) { return v.x <= 0.0872f ? m_TextlineDir : 0; } if (v.x <= 0.0872f) { return 1; } return m_TextlineDir; } FX_BOOL CPDF_TextPage::IsHyphen(FX_WCHAR curChar) { CFX_WideString strCurText = m_TempTextBuf.GetWideString(); if (strCurText.GetLength() == 0) { strCurText = m_TextBuf.GetWideString(); } FX_STRSIZE nCount = strCurText.GetLength(); int nIndex = nCount - 1; FX_WCHAR wcTmp = strCurText.GetAt(nIndex); while (wcTmp == 0x20 && nIndex <= nCount - 1 && nIndex >= 0) { wcTmp = strCurText.GetAt(--nIndex); } if (0x2D == wcTmp || 0xAD == wcTmp) { if (--nIndex > 0) { FX_WCHAR preChar = strCurText.GetAt((nIndex)); if (((preChar >= L'A' && preChar <= L'Z') || (preChar >= L'a' && preChar <= L'z')) && ((curChar >= L'A' && curChar <= L'Z') || (curChar >= L'a' && curChar <= L'z'))) { return TRUE; } } int size = m_TempCharList.GetSize(); PAGECHAR_INFO preChar; if (size) { preChar = (PAGECHAR_INFO)m_TempCharList[size - 1]; } else { size = m_charList.GetSize(); if (size == 0) { return FALSE; } preChar = (PAGECHAR_INFO)m_charList[size - 1]; } if (FPDFTEXT_CHAR_PIECE == preChar.m_Flag) if (0xAD == preChar.m_Unicode || 0x2D == preChar.m_Unicode) { return TRUE; } } return FALSE; } int CPDF_TextPage::ProcessInsertObject(const CPDF_TextObject* pObj, const CFX_AffineMatrix& formMatrix) { FindPreviousTextObject(); FX_BOOL bNewline = FALSE; int WritingMode = GetTextObjectWritingMode(pObj); if (WritingMode == -1) { WritingMode = GetTextObjectWritingMode(m_pPreTextObj); } CFX_FloatRect this_rect(pObj->m_Left, pObj->m_Bottom, pObj->m_Right, pObj->m_Top); CFX_FloatRect prev_rect(m_pPreTextObj->m_Left, m_pPreTextObj->m_Bottom, m_pPreTextObj->m_Right, m_pPreTextObj->m_Top); CPDF_TextObjectItem PrevItem, item; int nItem = m_pPreTextObj->CountItems(); m_pPreTextObj->GetItemInfo(nItem - 1, &PrevItem); pObj->GetItemInfo(0, &item); CFX_WideString wstrItem = pObj->GetFont()->UnicodeFromCharCode(item.m_CharCode); if (wstrItem.IsEmpty()) { wstrItem += (FX_WCHAR)item.m_CharCode; } FX_WCHAR curChar = wstrItem.GetAt(0); if (WritingMode == 0) { if (this_rect.Height() > 4.5 && prev_rect.Height() > 4.5) { FX_FLOAT top = this_rect.top < prev_rect.top ? this_rect.top : prev_rect.top; FX_FLOAT bottom = this_rect.bottom > prev_rect.bottom ? this_rect.bottom : prev_rect.bottom; if (bottom >= top) { if (IsHyphen(curChar)) { return 3; } return 2; } } } else if (WritingMode == 1) { if (this_rect.Width() > pObj->GetFontSize() * 0.1f && prev_rect.Width() > m_pPreTextObj->GetFontSize() * 0.1f) { FX_FLOAT left = this_rect.left > m_CurlineRect.left ? this_rect.left : m_CurlineRect.left; FX_FLOAT right = this_rect.right < m_CurlineRect.right ? this_rect.right : m_CurlineRect.right; if (right <= left) { if (IsHyphen(curChar)) { return 3; } return 2; } } } FX_FLOAT last_pos = PrevItem.m_OriginX; int nLastWidth = GetCharWidth(PrevItem.m_CharCode, m_pPreTextObj->GetFont()); FX_FLOAT last_width = nLastWidth * m_pPreTextObj->GetFontSize() / 1000; last_width = FXSYS_fabs(last_width); int nThisWidth = GetCharWidth(item.m_CharCode, pObj->GetFont()); FX_FLOAT this_width = nThisWidth * pObj->GetFontSize() / 1000; this_width = FXSYS_fabs(this_width); FX_FLOAT threshold = last_width > this_width ? last_width / 4 : this_width / 4; CFX_AffineMatrix prev_matrix, prev_reverse; m_pPreTextObj->GetTextMatrix(&prev_matrix); prev_matrix.Concat(m_perMatrix); prev_reverse.SetReverse(prev_matrix); FX_FLOAT x = pObj->GetPosX(); FX_FLOAT y = pObj->GetPosY(); formMatrix.Transform(x, y); prev_reverse.Transform(x, y); if (last_width < this_width) { threshold = prev_reverse.TransformDistance(threshold); } CFX_FloatRect rect1(m_pPreTextObj->m_Left, pObj->m_Bottom, m_pPreTextObj->m_Right, pObj->m_Top); CFX_FloatRect rect2(m_pPreTextObj->m_Left, m_pPreTextObj->m_Bottom, m_pPreTextObj->m_Right, m_pPreTextObj->m_Top); CFX_FloatRect rect3 = rect1; rect1.Intersect(rect2); if (WritingMode == 0) { if ((rect1.IsEmpty() && rect2.Height() > 5 && rect3.Height() > 5) || ((y > threshold * 2 || y < threshold * -3) && (FXSYS_fabs(y) < 1 ? FXSYS_fabs(x) < FXSYS_fabs(y) : TRUE))) { bNewline = TRUE; if (nItem > 1) { CPDF_TextObjectItem tempItem; m_pPreTextObj->GetItemInfo(0, &tempItem); CFX_AffineMatrix m; m_pPreTextObj->GetTextMatrix(&m); if (PrevItem.m_OriginX > tempItem.m_OriginX && m_DisplayMatrix.a > 0.9 && m_DisplayMatrix.b < 0.1 && m_DisplayMatrix.c < 0.1 && m_DisplayMatrix.d < -0.9 && m.b < 0.1 && m.c < 0.1) { CFX_FloatRect re(0, m_pPreTextObj->m_Bottom, 1000, m_pPreTextObj->m_Top); if (re.Contains(pObj->GetPosX(), pObj->GetPosY())) { bNewline = FALSE; } else { CFX_FloatRect re(0, pObj->m_Bottom, 1000, pObj->m_Top); if (re.Contains(m_pPreTextObj->GetPosX(), m_pPreTextObj->GetPosY())) { bNewline = FALSE; } } } } } } if (bNewline) { if (IsHyphen(curChar)) { return 3; } return 2; } int32_t nChars = pObj->CountChars(); if (nChars == 1 && (0x2D == curChar || 0xAD == curChar)) if (IsHyphen(curChar)) { return 3; } CFX_WideString PrevStr = m_pPreTextObj->GetFont()->UnicodeFromCharCode(PrevItem.m_CharCode); FX_WCHAR preChar = PrevStr.GetAt(PrevStr.GetLength() - 1); CFX_AffineMatrix matrix; pObj->GetTextMatrix(&matrix); matrix.Concat(formMatrix); threshold = (FX_FLOAT)(nLastWidth > nThisWidth ? nLastWidth : nThisWidth); threshold = threshold > 400 ? (threshold < 700 ? threshold / 4 : (threshold > 800 ? threshold / 6 : threshold / 5)) : (threshold / 2); if (nLastWidth >= nThisWidth) { threshold *= FXSYS_fabs(m_pPreTextObj->GetFontSize()); } else { threshold *= FXSYS_fabs(pObj->GetFontSize()); threshold = matrix.TransformDistance(threshold); threshold = prev_reverse.TransformDistance(threshold); } threshold /= 1000; if ((threshold < 1.4881 && threshold > 1.4879) || (threshold < 1.39001 && threshold > 1.38999)) { threshold *= 1.5; } if (FXSYS_fabs(last_pos + last_width - x) > threshold && curChar != L' ' && preChar != L' ') if (curChar != L' ' && preChar != L' ') { if ((x - last_pos - last_width) > threshold || (last_pos - x - last_width) > threshold) { return 1; } if (x < 0 && (last_pos - x - last_width) > threshold) { return 1; } if ((x - last_pos - last_width) > this_width || (x - last_pos - this_width) > last_width) { return 1; } } return 0; } FX_BOOL CPDF_TextPage::IsSameTextObject(CPDF_TextObject* pTextObj1, CPDF_TextObject* pTextObj2) { if (!pTextObj1 || !pTextObj2) { return FALSE; } CFX_FloatRect rcPreObj(pTextObj2->m_Left, pTextObj2->m_Bottom, pTextObj2->m_Right, pTextObj2->m_Top); CFX_FloatRect rcCurObj(pTextObj1->m_Left, pTextObj1->m_Bottom, pTextObj1->m_Right, pTextObj1->m_Top); if (rcPreObj.IsEmpty() && rcCurObj.IsEmpty() && !m_ParseOptions.m_bGetCharCodeOnly) { FX_FLOAT dbXdif = FXSYS_fabs(rcPreObj.left - rcCurObj.left); int nCount = m_charList.GetSize(); if (nCount >= 2) { PAGECHAR_INFO perCharTemp = (PAGECHAR_INFO)m_charList[nCount - 2]; FX_FLOAT dbSpace = perCharTemp.m_CharBox.Width(); if (dbXdif > dbSpace) { return FALSE; } } } if (!rcPreObj.IsEmpty() || !rcCurObj.IsEmpty()) { rcPreObj.Intersect(rcCurObj); if (rcPreObj.IsEmpty()) { return FALSE; } if (FXSYS_fabs(rcPreObj.Width() - rcCurObj.Width()) > rcCurObj.Width() / 2) { return FALSE; } if (pTextObj2->GetFontSize() != pTextObj1->GetFontSize()) { return FALSE; } } int nPreCount = pTextObj2->CountItems(); int nCurCount = pTextObj1->CountItems(); if (nPreCount != nCurCount) { return FALSE; } CPDF_TextObjectItem itemPer, itemCur; for (int i = 0; i < nPreCount; i++) { pTextObj2->GetItemInfo(i, &itemPer); pTextObj1->GetItemInfo(i, &itemCur); if (itemCur.m_CharCode != itemPer.m_CharCode) { return FALSE; } } if (FXSYS_fabs(pTextObj1->GetPosX() - pTextObj2->GetPosX()) > GetCharWidth(itemPer.m_CharCode, pTextObj2->GetFont()) * pTextObj2->GetFontSize() / 1000 * 0.9 || FXSYS_fabs(pTextObj1->GetPosY() - pTextObj2->GetPosY()) > FX_MAX(FX_MAX(rcPreObj.Height(), rcPreObj.Width()), pTextObj2->GetFontSize()) / 8) { return FALSE; } return TRUE; } FX_BOOL CPDF_TextPage::IsSameAsPreTextObject(CPDF_TextObject* pTextObj, FX_POSITION ObjPos) { if (!pTextObj) { return FALSE; } int i = 0; if (!ObjPos) { ObjPos = m_pPage->GetLastObjectPosition(); } CPDF_PageObject* pObj = m_pPage->GetPrevObject(ObjPos); while (i < 5 && ObjPos) { pObj = m_pPage->GetPrevObject(ObjPos); if (pObj == pTextObj) { continue; } if (pObj->m_Type != PDFPAGE_TEXT) { continue; } if (IsSameTextObject((CPDF_TextObject*)pObj, pTextObj)) { return TRUE; } i++; } return FALSE; } FX_BOOL CPDF_TextPage::GenerateCharInfo(FX_WCHAR unicode, PAGECHAR_INFO& info) { int size = m_TempCharList.GetSize(); PAGECHAR_INFO preChar; if (size) { preChar = (PAGECHAR_INFO)m_TempCharList[size - 1]; } else { size = m_charList.GetSize(); if (size == 0) { return FALSE; } preChar = (PAGECHAR_INFO)m_charList[size - 1]; } info.m_Index = m_TextBuf.GetLength(); info.m_Unicode = unicode; info.m_pTextObj = NULL; info.m_CharCode = -1; info.m_Flag = FPDFTEXT_CHAR_GENERATED; int preWidth = 0; if (preChar.m_pTextObj && preChar.m_CharCode != (FX_DWORD)-1) { preWidth = GetCharWidth(preChar.m_CharCode, preChar.m_pTextObj->GetFont()); } FX_FLOAT fs = 0; if (preChar.m_pTextObj) { fs = preChar.m_pTextObj->GetFontSize(); } else { fs = preChar.m_CharBox.Height(); } if (!fs) { fs = 1; } info.m_OriginX = preChar.m_OriginX + preWidth * (fs) / 1000; info.m_OriginY = preChar.m_OriginY; info.m_CharBox = CFX_FloatRect(info.m_OriginX, info.m_OriginY, info.m_OriginX, info.m_OriginY); return TRUE; } FX_BOOL CPDF_TextPage::IsRectIntersect(const CFX_FloatRect& rect1, const CFX_FloatRect& rect2) { CFX_FloatRect rect = rect1; rect.Intersect(rect2); return !rect.IsEmpty(); } FX_BOOL CPDF_TextPage::IsLetter(FX_WCHAR unicode) { if (unicode < L'A') { return FALSE; } if (unicode > L'Z' && unicode < L'a') { return FALSE; } if (unicode > L'z') { return FALSE; } return TRUE; } CPDF_TextPageFind::CPDF_TextPageFind(const IPDF_TextPage* pTextPage) : m_pTextPage(pTextPage), m_flags(0), m_findNextStart(-1), m_findPreStart(-1), m_bMatchCase(FALSE), m_bMatchWholeWord(FALSE), m_resStart(0), m_resEnd(-1), m_IsFind(FALSE) { m_strText = m_pTextPage->GetPageText(); int nCount = pTextPage->CountChars(); if (nCount) { m_CharIndex.Add(0); } for (int i = 0; i < nCount; i++) { FPDF_CHAR_INFO info; pTextPage->GetCharInfo(i, info); int indexSize = m_CharIndex.GetSize(); if (info.m_Flag == CHAR_NORMAL || info.m_Flag == CHAR_GENERATED) { if (indexSize % 2) { m_CharIndex.Add(1); } else { if (indexSize <= 0) { continue; } m_CharIndex.SetAt(indexSize - 1, m_CharIndex.GetAt(indexSize - 1) + 1); } } else { if (indexSize % 2) { if (indexSize <= 0) { continue; } m_CharIndex.SetAt(indexSize - 1, i + 1); } else { m_CharIndex.Add(i + 1); } } } int indexSize = m_CharIndex.GetSize(); if (indexSize % 2) { m_CharIndex.RemoveAt(indexSize - 1); } } int CPDF_TextPageFind::GetCharIndex(int index) const { return m_pTextPage->CharIndexFromTextIndex(index); int indexSize = m_CharIndex.GetSize(); int count = 0; for (int i = 0; i < indexSize; i += 2) { count += m_CharIndex.GetAt(i + 1); if (count > index) { return index - count + m_CharIndex.GetAt(i + 1) + m_CharIndex.GetAt(i); } } return -1; } FX_BOOL CPDF_TextPageFind::FindFirst(const CFX_WideString& findwhat, int flags, int startPos) { if (!m_pTextPage) { return FALSE; } if (m_strText.IsEmpty() || m_bMatchCase != (flags & FPDFTEXT_MATCHCASE)) { m_strText = m_pTextPage->GetPageText(); } CFX_WideString findwhatStr = findwhat; m_findWhat = findwhatStr; m_flags = flags; m_bMatchCase = flags & FPDFTEXT_MATCHCASE; if (m_strText.IsEmpty()) { m_IsFind = FALSE; return TRUE; } FX_STRSIZE len = findwhatStr.GetLength(); if (!m_bMatchCase) { findwhatStr.MakeLower(); m_strText.MakeLower(); } m_bMatchWholeWord = flags & FPDFTEXT_MATCHWHOLEWORD; m_findNextStart = startPos; if (startPos == -1) { m_findPreStart = m_strText.GetLength() - 1; } else { m_findPreStart = startPos; } m_csFindWhatArray.RemoveAll(); int i = 0; while (i < len) { if (findwhatStr.GetAt(i) != ' ') { break; } i++; } if (i < len) { ExtractFindWhat(findwhatStr); } else { m_csFindWhatArray.Add(findwhatStr); } if (m_csFindWhatArray.GetSize() <= 0) { return FALSE; } m_IsFind = TRUE; m_resStart = 0; m_resEnd = -1; return TRUE; } FX_BOOL CPDF_TextPageFind::FindNext() { if (!m_pTextPage) { return FALSE; } m_resArray.RemoveAll(); if (m_findNextStart == -1) { return FALSE; } if (m_strText.IsEmpty()) { m_IsFind = FALSE; return m_IsFind; } int strLen = m_strText.GetLength(); if (m_findNextStart > strLen - 1) { m_IsFind = FALSE; return m_IsFind; } int nCount = m_csFindWhatArray.GetSize(); int nResultPos = 0; int nStartPos = 0; nStartPos = m_findNextStart; FX_BOOL bSpaceStart = FALSE; for (int iWord = 0; iWord < nCount; iWord++) { CFX_WideString csWord = m_csFindWhatArray[iWord]; if (csWord.IsEmpty()) { if (iWord == nCount - 1) { FX_WCHAR strInsert = m_strText.GetAt(nStartPos); if (strInsert == TEXT_LINEFEED_CHAR || strInsert == TEXT_BLANK_CHAR || strInsert == TEXT_RETURN_CHAR || strInsert == 160) { nResultPos = nStartPos + 1; break; } iWord = -1; } else if (iWord == 0) { bSpaceStart = TRUE; } continue; } int endIndex; nResultPos = m_strText.Find(csWord.c_str(), nStartPos); if (nResultPos == -1) { m_IsFind = FALSE; return m_IsFind; } endIndex = nResultPos + csWord.GetLength() - 1; if (iWord == 0) { m_resStart = nResultPos; } FX_BOOL bMatch = TRUE; if (iWord != 0 && !bSpaceStart) { int PreResEndPos = nStartPos; int curChar = csWord.GetAt(0); CFX_WideString lastWord = m_csFindWhatArray[iWord - 1]; int lastChar = lastWord.GetAt(lastWord.GetLength() - 1); if (nStartPos == nResultPos && !(_IsIgnoreSpaceCharacter(lastChar) || _IsIgnoreSpaceCharacter(curChar))) { bMatch = FALSE; } for (int d = PreResEndPos; d < nResultPos; d++) { FX_WCHAR strInsert = m_strText.GetAt(d); if (strInsert != TEXT_LINEFEED_CHAR && strInsert != TEXT_BLANK_CHAR && strInsert != TEXT_RETURN_CHAR && strInsert != 160) { bMatch = FALSE; break; } } } else if (bSpaceStart) { if (nResultPos > 0) { FX_WCHAR strInsert = m_strText.GetAt(nResultPos - 1); if (strInsert != TEXT_LINEFEED_CHAR && strInsert != TEXT_BLANK_CHAR && strInsert != TEXT_RETURN_CHAR && strInsert != 160) { bMatch = FALSE; m_resStart = nResultPos; } else { m_resStart = nResultPos - 1; } } } if (m_bMatchWholeWord && bMatch) { bMatch = IsMatchWholeWord(m_strText, nResultPos, endIndex); } nStartPos = endIndex + 1; if (!bMatch) { iWord = -1; if (bSpaceStart) { nStartPos = m_resStart + m_csFindWhatArray[1].GetLength(); } else { nStartPos = m_resStart + m_csFindWhatArray[0].GetLength(); } } } m_resEnd = nResultPos + m_csFindWhatArray[m_csFindWhatArray.GetSize() - 1].GetLength() - 1; m_IsFind = TRUE; int resStart = GetCharIndex(m_resStart); int resEnd = GetCharIndex(m_resEnd); m_pTextPage->GetRectArray(resStart, resEnd - resStart + 1, m_resArray); if (m_flags & FPDFTEXT_CONSECUTIVE) { m_findNextStart = m_resStart + 1; m_findPreStart = m_resEnd - 1; } else { m_findNextStart = m_resEnd + 1; m_findPreStart = m_resStart - 1; } return m_IsFind; } FX_BOOL CPDF_TextPageFind::FindPrev() { if (!m_pTextPage) { return FALSE; } m_resArray.RemoveAll(); if (m_strText.IsEmpty() || m_findPreStart < 0) { m_IsFind = FALSE; return m_IsFind; } CPDF_TextPageFind findEngine(m_pTextPage); FX_BOOL ret = findEngine.FindFirst(m_findWhat, m_flags); if (!ret) { m_IsFind = FALSE; return m_IsFind; } int order = -1, MatchedCount = 0; while (ret) { ret = findEngine.FindNext(); if (ret) { int order1 = findEngine.GetCurOrder(); int MatchedCount1 = findEngine.GetMatchedCount(); if (((order1 + MatchedCount1) - 1) > m_findPreStart) { break; } order = order1; MatchedCount = MatchedCount1; } } if (order == -1) { m_IsFind = FALSE; return m_IsFind; } m_resStart = m_pTextPage->TextIndexFromCharIndex(order); m_resEnd = m_pTextPage->TextIndexFromCharIndex(order + MatchedCount - 1); m_IsFind = TRUE; m_pTextPage->GetRectArray(order, MatchedCount, m_resArray); if (m_flags & FPDFTEXT_CONSECUTIVE) { m_findNextStart = m_resStart + 1; m_findPreStart = m_resEnd - 1; } else { m_findNextStart = m_resEnd + 1; m_findPreStart = m_resStart - 1; } return m_IsFind; } void CPDF_TextPageFind::ExtractFindWhat(const CFX_WideString& findwhat) { if (findwhat.IsEmpty()) { return; } int index = 0; while (1) { CFX_WideString csWord = TEXT_EMPTY; int ret = ExtractSubString(csWord, findwhat.c_str(), index, TEXT_BLANK_CHAR); if (csWord.IsEmpty()) { if (ret) { m_csFindWhatArray.Add(CFX_WideString(L"")); index++; continue; } else { break; } } int pos = 0; while (pos < csWord.GetLength()) { CFX_WideString curStr = csWord.Mid(pos, 1); FX_WCHAR curChar = csWord.GetAt(pos); if (_IsIgnoreSpaceCharacter(curChar)) { if (pos > 0 && curChar == 0x2019) { pos++; continue; } if (pos > 0) { CFX_WideString preStr = csWord.Mid(0, pos); m_csFindWhatArray.Add(preStr); } m_csFindWhatArray.Add(curStr); if (pos == csWord.GetLength() - 1) { csWord.Empty(); break; } csWord = csWord.Right(csWord.GetLength() - pos - 1); pos = 0; continue; } pos++; } if (!csWord.IsEmpty()) { m_csFindWhatArray.Add(csWord); } index++; } } FX_BOOL CPDF_TextPageFind::IsMatchWholeWord(const CFX_WideString& csPageText, int startPos, int endPos) { int char_left = 0; int char_right = 0; int char_count = endPos - startPos + 1; if (char_count < 1) { return FALSE; } if (char_count == 1 && csPageText.GetAt(startPos) > 255) { return TRUE; } if (startPos - 1 >= 0) { char_left = csPageText.GetAt(startPos - 1); } if (startPos + char_count < csPageText.GetLength()) { char_right = csPageText.GetAt(startPos + char_count); } if ((char_left > 'A' && char_left < 'a') || (char_left > 'a' && char_left < 'z') || (char_left > 0xfb00 && char_left < 0xfb06) || (char_left >= '0' && char_left <= '9') || (char_right > 'A' && char_right < 'a') || (char_right > 'a' && char_right < 'z') || (char_right > 0xfb00 && char_right < 0xfb06) || (char_right >= '0' && char_right <= '9')) { return FALSE; } if (!(('A' > char_left || char_left > 'Z') && ('a' > char_left || char_left > 'z') && ('A' > char_right || char_right > 'Z') && ('a' > char_right || char_right > 'z'))) { return FALSE; } if (char_count > 0) { if (csPageText.GetAt(startPos) >= L'0' && csPageText.GetAt(startPos) <= L'9' && char_left >= L'0' && char_left <= L'9') { return FALSE; } if (csPageText.GetAt(endPos) >= L'0' && csPageText.GetAt(endPos) <= L'9' && char_right >= L'0' && char_right <= L'9') { return FALSE; } } return TRUE; } FX_BOOL CPDF_TextPageFind::ExtractSubString(CFX_WideString& rString, const FX_WCHAR* lpszFullString, int iSubString, FX_WCHAR chSep) { if (lpszFullString == NULL) { return FALSE; } while (iSubString--) { lpszFullString = FXSYS_wcschr(lpszFullString, chSep); if (lpszFullString == NULL) { rString.Empty(); return FALSE; } lpszFullString++; while (*lpszFullString == chSep) { lpszFullString++; } } const FX_WCHAR* lpchEnd = FXSYS_wcschr(lpszFullString, chSep); int nLen = (lpchEnd == NULL) ? (int)FXSYS_wcslen(lpszFullString) : (int)(lpchEnd - lpszFullString); ASSERT(nLen >= 0); FXSYS_memcpy(rString.GetBuffer(nLen), lpszFullString, nLen * sizeof(FX_WCHAR)); rString.ReleaseBuffer(); return TRUE; } CFX_WideString CPDF_TextPageFind::MakeReverse(const CFX_WideString& str) { CFX_WideString str2; str2.Empty(); int nlen = str.GetLength(); for (int i = nlen - 1; i >= 0; i--) { str2 += str.GetAt(i); } return str2; } void CPDF_TextPageFind::GetRectArray(CFX_RectArray& rects) const { rects.Copy(m_resArray); } int CPDF_TextPageFind::GetCurOrder() const { return GetCharIndex(m_resStart); } int CPDF_TextPageFind::GetMatchedCount() const { int resStart = GetCharIndex(m_resStart); int resEnd = GetCharIndex(m_resEnd); return resEnd - resStart + 1; } CPDF_LinkExtract::CPDF_LinkExtract() : m_pTextPage(nullptr), m_bIsParsed(false) { } CPDF_LinkExtract::~CPDF_LinkExtract() { DeleteLinkList(); } FX_BOOL CPDF_LinkExtract::ExtractLinks(const IPDF_TextPage* pTextPage) { if (!pTextPage || !pTextPage->IsParsed()) return FALSE; m_pTextPage = (const CPDF_TextPage*)pTextPage; m_strPageText = m_pTextPage->GetPageText(0, -1); DeleteLinkList(); if (m_strPageText.IsEmpty()) { return FALSE; } ParseLink(); m_bIsParsed = true; return TRUE; } void CPDF_LinkExtract::DeleteLinkList() { while (m_LinkList.GetSize()) { CPDF_LinkExt* linkinfo = NULL; linkinfo = m_LinkList.GetAt(0); m_LinkList.RemoveAt(0); delete linkinfo; } m_LinkList.RemoveAll(); } int CPDF_LinkExtract::CountLinks() const { if (!m_bIsParsed) { return -1; } return m_LinkList.GetSize(); } void CPDF_LinkExtract::ParseLink() { int start = 0, pos = 0; int TotalChar = m_pTextPage->CountChars(); while (pos < TotalChar) { FPDF_CHAR_INFO pageChar; m_pTextPage->GetCharInfo(pos, pageChar); if (pageChar.m_Flag == CHAR_GENERATED || pageChar.m_Unicode == 0x20 || pos == TotalChar - 1) { int nCount = pos - start; if (pos == TotalChar - 1) { nCount++; } CFX_WideString strBeCheck; strBeCheck = m_pTextPage->GetPageText(start, nCount); if (strBeCheck.GetLength() > 5) { while (strBeCheck.GetLength() > 0) { FX_WCHAR ch = strBeCheck.GetAt(strBeCheck.GetLength() - 1); if (ch == L')' || ch == L',' || ch == L'>' || ch == L'.') { strBeCheck = strBeCheck.Mid(0, strBeCheck.GetLength() - 1); nCount--; } else { break; } } if (nCount > 5 && (CheckWebLink(strBeCheck) || CheckMailLink(strBeCheck))) { if (!AppendToLinkList(start, nCount, strBeCheck)) { break; } } } start = ++pos; } else { pos++; } } } FX_BOOL CPDF_LinkExtract::CheckWebLink(CFX_WideString& strBeCheck) { CFX_WideString str = strBeCheck; str.MakeLower(); if (str.Find(L"http://www.") != -1) { strBeCheck = strBeCheck.Right(str.GetLength() - str.Find(L"http://www.")); return TRUE; } if (str.Find(L"http://") != -1) { strBeCheck = strBeCheck.Right(str.GetLength() - str.Find(L"http://")); return TRUE; } if (str.Find(L"https://www.") != -1) { strBeCheck = strBeCheck.Right(str.GetLength() - str.Find(L"https://www.")); return TRUE; } if (str.Find(L"https://") != -1) { strBeCheck = strBeCheck.Right(str.GetLength() - str.Find(L"https://")); return TRUE; } if (str.Find(L"www.") != -1) { strBeCheck = strBeCheck.Right(str.GetLength() - str.Find(L"www.")); strBeCheck = L"http://" + strBeCheck; return TRUE; } return FALSE; } FX_BOOL CPDF_LinkExtract::CheckMailLink(CFX_WideString& str) { str.MakeLower(); int aPos = str.Find(L'@'); if (aPos < 1) { return FALSE; } if (str.GetAt(aPos - 1) == L'.' || str.GetAt(aPos - 1) == L'_') { return FALSE; } int i; for (i = aPos - 1; i >= 0; i--) { FX_WCHAR ch = str.GetAt(i); if (ch == L'_' || ch == L'.' || (ch >= L'a' && ch <= L'z') || (ch >= L'0' && ch <= L'9')) { continue; } else { if (i == aPos - 1) { return FALSE; } str = str.Right(str.GetLength() - i - 1); break; } } aPos = str.Find(L'@'); if (aPos < 1) { return FALSE; } CFX_WideString strtemp = L""; for (i = 0; i < aPos; i++) { FX_WCHAR wch = str.GetAt(i); if (wch >= L'a' && wch <= L'z') { break; } else { strtemp = str.Right(str.GetLength() - i + 1); } } if (strtemp != L"") { str = strtemp; } aPos = str.Find(L'@'); if (aPos < 1) { return FALSE; } str.TrimRight(L'.'); strtemp = str; int ePos = str.Find(L'.'); if (ePos == -1) { return FALSE; } while (ePos != -1) { strtemp = strtemp.Right(strtemp.GetLength() - ePos - 1); ePos = strtemp.Find('.'); } ePos = strtemp.GetLength(); for (i = 0; i < ePos; i++) { FX_WCHAR wch = str.GetAt(i); if ((wch >= L'a' && wch <= L'z') || (wch >= L'0' && wch <= L'9')) { continue; } else { str = str.Left(str.GetLength() - ePos + i + 1); ePos = ePos - i - 1; break; } } int nLen = str.GetLength(); for (i = aPos + 1; i < nLen - ePos; i++) { FX_WCHAR wch = str.GetAt(i); if (wch == L'-' || wch == L'.' || (wch >= L'a' && wch <= L'z') || (wch >= L'0' && wch <= L'9')) { continue; } else { return FALSE; } } if (str.Find(L"mailto:") == -1) { str = L"mailto:" + str; } return TRUE; } FX_BOOL CPDF_LinkExtract::AppendToLinkList(int start, int count, const CFX_WideString& strUrl) { CPDF_LinkExt* linkInfo = new CPDF_LinkExt; linkInfo->m_strUrl = strUrl; linkInfo->m_Start = start; linkInfo->m_Count = count; m_LinkList.Add(linkInfo); return TRUE; } CFX_WideString CPDF_LinkExtract::GetURL(int index) const { if (!m_bIsParsed || index < 0 || index >= m_LinkList.GetSize()) { return L""; } CPDF_LinkExt* link = NULL; link = m_LinkList.GetAt(index); if (!link) { return L""; } return link->m_strUrl; } void CPDF_LinkExtract::GetBoundedSegment(int index, int& start, int& count) const { if (!m_bIsParsed || index < 0 || index >= m_LinkList.GetSize()) { return; } CPDF_LinkExt* link = NULL; link = m_LinkList.GetAt(index); if (!link) { return; } start = link->m_Start; count = link->m_Count; } void CPDF_LinkExtract::GetRects(int index, CFX_RectArray& rects) const { if (!m_bIsParsed || index < 0 || index >= m_LinkList.GetSize()) { return; } CPDF_LinkExt* link = NULL; link = m_LinkList.GetAt(index); if (!link) { return; } m_pTextPage->GetRectArray(link->m_Start, link->m_Count, rects); }
{ "content_hash": "83c0439f4f9211ff117ccf99e3d0c319", "timestamp": "", "source": "github", "line_count": 2719, "max_line_length": 80, "avg_line_length": 31.12798823096727, "alnum_prop": 0.5772180015832319, "repo_name": "azunite/libpdfium", "id": "b81d9677768a69e475525a4424236f54150c339a", "size": "85316", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "core/src/fpdftext/fpdf_text_int.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "4924778" }, { "name": "C++", "bytes": "9778619" }, { "name": "Python", "bytes": "61427" }, { "name": "Shell", "bytes": "545" } ], "symlink_target": "" }
package org.supercsv.cellprocessor.constraint; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.supercsv.TestConstants; import org.supercsv.cellprocessor.Optional; import org.supercsv.cellprocessor.ift.CellProcessor; import org.supercsv.exception.SuperCSVException; import org.supercsv.mock.ComparerCellProcessor; import org.supercsv.util.CSVContext; /** * @author Dominique De Vito */ public class NotNullTest { private static final CSVContext CTXT = TestConstants.ANONYMOUS_CSVCONTEXT; NotNull cp; CellProcessor ccp; @Before public void setUp() throws Exception { cp = new NotNull(); } public void testChaining() throws Exception { String VALUE = "some value"; ccp = new NotNull(new ComparerCellProcessor(VALUE)); Assert.assertEquals("chaining test", true, VALUE.equals(ccp.execute(VALUE, CTXT))); } @Test public void testValidInput() throws Exception { Assert.assertEquals("test length", "help", cp.execute("help", CTXT)); } @Test(expected = SuperCSVException.class) public void testNullInput() throws Exception { cp.execute(null, CTXT); } @Test public void testEmptyInput() throws Exception { cp.execute("", CTXT); } }
{ "content_hash": "f10f9bcb8f2054d591184042c4989a2a", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 85, "avg_line_length": 25.541666666666668, "alnum_prop": 0.7414355628058727, "repo_name": "magro/supercsv", "id": "f7572c716ba65e3cde3478f8b190fd19a8b1a2ef", "size": "1226", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "test/org/supercsv/cellprocessor/constraint/NotNullTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "287076" } ], "symlink_target": "" }
""" mbed SDK Copyright (c) 2011-2015 ARM Limited 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 re import os import json class MbedLsToolsBase: """ Base class for mbed-lstools, defines mbed-ls tools interface for mbed-enabled devices detection for various hosts """ def __init__(self): """ ctor """ #extra flags self.DEBUG_FLAG = False # Used to enable debug code / prints self.ERRORLEVEL_FLAG = 0 # Used to return success code to environment # Which OSs are supported by this module # Note: more than one OS can be supported by mbed-lstools_* module os_supported = [] # Dictionary describing mapping between manufacturers' ids and platform name. manufacture_ids = { "0001": "LPC2368", "0002": "LPC2368", "0003": "LPC2368", "0004": "LPC2368", "0005": "LPC2368", "0006": "LPC2368", "0007": "LPC2368", "0100": "LPC2368", "0183": "UBLOX_C027", "0200": "KL25Z", "0210": "KL05Z", "0220": "KL46Z", "0230": "K20D50M", "0231": "K22F", "0240": "K64F", "0245": "K64F", "0300": "MTS_GAMBIT", "0305": "MTS_MDOT_F405RG", "0310": "MTS_DRAGONFLY_F411RE", "0315": "MTS_MDOT_F411RE", "0400": "MAXWSNENV", "0405": "MAX32600MBED", "0500": "SPANSION_PLACEHOLDER", "0505": "SPANSION_PLACEHOLDER", "0510": "SPANSION_PLACEHOLDER", "0700": "NUCLEO_F103RB", "0705": "NUCLEO_F302R8", "0710": "NUCLEO_L152RE", "0715": "NUCLEO_L053R8", "0720": "NUCLEO_F401RE", "0725": "NUCLEO_F030R8", "0730": "NUCLEO_F072RB", "0735": "NUCLEO_F334R8", "0740": "NUCLEO_F411RE", "0745": "NUCLEO_F303RE", "0750": "NUCLEO_F091RC", "0755": "NUCLEO_F070RB", "0760": "NUCLEO_F073RZ", "0765": "ST_PLACEHOLDER", "0770": "ST_PLACEHOLDER", "0775": "ST_PLACEHOLDER", "0780": "ST_PLACEHOLDER", "0785": "ST_PLACEHOLDER", "0790": "ST_PLACEHOLDER", "0795": "ST_PLACEHOLDER", "0799": "ST_PLACEHOLDER", "0805": "DISCO_L053C8", "0810": "DISCO_F334C8", "0815": "DISCO_F746NG", "0820": "DISCO_L476VG", "0824": "LPC824", "1000": "LPC2368", "1001": "LPC2368", "1010": "LPC1768", "1017": "HRM1017", "1018": "SSCI824", "1034": "LPC11U34", "1040": "LPC11U24", "1045": "LPC11U24", "1050": "LPC812", "1060": "LPC4088", "1061": "LPC11U35_401", "1062": "LPC4088_DM", "1070": "NRF51822", "1075": "NRF51822_OTA", "1080": "OC_MBUINO", "1090": "RBLAB_NRF51822", "1095": "RBLAB_BLENANO", "1100": "NRF51_DK", "1105": "NRF51_DK_OTA", "1114": "LPC1114", "1120": "NRF51_DONGLE", "1130": "NRF51822_SBK", "1140": "WALLBOT_BLE", "1168": "LPC11U68", "1234": "UBLOX_C027", "1235": "UBLOX_C027", "1549": "LPC1549", "1600": "LPC4330_M4", "1605": "LPC4330_M4", "2000": "EFM32_G8XX_STK", "2005": "EFM32HG_STK3400", "2010": "EFM32WG_STK3800", "2015": "EFM32GG_STK3700", "2020": "EFM32LG_STK3600", "2025": "EFM32TG_STK3300", "2030": "EFM32ZG_STK3200", "2100": "XBED_LPC1768", "3001": "LPC11U24", "4000": "LPC11U35_Y5_MBUG", "4005": "NRF51822_Y5_MBUG", "4100": "MOTE_L152RC", "4337": "LPC4337", "4500": "DELTA_DFCM_NNN40", "5000": "ARM_MPS2", "5001": "ARM_MPS2_M0", "5003": "ARM_MPS2_M0P", "5005": "ARM_MPS2_M0DS", "5007": "ARM_MPS2_M1", "5009": "ARM_MPS2_M3", "5011": "ARM_MPS2_M4", "5015": "ARM_MPS2_M7", "5020": "HOME_GATEWAY_6LOWPAN", "5500": "RZ_A1H", "7778": "TEENSY3_1", "9001": "LPC1347", "9002": "LPC11U24", "9003": "LPC1347", "9004": "ARCH_PRO", "9006": "LPC11U24", "9007": "LPC11U35_501", "9008": "XADOW_M0", "9009": "ARCH_BLE", "9010": "ARCH_GPRS", "9011": "ARCH_MAX", "9012": "SEEED_TINY_BLE", "FFFF": "K20 BOOTLOADER", "RIOT": "RIOT", } # # Note: 'Ven_SEGGER' - This is used to detect devices from EFM family, they use Segger J-LInk to wrap MSD and CDC usb_vendor_list = ['Ven_MBED', 'Ven_SEGGER'] # Interface def list_mbeds(self): """! Get information about mbeds connected to device @return Returns None or if no error MBED_BOARDS = [ <MBED_BOARD>, ] @details MBED_BOARD { 'mount_point' : <>, 'serial_port' : <>, 'target_id' : <>, 'platform_name' : <>, } # If field unknown, place None """ return None def list_mbeds_ext(self): """! Function adds extra information for each mbed device @return Returns list of mbed devices plus extended data like 'platform_name_unique' @details Get information about mbeds with extended parameters/info included """ platform_names = {} # Count existing platforms and assign unique number mbeds = self.list_mbeds() for i, val in enumerate(mbeds): platform_name = val['platform_name'] if platform_name not in platform_names: platform_names[platform_name] = 0 else: platform_names[platform_name] += 1 # Assign normalized, unique string at the end of target name: TARGET_NAME[x] where x is an ordinal integer mbeds[i]['platform_name_unique'] = "%s[%d]" % (platform_name, platform_names[platform_name]) if self.DEBUG_FLAG: self.debug(self.list_mbeds_ext.__name__, (mbeds[i]['platform_name_unique'], val['target_id'])) return mbeds def list_platforms(self): """ Useful if you just want to know which platforms are currently available on the system @return List of (unique values) available platforms """ result = [] mbeds = self.list_mbeds() for i, val in enumerate(mbeds): platform_name = val['platform_name'] if platform_name not in result: result.append(platform_name) return result def list_platforms_ext(self): """ Useful if you just want to know how many platforms of each type are currently available on the system @return Dict of platform: platform_count """ result = {} mbeds = self.list_mbeds() for i, val in enumerate(mbeds): platform_name = val['platform_name'] if platform_name not in result: result[platform_name] = 1 else: result[platform_name] += 1 return result def list_mbeds_by_targetid(self): """ Get information about mbeds with extended parameters/info included @return Returns dictionary where keys are TargetIDs and values are mbed structures @details Ordered by target id (key: target_id). """ result = {} mbed_list = self.list_mbeds_ext() for mbed in mbed_list: target_id = mbed['target_id'] result[target_id] = mbed return result # Private part, methods used to drive interface functions def load_mbed_description(self, file_name): """ Loads JSON file with mbeds' description (mapping between target id and platform name) Sets self.manufacture_ids with mapping between manufacturers' ids and platform name. """ #self.manufacture_ids = {} # TODO: load this values from file pass def err(self, text): """! Prints error messages @param text Text to be included in error message @details Function prints directly on console """ print 'error: %s'% text def debug(self, name, text): """! Prints error messages @param name Called function name @param text Text to be included in debug message @details Function prints directly on console """ print 'debug @%s.%s: %s'% (self.__class__.__name__, name, text) def __str__(self): """! Object to string casting @return Stringified class object should be prettytable formated string """ return self.get_string() def get_string(self, border=False, header=True, padding_width=0, sortby='platform_name'): """! Printing with some sql table like decorators @param border Table border visibility @param header Table header visibility @param padding_width Table padding @param sortby Column used to sort results @return Returns string which can be printed on console """ from prettytable import PrettyTable from prettytable import PLAIN_COLUMNS result = '' mbeds = self.list_mbeds_ext() if mbeds is not None: """ ['platform_name', 'mount_point', 'serial_port', 'target_id'] - columns generated from USB auto-detection ['platform_name_unique', ...] - columns generated outside detection subsystem (OS dependent detection) """ columns = ['platform_name', 'platform_name_unique', 'mount_point', 'serial_port', 'target_id'] pt = PrettyTable(columns) for col in columns: pt.align[col] = 'l' for mbed in mbeds: row = [] for col in columns: row.append(mbed[col] if col in mbed and mbed[col] is not None else 'unknown') pt.add_row(row) pt.set_style(PLAIN_COLUMNS) result = pt.get_string(border=border, header=header, padding_width=padding_width, sortby=sortby) return result # Private functions supporting API def get_json_data_from_file(self, json_spec_filename, verbose=False): """! Loads from file JSON formatted string to data structure @return None if JSON can be loaded """ result = None try: with open(json_spec_filename) as data_file: try: result = json.load(data_file) except ValueError as json_error_msg: result = None if verbose: print "Error parsing file(%s): %s" % (json_spec_filename, json_error_msg) except IOError as fileopen_error_msg: if verbose: print "Warning: %s" % (fileopen_error_msg) return result def get_mbed_htm_target_id(self, mount_point): """! Function scans mbed.htm to get information about TargetID. @return Function returns targetID, in case of failure returns None. @details Note: This function should be improved to scan variety of boards' mbed.htm files """ result = None MBED_HTM_LIST = ['mbed.htm', 'MBED.HTM', 'MBED.htm'] for mbed_htm in MBED_HTM_LIST: mbed_htm_path = os.path.join(mount_point, mbed_htm) try: with open(mbed_htm_path, 'r') as f: fline = f.readlines() for line in fline: target_id = self.scan_html_line_for_target_id(line) if target_id is not None: return target_id except IOError: if self.DEBUG_FLAG: self.debug(self.get_mbed_htm_target_id.__name__, ('Failed to open file', mbed_htm_path)) return result def scan_html_line_for_target_id(self, line): """! Scan if given line contains target id encoded in URL. @return Returns None when no target_id string in line """ # Detecting modern mbed.htm file format m = re.search('\?code=([a-fA-F0-9]+)', line) if m is not None: result = m.groups()[0] if self.DEBUG_FLAG: self.debug(self.scan_html_line_for_target_id.__name__, line.strip()) if self.DEBUG_FLAG: self.debug(self.scan_html_line_for_target_id.__name__, (m.groups(), result)) return result # Last resort, we can try to see if old mbed.htm format is there else: m = re.search('\?auth=([a-fA-F0-9]+)', line) if m is not None: result = m.groups()[0] if self.DEBUG_FLAG: self.debug(self.scan_html_line_for_target_id.__name__, line.strip()) if self.DEBUG_FLAG: self.debug(self.scan_html_line_for_target_id.__name__, (m.groups(), result)) return result return None
{ "content_hash": "e9d9e0f5bffc3dc39e74ef976dd0586b", "timestamp": "", "source": "github", "line_count": 376, "max_line_length": 121, "avg_line_length": 35.88563829787234, "alnum_prop": 0.5514711331801675, "repo_name": "0xc0170/mbed-ls", "id": "d1e2275628f7b2401dd0d70b2f822e2ec7597573", "size": "13493", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "mbed_lstools/lstools_base.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "58124" } ], "symlink_target": "" }
/** * SECTION:element-zbar * @title: zbar * * Detect bar codes in the video streams and send them as element messages to * the #GstBus if .#GstZBar:message property is %TRUE. * If the .#GstZBar:attach-frame property is %TRUE, the posted barcode message * includes a sample of the frame where the barcode was detected (Since 1.6). * * The element generate messages named`barcode`. The structure containes these fields: * * * #GstClockTime `timestamp`: the timestamp of the buffer that triggered the message. * * gchar * `type`: the symbol type. * * gchar * `symbol`: the deteted bar code data. * * gint `quality`: an unscaled, relative quantity: larger values are better than smaller * values. * * GstSample `frame`: the frame in which the barcode message was detected, if * the .#GstZBar:attach-frame property was set to %TRUE (Since 1.6) * * ## Example launch lines * |[ * gst-launch-1.0 -m v4l2src ! videoconvert ! zbar ! videoconvert ! xvimagesink * ]| This pipeline will detect barcodes and send them as messages. * |[ * gst-launch-1.0 -m v4l2src ! tee name=t ! queue ! videoconvert ! zbar ! fakesink t. ! queue ! xvimagesink * ]| Same as above, but running the filter on a branch to keep the display in color * */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "gstzbar.h" #include <string.h> #include <math.h> #include <gst/video/video.h> GST_DEBUG_CATEGORY_STATIC (zbar_debug); #define GST_CAT_DEFAULT zbar_debug /* GstZBar signals and args */ enum { /* FILL ME */ LAST_SIGNAL }; enum { PROP_0, PROP_MESSAGE, PROP_ATTACH_FRAME, PROP_CACHE }; #define DEFAULT_CACHE FALSE #define DEFAULT_MESSAGE TRUE #define DEFAULT_ATTACH_FRAME FALSE #define ZBAR_YUV_CAPS \ "{ Y800, I420, YV12, NV12, NV21, Y41B, Y42B, YUV9, YVU9 }" static GstStaticPadTemplate gst_zbar_src_template = GST_STATIC_PAD_TEMPLATE ("src", GST_PAD_SRC, GST_PAD_ALWAYS, GST_STATIC_CAPS (GST_VIDEO_CAPS_MAKE (ZBAR_YUV_CAPS)) ); static GstStaticPadTemplate gst_zbar_sink_template = GST_STATIC_PAD_TEMPLATE ("sink", GST_PAD_SINK, GST_PAD_ALWAYS, GST_STATIC_CAPS (GST_VIDEO_CAPS_MAKE (ZBAR_YUV_CAPS)) ); static void gst_zbar_finalize (GObject * object); static void gst_zbar_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec); static void gst_zbar_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec); static gboolean gst_zbar_start (GstBaseTransform * base); static gboolean gst_zbar_stop (GstBaseTransform * base); static GstFlowReturn gst_zbar_transform_frame_ip (GstVideoFilter * vfilter, GstVideoFrame * frame); #define gst_zbar_parent_class parent_class G_DEFINE_TYPE (GstZBar, gst_zbar, GST_TYPE_VIDEO_FILTER); static void gst_zbar_class_init (GstZBarClass * g_class) { GObjectClass *gobject_class; GstElementClass *gstelement_class; GstBaseTransformClass *trans_class; GstVideoFilterClass *vfilter_class; gobject_class = G_OBJECT_CLASS (g_class); gstelement_class = GST_ELEMENT_CLASS (g_class); trans_class = GST_BASE_TRANSFORM_CLASS (g_class); vfilter_class = GST_VIDEO_FILTER_CLASS (g_class); gobject_class->set_property = gst_zbar_set_property; gobject_class->get_property = gst_zbar_get_property; gobject_class->finalize = gst_zbar_finalize; g_object_class_install_property (gobject_class, PROP_MESSAGE, g_param_spec_boolean ("message", "message", "Post a barcode message for each detected code", DEFAULT_MESSAGE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); /** * GstZBar::attach-frame: * * Attach the frame in which the barcode was detected to the posted * barcode message. * * Since: 1.6 */ g_object_class_install_property (gobject_class, PROP_ATTACH_FRAME, g_param_spec_boolean ("attach-frame", "Attach frame", "Attach a frame dump to each barcode message", DEFAULT_ATTACH_FRAME, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_CACHE, g_param_spec_boolean ("cache", "cache", "Enable or disable the inter-image result cache", DEFAULT_CACHE, G_PARAM_READWRITE | GST_PARAM_MUTABLE_READY | G_PARAM_STATIC_STRINGS)); gst_element_class_set_static_metadata (gstelement_class, "Barcode detector", "Filter/Analyzer/Video", "Detect bar codes in the video streams", "Stefan Kost <ensonic@users.sf.net>"); gst_element_class_add_static_pad_template (gstelement_class, &gst_zbar_sink_template); gst_element_class_add_static_pad_template (gstelement_class, &gst_zbar_src_template); trans_class->start = GST_DEBUG_FUNCPTR (gst_zbar_start); trans_class->stop = GST_DEBUG_FUNCPTR (gst_zbar_stop); trans_class->transform_ip_on_passthrough = FALSE; vfilter_class->transform_frame_ip = GST_DEBUG_FUNCPTR (gst_zbar_transform_frame_ip); } static void gst_zbar_init (GstZBar * zbar) { zbar->cache = DEFAULT_CACHE; zbar->message = DEFAULT_MESSAGE; zbar->attach_frame = DEFAULT_ATTACH_FRAME; zbar->scanner = zbar_image_scanner_create (); } static void gst_zbar_finalize (GObject * object) { GstZBar *zbar = GST_ZBAR (object); zbar_image_scanner_destroy (zbar->scanner); G_OBJECT_CLASS (parent_class)->finalize (object); } static void gst_zbar_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec) { GstZBar *zbar; g_return_if_fail (GST_IS_ZBAR (object)); zbar = GST_ZBAR (object); switch (prop_id) { case PROP_CACHE: zbar->cache = g_value_get_boolean (value); break; case PROP_MESSAGE: zbar->message = g_value_get_boolean (value); break; case PROP_ATTACH_FRAME: zbar->attach_frame = g_value_get_boolean (value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static void gst_zbar_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec) { GstZBar *zbar; g_return_if_fail (GST_IS_ZBAR (object)); zbar = GST_ZBAR (object); switch (prop_id) { case PROP_CACHE: g_value_set_boolean (value, zbar->cache); break; case PROP_MESSAGE: g_value_set_boolean (value, zbar->message); break; case PROP_ATTACH_FRAME: g_value_set_boolean (value, zbar->attach_frame); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static GstFlowReturn gst_zbar_transform_frame_ip (GstVideoFilter * vfilter, GstVideoFrame * frame) { GstZBar *zbar = GST_ZBAR (vfilter); gpointer data; gint stride, height; zbar_image_t *image; const zbar_symbol_t *symbol; int n; image = zbar_image_create (); /* all formats we support start with an 8-bit Y plane. zbar doesn't need * to know about the chroma plane(s) */ data = GST_VIDEO_FRAME_COMP_DATA (frame, 0); stride = GST_VIDEO_FRAME_COMP_STRIDE (frame, 0); height = GST_VIDEO_FRAME_HEIGHT (frame); zbar_image_set_format (image, GST_MAKE_FOURCC ('Y', '8', '0', '0')); zbar_image_set_size (image, stride, height); zbar_image_set_data (image, (gpointer) data, stride * height, NULL); /* scan the image for barcodes */ n = zbar_scan_image (zbar->scanner, image); if (G_UNLIKELY (n == -1)) { GST_WARNING_OBJECT (zbar, "Error trying to scan frame. Skipping"); goto out; } if (n == 0) goto out; /* extract results */ symbol = zbar_image_first_symbol (image); for (; symbol; symbol = zbar_symbol_next (symbol)) { zbar_symbol_type_t typ = zbar_symbol_get_type (symbol); const char *data = zbar_symbol_get_data (symbol); gint quality = zbar_symbol_get_quality (symbol); GST_DEBUG_OBJECT (zbar, "decoded %s symbol \"%s\" at quality %d", zbar_get_symbol_name (typ), data, quality); if (zbar->cache && zbar_symbol_get_count (symbol) != 0) continue; if (zbar->message) { GstMessage *m; GstStructure *s; GstSample *sample; GstCaps *sample_caps; GstClockTime timestamp, running_time, stream_time, duration; timestamp = GST_BUFFER_TIMESTAMP (frame->buffer); duration = GST_BUFFER_DURATION (frame->buffer); running_time = gst_segment_to_running_time (&GST_BASE_TRANSFORM (zbar)->segment, GST_FORMAT_TIME, timestamp); stream_time = gst_segment_to_stream_time (&GST_BASE_TRANSFORM (zbar)->segment, GST_FORMAT_TIME, timestamp); s = gst_structure_new ("barcode", "timestamp", G_TYPE_UINT64, timestamp, "stream-time", G_TYPE_UINT64, stream_time, "running-time", G_TYPE_UINT64, running_time, "type", G_TYPE_STRING, zbar_get_symbol_name (typ), "symbol", G_TYPE_STRING, data, "quality", G_TYPE_INT, quality, NULL); if (GST_CLOCK_TIME_IS_VALID (duration)) gst_structure_set (s, "duration", G_TYPE_UINT64, duration, NULL); if (zbar->attach_frame) { /* create a sample from image */ sample_caps = gst_video_info_to_caps (&frame->info); sample = gst_sample_new (frame->buffer, sample_caps, NULL, NULL); gst_caps_unref (sample_caps); gst_structure_set (s, "frame", GST_TYPE_SAMPLE, sample, NULL); gst_sample_unref (sample); } m = gst_message_new_element (GST_OBJECT (zbar), s); gst_element_post_message (GST_ELEMENT (zbar), m); } else if (zbar->attach_frame) GST_WARNING_OBJECT (zbar, "attach-frame=true has no effect if message=false"); } out: /* clean up */ zbar_image_scanner_recycle_image (zbar->scanner, image); zbar_image_destroy (image); return GST_FLOW_OK; } static gboolean gst_zbar_start (GstBaseTransform * base) { GstZBar *zbar = GST_ZBAR (base); /* start the cache if enabled (e.g. for filtering dupes) */ zbar_image_scanner_enable_cache (zbar->scanner, zbar->cache); return TRUE; } static gboolean gst_zbar_stop (GstBaseTransform * base) { GstZBar *zbar = GST_ZBAR (base); /* stop the cache if enabled (e.g. for filtering dupes) */ zbar_image_scanner_enable_cache (zbar->scanner, zbar->cache); return TRUE; } static gboolean plugin_init (GstPlugin * plugin) { GST_DEBUG_CATEGORY_INIT (zbar_debug, "zbar", 0, "zbar"); return gst_element_register (plugin, "zbar", GST_RANK_NONE, GST_TYPE_ZBAR); } GST_PLUGIN_DEFINE (GST_VERSION_MAJOR, GST_VERSION_MINOR, zbar, "zbar barcode scanner", plugin_init, VERSION, GST_LICENSE, GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN);
{ "content_hash": "9ba6591aba5931b52e7cfa802c168592", "timestamp": "", "source": "github", "line_count": 357, "max_line_length": 107, "avg_line_length": 29.680672268907564, "alnum_prop": 0.6676104190260476, "repo_name": "google/aistreams", "id": "6591d1968d63bf73692b78af0862299f91e8609b", "size": "11413", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "third_party/gst-plugins-bad/ext/zbar/gstzbar.c", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "77741" }, { "name": "C++", "bytes": "626396" }, { "name": "Python", "bytes": "41809" }, { "name": "Starlark", "bytes": "56595" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <title>Game</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script src="application.js"></script> <script src="controller.js"></script> <link rel="stylesheet" type="text/css" href="application.css"> </head> <body> <h1>Use the arrow keys to move, and z to inspect</h1> <canvas id="canvas" width="1000" height ="450" style="border:1px solid #000000;"></canvas> <div id ="ozymandias"> <p class="poem" id="one">I met a traveller from an antique land<br> Who said: Two vast and trunkless legs of stone<br> Stand in the desert. Near them on the sand,<br> Half sunk, a shattered visage lies, whose frown</p> <p class="poem" id="two">And wrinkled lip and sneer of cold command<br> Tell that its sculptor well those passions read<br> Which yet survive, stamped on these lifeless things,<br> The hand that mocked them and the heart that fed.</p> <p class="poem" id="three">And on the pedestal these words appear:<br> `My name is Ozymandias, King of Kings:<br> Look on my works, ye mighty, and despair!'</p> <p class="poem" id="four">Nothing beside remains. Round the decay<br> Of that colossal wreck, boundless and bare,<br> The lone and level sands stretch far away". </p> </div> <audio autoplay loop> <source src="./audio/ghost_town_wind.mp3" type="audio/mpeg"> </audio> <audio id="bell"> <source src="./audio/bell.mp3"> </audio> </body> </html>
{ "content_hash": "205fd29c99b70356f59bc78913e77fc7", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 92, "avg_line_length": 38.82051282051282, "alnum_prop": 0.6697490092470277, "repo_name": "NoahHeinrich/Game-testing", "id": "c51ad79417147cce120fc21a07584e76fdcf2787", "size": "1514", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "game.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "126" }, { "name": "HTML", "bytes": "1514" }, { "name": "JavaScript", "bytes": "1588" } ], "symlink_target": "" }
require "test_helper" require "models/firm" require "models/account" require "models/department" module ActiveRecord module Associations class HasOneTest < SpannerAdapter::TestCase include SpannerAdapter::Associations::TestHelper attr_accessor :firm, :account def setup super @account = Account.create name: "Account - #{rand 1000}", credit_limit: 100 @firm = Firm.create name: "Firm-#{rand 1000}", account: account @account.reload @firm.reload end def teardown Firm.destroy_all Account.destroy_all Department.destroy_all end def test_has_one assert_equal account, firm.account assert_equal account.credit_limit, firm.account.credit_limit end def test_has_one_does_not_use_order_by sql_log = capture_sql { firm.account } assert sql_log.all? { |sql| !/order by/i.match?(sql) }, "ORDER BY was used in the query: #{sql_log}" end def test_finding_using_primary_key assert_equal Account.find_by(firm_id: firm.id), firm.account end def test_successful_build_association account = firm.build_account(credit_limit: 1000) assert account.save firm.reload assert_equal account, firm.account end def test_delete_associated_records assert_equal account, firm.account firm.account.destroy firm.reload assert_nil firm.account end def test_polymorphic_association assert_equal 0, firm.departments.count firm.departments.create(name: "Department - 1") firm.reload assert_equal 1, firm.departments.count assert_equal "Department - 1", firm.departments.first.name end end end end
{ "content_hash": "3b9289373d750983d886d58d7e148887", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 108, "avg_line_length": 25.422535211267604, "alnum_prop": 0.6387811634349031, "repo_name": "googleapis/ruby-spanner-activerecord", "id": "0189dce9e3ef3f56094d8113682cae7053db3498", "size": "2014", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "acceptance/cases/associations/has_one_associations_test.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "695332" }, { "name": "Shell", "bytes": "18145" } ], "symlink_target": "" }
require "thor/shell/basic" module GemSuit class CLI < Thor module Base module Shell def self.included(base) base.send :include, InstanceMethods end module InstanceMethods def shell @shell ||= Thor::Shell::Basic.new end def is?(*args) shell.send :is?, *args end def agree?(question, default = nil) opts = %w(y n).collect{|x| !default.nil? && x =~ is?(default) ? x.upcase : x} answer = ask question, opts, default !!(answer =~ is?(:yes)) end def ask(question, opts = nil, default = nil) in_brackets = [opts, default].compact.first statement = [question, ("[#{in_brackets}]" unless in_brackets.nil?)].compact.join " " answer = shell.ask statement if options.interactive? || default.nil? answer.nil? || answer.empty? ? default.to_s : answer end end end end end end
{ "content_hash": "c3c725cf7a09a0058b37eb6e254f74b6", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 99, "avg_line_length": 25.073170731707318, "alnum_prop": 0.52431906614786, "repo_name": "archan937/gem_suit", "id": "0ea62ac9b385ccb0c618540c7294016fd9ce5dd8", "size": "1028", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/gem_suit/cli/base/shell.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "54228" } ], "symlink_target": "" }
![screenshot.png](screenshot.png) [![Build Status](https://travis-ci.org/nodaguti/word-quiz-generator-webapp.svg?branch=master)](https://travis-ci.org/nodaguti/word-quiz-generator-webapp) [![Dependency Status](https://david-dm.org/nodaguti/word-quiz-generator-webapp.svg)](https://david-dm.org/nodaguti/word-quiz-generator-webapp) [![devDependency Status](https://david-dm.org/nodaguti/word-quiz-generator-webapp/dev-status.svg)](https://david-dm.org/nodaguti/word-quiz-generator-webapp#info=devDependencies) [![Code Climate](https://codeclimate.com/github/nodaguti/word-quiz-generator-webapp/badges/gpa.svg)](https://codeclimate.com/github/nodaguti/word-quiz-generator-webapp) A web application for generating a vocabulary quiz. Once you specify a test material, Online Word Quiz Generator then retrieves a sentence which includes one of the words/phrases in the material from existing source texts, and creates a "Write the definition" questions. This package features the Web-based GUI. If you need full control over the quiz generation process, or want to use it from CLI or your program, please use [word-quiz-generator](https://github.com/nodaguti/word-quiz-generator) package. ## Launch ```sh $ npm start ``` This is a NodeJS application. You need to have the latest version of Node.js. The app will run on `127.0.0.1:8080` by default. If you want to change it, please specify a new IP address (hostname) and port number through environment variables: ```sh export IP=192.168.0.1 export PORT=8008 ``` ## Resources The lists of materials and sources the application uses are stored in resources.json, which is located on the root of this repository by default. If you want to change the path, please specify a new path through environment variables: ```sh export RESOURCES=/path/to/resources.json ``` ### Materials The materials are a CSV-formatted list of words/phrases to be on quiz. ``` { "id": "duo", "name": "Duo 3.0", "lang": "en", "sections": "1-45", "path": "../data/materials/duo.csv" } ``` - __id__ An unique identity. - __name__ A material's name which will be shown in the material list on the app. - __lang__ The language name in which a material written. It must be one of the [IETF language tags](http://unicode.org/cldr/utility/languageid.jsp). - __sections__ The number of sections a material has. - __path__ The relative path to a material from resources.json. For more details about the format of a material file, please see [ReadMe at word-quiz-generator repository](https://github.com/nodaguti/word-quiz-generator#material). ### Sources The sources are a text which will be used on generating a question sentence. ``` { "id": "university-of-tokyo-entrance-examination-english", "name": "Entrance Exam of University of Tokyo (English, 2005)", "lang": "en", "path": "../data/sources/en/tokyo/" } ``` - __id__ An unique identity. - __name__ A source's name which will be shown in the sources list on the app. - __lang__ An language name and must be one of the [IETF language tags](http://unicode.org/cldr/utility/languageid.jsp). - __path__ A relative path to the material from resources.json. The app can use a preprocessed and lemmatized text to improve the quality of searching a word/phrase. For more details please see [Preprocessing and Lemmatizing at word-quiz-generator repository](https://github.com/nodaguti/word-quiz-generator#preprocessing-and-lemmatizing). ## Contributing 1. Fork it! 2. Create your feature branch: `git checkout -b my-new-feature` 3. Commit your changes: `git commit -am 'Add some feature'` 4. Push to the branch: `git push origin my-new-feature` 5. Submit a pull request :D ## License MIT License (http://nodaguti.mit-license.org/)
{ "content_hash": "178465189bb2aab231d9c8ecd093c8e4", "timestamp": "", "source": "github", "line_count": 117, "max_line_length": 275, "avg_line_length": 32.205128205128204, "alnum_prop": 0.7380573248407644, "repo_name": "nodaguti/word-quiz-generator-webapp", "id": "d3b3977caaebdbae7198196e25feb9396b51ff34", "size": "3798", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ReadMe.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3535" }, { "name": "HTML", "bytes": "377" }, { "name": "JavaScript", "bytes": "54668" } ], "symlink_target": "" }
SUPHARNT_IMPORT_SYSCALL(NtAllocateVirtualMemory, 24) SUPHARNT_IMPORT_SYSCALL(NtClearEvent, 4) SUPHARNT_IMPORT_SYSCALL(NtClose, 4) SUPHARNT_IMPORT_SYSCALL(NtCreateEvent, 20) SUPHARNT_IMPORT_SYSCALL(NtCreateFile, 44) SUPHARNT_IMPORT_SYSCALL(NtCreateSymbolicLinkObject, 16) SUPHARNT_IMPORT_SYSCALL(NtDelayExecution, 8) SUPHARNT_IMPORT_SYSCALL(NtDeviceIoControlFile, 40) SUPHARNT_IMPORT_SYSCALL(NtDuplicateObject, 28) SUPHARNT_IMPORT_SYSCALL(NtFlushBuffersFile, 8) SUPHARNT_IMPORT_SYSCALL(NtFreeVirtualMemory, 16) SUPHARNT_IMPORT_SYSCALL(NtGetContextThread, 8) SUPHARNT_IMPORT_SYSCALL(NtMapViewOfSection, 40) SUPHARNT_IMPORT_SYSCALL(NtOpenDirectoryObject, 12) SUPHARNT_IMPORT_SYSCALL(NtOpenEvent, 12) SUPHARNT_IMPORT_SYSCALL(NtOpenKey, 12) SUPHARNT_IMPORT_SYSCALL(NtOpenProcess, 16) SUPHARNT_IMPORT_SYSCALL(NtOpenProcessToken, 12) SUPHARNT_IMPORT_SYSCALL(NtOpenSymbolicLinkObject, 12) SUPHARNT_IMPORT_SYSCALL(NtOpenThread, 16) SUPHARNT_IMPORT_SYSCALL(NtOpenThreadToken, 16) SUPHARNT_IMPORT_SYSCALL(NtProtectVirtualMemory, 20) SUPHARNT_IMPORT_SYSCALL(NtQueryDirectoryFile, 44) SUPHARNT_IMPORT_SYSCALL(NtQueryDirectoryObject, 28) SUPHARNT_IMPORT_SYSCALL(NtQueryEvent, 20) SUPHARNT_IMPORT_SYSCALL(NtQueryInformationFile, 20) SUPHARNT_IMPORT_SYSCALL(NtQueryInformationProcess, 20) SUPHARNT_IMPORT_SYSCALL(NtQueryInformationThread, 20) SUPHARNT_IMPORT_SYSCALL(NtQueryInformationToken, 20) SUPHARNT_IMPORT_SYSCALL(NtQueryObject, 20) SUPHARNT_IMPORT_SYSCALL(NtQuerySecurityObject, 20) SUPHARNT_IMPORT_SYSCALL(NtQuerySymbolicLinkObject, 12) SUPHARNT_IMPORT_SYSCALL(NtQuerySystemInformation, 16) SUPHARNT_IMPORT_SYSCALL(NtQueryTimerResolution, 12) SUPHARNT_IMPORT_SYSCALL(NtQueryValueKey, 24) SUPHARNT_IMPORT_SYSCALL(NtQueryVirtualMemory, 24) SUPHARNT_IMPORT_SYSCALL(NtReadFile, 36) SUPHARNT_IMPORT_SYSCALL(NtReadVirtualMemory, 20) SUPHARNT_IMPORT_SYSCALL(NtResetEvent, 8) SUPHARNT_IMPORT_SYSCALL(NtResumeProcess, 4) SUPHARNT_IMPORT_SYSCALL(NtResumeThread, 8) SUPHARNT_IMPORT_SYSCALL(NtSetContextThread, 8) SUPHARNT_IMPORT_SYSCALL(NtSetEvent, 8) SUPHARNT_IMPORT_SYSCALL(NtSetInformationFile, 20) SUPHARNT_IMPORT_SYSCALL(NtSetInformationObject, 16) SUPHARNT_IMPORT_SYSCALL(NtSetInformationProcess, 16) SUPHARNT_IMPORT_SYSCALL(NtSetInformationThread, 16) SUPHARNT_IMPORT_SYSCALL(NtSetTimerResolution, 12) SUPHARNT_IMPORT_SYSCALL(NtSuspendProcess, 4) SUPHARNT_IMPORT_SYSCALL(NtSuspendThread, 8) SUPHARNT_IMPORT_SYSCALL(NtTerminateProcess, 8) SUPHARNT_IMPORT_SYSCALL(NtTerminateThread, 8) SUPHARNT_IMPORT_SYSCALL(NtUnmapViewOfSection, 8) SUPHARNT_IMPORT_SYSCALL(NtWaitForMultipleObjects, 20) SUPHARNT_IMPORT_SYSCALL(NtWaitForSingleObject, 12) SUPHARNT_IMPORT_SYSCALL(NtWriteFile, 36) SUPHARNT_IMPORT_SYSCALL(NtWriteVirtualMemory, 20) SUPHARNT_IMPORT_SYSCALL(NtYieldExecution, 0) SUPHARNT_IMPORT_SYSCALL(NtCreateSection, 28) SUPHARNT_IMPORT_SYSCALL(NtQueryVolumeInformationFile, 20) SUPHARNT_IMPORT_STDCALL_EARLY(LdrInitializeThunk, 12) SUPHARNT_IMPORT_STDCALL_EARLY_OPTIONAL(LdrRegisterDllNotification, 16) SUPHARNT_IMPORT_STDCALL_EARLY(LdrGetDllHandle, 16) SUPHARNT_IMPORT_STDCALL(RtlAddAccessAllowedAce, 16) SUPHARNT_IMPORT_STDCALL(RtlAddAccessDeniedAce, 16) SUPHARNT_IMPORT_STDCALL(RtlAllocateHeap, 12) SUPHARNT_IMPORT_STDCALL(RtlCompactHeap, 8) SUPHARNT_IMPORT_STDCALL(RtlCopySid, 12) SUPHARNT_IMPORT_STDCALL(RtlCreateAcl, 12) SUPHARNT_IMPORT_STDCALL(RtlCreateHeap, 24) SUPHARNT_IMPORT_STDCALL(RtlCreateProcessParameters, 40) SUPHARNT_IMPORT_STDCALL(RtlCreateSecurityDescriptor, 8) SUPHARNT_IMPORT_STDCALL(RtlCreateUserProcess, 40) SUPHARNT_IMPORT_STDCALL(RtlCreateUserThread, 40) SUPHARNT_IMPORT_STDCALL(RtlDestroyProcessParameters, 4) SUPHARNT_IMPORT_STDCALL_EARLY(RtlDosApplyFileIsolationRedirection_Ustr, 36) SUPHARNT_IMPORT_STDCALL_EARLY(RtlEqualSid, 8) SUPHARNT_IMPORT_STDCALL_EARLY_OPTIONAL(RtlExitUserProcess, 4) SUPHARNT_IMPORT_STDCALL_EARLY(RtlExitUserThread, 4) SUPHARNT_IMPORT_STDCALL(RtlExpandEnvironmentStrings_U, 16) SUPHARNT_IMPORT_STDCALL(RtlFreeHeap, 12) SUPHARNT_IMPORT_STDCALL_EARLY(RtlFreeUnicodeString, 4) SUPHARNT_IMPORT_STDCALL_EARLY(RtlGetLastNtStatus, 0) SUPHARNT_IMPORT_STDCALL_EARLY(RtlGetLastWin32Error, 0) SUPHARNT_IMPORT_STDCALL_EARLY(RtlGetVersion, 4) SUPHARNT_IMPORT_STDCALL_EARLY(RtlInitializeSid, 12) SUPHARNT_IMPORT_STDCALL_EARLY(RtlNtStatusToDosError, 4) SUPHARNT_IMPORT_STDCALL_EARLY(RtlReAllocateHeap, 16) SUPHARNT_IMPORT_STDCALL_EARLY(RtlRestoreLastWin32Error, 4) SUPHARNT_IMPORT_STDCALL(RtlSetDaclSecurityDescriptor, 16) SUPHARNT_IMPORT_STDCALL_EARLY(RtlSetLastWin32Error, 4) SUPHARNT_IMPORT_STDCALL_EARLY(RtlSetLastWin32ErrorAndNtStatusFromNtStatus, 4) SUPHARNT_IMPORT_STDCALL(RtlSizeHeap, 12) SUPHARNT_IMPORT_STDCALL_EARLY(RtlSubAuthoritySid, 8)
{ "content_hash": "1a3c684670ffb55007bcecab73e40aef", "timestamp": "", "source": "github", "line_count": 97, "max_line_length": 77, "avg_line_length": 48.23711340206186, "alnum_prop": 0.854028638597991, "repo_name": "egraba/vbox_openbsd", "id": "c9b7f7b83356a5b6dbe7a07202747655ad5c216a", "size": "4679", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "VirtualBox-5.0.0/src/VBox/HostDrivers/Support/win/import-template-ntdll.h", "mode": "33188", "license": "mit", "language": [ { "name": "Ada", "bytes": "88714" }, { "name": "Assembly", "bytes": "4303680" }, { "name": "AutoIt", "bytes": "2187" }, { "name": "Batchfile", "bytes": "95534" }, { "name": "C", "bytes": "192632221" }, { "name": "C#", "bytes": "64255" }, { "name": "C++", "bytes": "83842667" }, { "name": "CLIPS", "bytes": "5291" }, { "name": "CMake", "bytes": "6041" }, { "name": "CSS", "bytes": "26756" }, { "name": "D", "bytes": "41844" }, { "name": "DIGITAL Command Language", "bytes": "56579" }, { "name": "DTrace", "bytes": "1466646" }, { "name": "GAP", "bytes": "350327" }, { "name": "Groff", "bytes": "298540" }, { "name": "HTML", "bytes": "467691" }, { "name": "IDL", "bytes": "106734" }, { "name": "Java", "bytes": "261605" }, { "name": "JavaScript", "bytes": "80927" }, { "name": "Lex", "bytes": "25122" }, { "name": "Logos", "bytes": "4941" }, { "name": "Makefile", "bytes": "426902" }, { "name": "Module Management System", "bytes": "2707" }, { "name": "NSIS", "bytes": "177212" }, { "name": "Objective-C", "bytes": "5619792" }, { "name": "Objective-C++", "bytes": "81554" }, { "name": "PHP", "bytes": "58585" }, { "name": "Pascal", "bytes": "69941" }, { "name": "Perl", "bytes": "240063" }, { "name": "PowerShell", "bytes": "10664" }, { "name": "Python", "bytes": "9094160" }, { "name": "QMake", "bytes": "3055" }, { "name": "R", "bytes": "21094" }, { "name": "SAS", "bytes": "1847" }, { "name": "Shell", "bytes": "1460572" }, { "name": "SourcePawn", "bytes": "4139" }, { "name": "TypeScript", "bytes": "142342" }, { "name": "Visual Basic", "bytes": "7161" }, { "name": "XSLT", "bytes": "1034475" }, { "name": "Yacc", "bytes": "22312" } ], "symlink_target": "" }
<html><head><meta charset = 'UTF-8'/><title></title></head><body><center><h1>Fausto Ferreira Gomes</h1></center><ul> <center><p> , 1969-05-12</p><p>Uma certid&#227;o militar, foi o documento que foi exigido ao senhor Fausto Ferreira Gomes para poder tirar a carta de condu&#231;&#227;o</p><img src="fotos/069-D-01.jpg" width=500><p></p></center>
{ "content_hash": "a4e275bea3d3292cdc104df5c9bc1d02", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 116, "avg_line_length": 87.5, "alnum_prop": 0.6828571428571428, "repo_name": "rgllm/uminho", "id": "f61d6e73df18558055a9b2b66745bf80f7839ebe", "size": "350", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "03/PL/tp1/codigo/galeria/069-D-01.html", "mode": "33188", "license": "mit", "language": [ { "name": "Awk", "bytes": "10994" }, { "name": "C", "bytes": "241432" }, { "name": "C#", "bytes": "68553" }, { "name": "C++", "bytes": "709313" }, { "name": "CLIPS", "bytes": "13648" }, { "name": "CMake", "bytes": "10758" }, { "name": "CSS", "bytes": "130829" }, { "name": "HTML", "bytes": "6164024" }, { "name": "Haskell", "bytes": "57476" }, { "name": "Java", "bytes": "948631" }, { "name": "JavaScript", "bytes": "177110" }, { "name": "Lex", "bytes": "4403" }, { "name": "Makefile", "bytes": "13186" }, { "name": "PLSQL", "bytes": "12734" }, { "name": "Prolog", "bytes": "34989" }, { "name": "Python", "bytes": "30180" }, { "name": "R", "bytes": "49327" }, { "name": "Rust", "bytes": "40" }, { "name": "SQLPL", "bytes": "19365" }, { "name": "Scilab", "bytes": "584" }, { "name": "Shell", "bytes": "3336" }, { "name": "TeX", "bytes": "1211757" }, { "name": "Yacc", "bytes": "17107" } ], "symlink_target": "" }
{-# LANGUAGE TupleSections, OverloadedStrings, QuasiQuotes, TemplateHaskell, TypeFamilies, RecordWildCards, DeriveGeneric ,MultiParamTypeClasses ,FlexibleInstances #-} module Protocol.ROC.PointTypes.PointType40 where import GHC.Generics import qualified Data.ByteString as BS import Data.Word import Data.Binary import Data.Binary.Get import Protocol.ROC.Float data PointType40 = PointType40 { pointType40SensorTag :: !PointType40SensorTag ,pointType40SensorAddress :: !PointType40SensorAddress ,pointType40SensorCFG :: !PointType40SensorCFG ,pointType40PollMode :: !PointType40PollMode ,pointType40InterfaceRev :: !PointType40InterfaceRev ,pointType40SensorStatus1 :: !PointType40SensorStatus1 ,pointType40SensorStatus2 :: !PointType40SensorStatus2 ,pointType40SensorVoltage :: !PointType40SensorVoltage ,pointType40DPReading :: !PointType40DPReading ,pointType40StatisPressAPReading :: !PointType40StatisPressAPReading ,pointType40TemperaturePTReading :: !PointType40TemperaturePTReading ,pointType40DPReverseFlow :: !PointType40DPReverseFlow ,pointType40StatisPressEffect :: !PointType40StatisPressEffect ,pointType40DPMinCalibValue :: !PointType40DPMinCalibValue ,pointType40DPCalibMidPnt1 :: !PointType40DPCalibMidPnt1 ,pointType40DPCalibMidPnt2 :: !PointType40DPCalibMidPnt2 ,pointType40DPCalibMidPnt3 :: !PointType40DPCalibMidPnt3 ,pointType40DPMaxCalibValue :: !PointType40DPMaxCalibValue ,pointType40APMinCalibValue :: !PointType40APMinCalibValue ,pointType40APCalibMidPnt1 :: !PointType40APCalibMidPnt1 ,pointType40APCalibMidPnt2 :: !PointType40APCalibMidPnt2 ,pointType40APCalibMidPnt3 :: !PointType40APCalibMidPnt3 ,pointType40APMaxCalibValue :: !PointType40APMaxCalibValue ,pointType40PTMinCalibValue :: !PointType40PTMinCalibValue ,pointType40PTCalibMidPnt1 :: !PointType40PTCalibMidPnt1 ,pointType40PTCalibMidPnt2 :: !PointType40PTCalibMidPnt2 ,pointType40PTCalibMidPnt3 :: !PointType40PTCalibMidPnt3 ,pointType40PTMaxCalibValue :: !PointType40PTMaxCalibValue ,pointType40CalibCommand :: !PointType40CalibCommand ,pointType40CalibType :: !PointType40CalibType ,pointType40CalibSetValue :: !PointType40CalibSetValue ,pointType40ManualDP :: !PointType40ManualDP ,pointType40ManualAP :: !PointType40ManualAP ,pointType40ManualPT :: !PointType40ManualPT ,pointType40DPMode :: !PointType40DPMode ,pointType40DPAlarmCode :: !PointType40DPAlarmCode ,pointType40DPLowAlarm :: !PointType40DPLowAlarm ,pointType40DPHighAlarm :: !PointType40DPHighAlarm ,pointType40DPDeadband :: !PointType40DPDeadband ,pointType40DPAlarmFaultValue :: !PointType40DPAlarmFaultValue ,pointType40APMode :: !PointType40APMode ,pointType40APAlarmCode :: !PointType40APAlarmCode ,pointType40APLowAlarm :: !PointType40APLowAlarm ,pointType40APHighAlarm :: !PointType40APHighAlarm ,pointType40APDeadband :: !PointType40APDeadband ,pointType40APAlarmFaultValue :: !PointType40APAlarmFaultValue ,pointType40PTMode :: !PointType40PTMode ,pointType40PTAlarmCode :: !PointType40PTAlarmCode ,pointType40PTLowAlarm :: !PointType40PTLowAlarm ,pointType40PTHighAlarm :: !PointType40PTHighAlarm ,pointType40PTDeadband :: !PointType40PTDeadband ,pointType40PTFaultValue :: !PointType40PTFaultValue ,pointType40PTBias :: !PointType40PTBias ,pointType40APOffset :: !PointType40APOffset } deriving (Read,Eq, Show, Generic) type PointType40SensorTag = BS.ByteString type PointType40SensorAddress = Word8 type PointType40SensorCFG = Word8 type PointType40PollMode = Word8 type PointType40InterfaceRev = Word8 type PointType40SensorStatus1 = Word8 type PointType40SensorStatus2 = Word8 type PointType40SensorVoltage = Float type PointType40DPReading = Float type PointType40StatisPressAPReading = Float type PointType40TemperaturePTReading = Float type PointType40DPReverseFlow = Float type PointType40StatisPressEffect = Float type PointType40DPMinCalibValue = Float type PointType40DPCalibMidPnt1 = Float type PointType40DPCalibMidPnt2 = Float type PointType40DPCalibMidPnt3 = Float type PointType40DPMaxCalibValue = Float type PointType40APMinCalibValue = Float type PointType40APCalibMidPnt1 = Float type PointType40APCalibMidPnt2 = Float type PointType40APCalibMidPnt3 = Float type PointType40APMaxCalibValue = Float type PointType40PTMinCalibValue = Float type PointType40PTCalibMidPnt1 = Float type PointType40PTCalibMidPnt2 = Float type PointType40PTCalibMidPnt3 = Float type PointType40PTMaxCalibValue = Float type PointType40CalibCommand = Word8 type PointType40CalibType = Word8 type PointType40CalibSetValue = Float type PointType40ManualDP = Float type PointType40ManualAP = Float type PointType40ManualPT = Float type PointType40DPMode = Word8 type PointType40DPAlarmCode = Word8 type PointType40DPLowAlarm = Float type PointType40DPHighAlarm = Float type PointType40DPDeadband = Float type PointType40DPAlarmFaultValue = Float type PointType40APMode = Word8 type PointType40APAlarmCode = Word8 type PointType40APLowAlarm = Float type PointType40APHighAlarm = Float type PointType40APDeadband = Float type PointType40APAlarmFaultValue = Float type PointType40PTMode = Word8 type PointType40PTAlarmCode = Word8 type PointType40PTLowAlarm = Float type PointType40PTHighAlarm = Float type PointType40PTDeadband = Float type PointType40PTFaultValue = Float type PointType40PTBias = Float type PointType40APOffset = Float pointType40Parser :: Get PointType40 pointType40Parser = do sensorTag <- getByteString 10 sensorAddress <- getWord8 sensorCFG <- getWord8 pollMode <- getWord8 interfaceRev <- getWord8 sensorStatus1 <- getWord8 sensorStatus2 <- getWord8 sensorVoltage <- getIeeeFloat32 dPReading <- getIeeeFloat32 statisPressAPReading <- getIeeeFloat32 temperaturePTReading <- getIeeeFloat32 dPReverseFlow <- getIeeeFloat32 statisPressEffect <- getIeeeFloat32 dPMinCalibValue <- getIeeeFloat32 dPCalibMidPnt1 <- getIeeeFloat32 dPCalibMidPnt2 <- getIeeeFloat32 dPCalibMidPnt3 <- getIeeeFloat32 dPMaxCalibValue <- getIeeeFloat32 aPMinCalibValue <- getIeeeFloat32 aPCalibMidPnt1 <- getIeeeFloat32 aPCalibMidPnt2 <- getIeeeFloat32 aPCalibMidPnt3 <- getIeeeFloat32 aPMaxCalibValue <- getIeeeFloat32 pTMinCalibValue <- getIeeeFloat32 pTCalibMidPnt1 <- getIeeeFloat32 pTCalibMidPnt2 <- getIeeeFloat32 pTCalibMidPnt3 <- getIeeeFloat32 pTMaxCalibValue <- getIeeeFloat32 calibCommand <- getWord8 calibType <- getWord8 calibSetValue <- getIeeeFloat32 manualDP <- getIeeeFloat32 manualAP <- getIeeeFloat32 manualPT <- getIeeeFloat32 dPMode <- getWord8 dPAlarmCode <- getWord8 dPLowAlarm <- getIeeeFloat32 dPHighAlarm <- getIeeeFloat32 dPDeadband <- getIeeeFloat32 dPAlarmFaultValue <- getIeeeFloat32 aPMode <- getWord8 aPAlarmCode <- getWord8 aPLowAlarm <- getIeeeFloat32 aPHighAlarm <- getIeeeFloat32 aPDeadband <- getIeeeFloat32 aPAlarmFaultValue <- getIeeeFloat32 pTMode <- getWord8 pTAlarmCode <- getWord8 pTLowAlarm <- getIeeeFloat32 pTHighAlarm <- getIeeeFloat32 pTDeadband <- getIeeeFloat32 pTFaultValue <- getIeeeFloat32 pTBias <- getIeeeFloat32 aPOffset <- getIeeeFloat32 return $ PointType40 sensorTag sensorAddress sensorCFG pollMode interfaceRev sensorStatus1 sensorStatus2 sensorVoltage dPReading statisPressAPReading temperaturePTReading dPReverseFlow statisPressEffect dPMinCalibValue dPCalibMidPnt1 dPCalibMidPnt2 dPCalibMidPnt3 dPMaxCalibValue aPMinCalibValue aPCalibMidPnt1 aPCalibMidPnt2 aPCalibMidPnt3 aPMaxCalibValue pTMinCalibValue pTCalibMidPnt1 pTCalibMidPnt2 pTCalibMidPnt3 pTMaxCalibValue calibCommand calibType calibSetValue manualDP manualAP manualPT dPMode dPAlarmCode dPLowAlarm dPHighAlarm dPDeadband dPAlarmFaultValue aPMode aPAlarmCode aPLowAlarm aPHighAlarm aPDeadband aPAlarmFaultValue pTMode pTAlarmCode pTLowAlarm pTHighAlarm pTDeadband pTFaultValue pTBias aPOffset
{ "content_hash": "de6cb1ecde4daaad43eb19d0a92ac1a6", "timestamp": "", "source": "github", "line_count": 221, "max_line_length": 174, "avg_line_length": 63.29864253393665, "alnum_prop": 0.47229966402173135, "repo_name": "jqpeterson/roc-translator", "id": "fa846cdf3003480c8805002a6185ff25288e346c", "size": "13989", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Protocol/ROC/PointTypes/PointType40.hs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Haskell", "bytes": "717606" } ], "symlink_target": "" }
* How I Put My Life on Hold and Survived Bootcamp / School / Self Education * True Tales of Interviews * What I Didn't Know
{ "content_hash": "856bf285784d4eeeffa2e9d1d0568199", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 75, "avg_line_length": 41.333333333333336, "alnum_prop": 0.7419354838709677, "repo_name": "anvaka/2015.cascadiajs.com", "id": "3f3fb61a6bdd761b47aa3ef9635c18a9f293feee", "size": "156", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "proposals/free_ideas/Adventures of a New Developer.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "331504" }, { "name": "HTML", "bytes": "9084" }, { "name": "JavaScript", "bytes": "7495" } ], "symlink_target": "" }
/** * @provides aphront-error-view-css */ .aphront-error-view, .aphront-error-view-dialogue { border-style: solid; border-width: 1px; } form.aphront-dialog-view .aphront-error-view { margin: 8px 0; } .aphront-error-view { margin: 20px; } .aphront-error-view-dialogue { margin: 0px 0px 16px 0px; } .device-phone .aphront-error-view { margin: 10px; } .aphront-error-view-body { padding: 10px; line-height: 1.6em; } .aphront-error-view-head { padding: 10px 10px 0 10px; font-weight: bold; color: #333333; } .aphront-error-view-list { margin: 0 0 0 20px; list-style: disc; } .aphront-error-severity-error { color: {$red}; border-color: {$red}; background: {$lightred}; } .aphront-error-severity-error .aphront-error-view-head { color: {$red}; } .aphront-error-severity-warning { color: #bc7837; border-color: {$yellow}; background: {$lightyellow}; } .aphront-error-severity-warning .aphront-error-view-head { color: #bc7837; } .aphront-error-severity-notice { color: {$blue}; border-color: {$blue}; background: {$lightblue}; } .aphront-error-severity-notice .aphront-error-view-head { color: {$blue}; } .aphront-error-severity-nodata { border-color: #dfdfdf; background: #f3f3f3; color: #666; } .make-me-sneeze .aphront-error-severity-nodata { background: #fff; border-color: #e6e6e6; }
{ "content_hash": "b34a5c0f9e51d4e9f9da614517d50d1b", "timestamp": "", "source": "github", "line_count": 81, "max_line_length": 58, "avg_line_length": 16.790123456790123, "alnum_prop": 0.674264705882353, "repo_name": "telerik/phabricator", "id": "df6f9fa9302c5757b9cb0e55f7bbb06a720e7f73", "size": "1360", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "webroot/rsrc/css/aphront/error-view.css", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ActionScript", "bytes": "39828" }, { "name": "JavaScript", "bytes": "586905" }, { "name": "PHP", "bytes": "6916423" }, { "name": "Shell", "bytes": "8251" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "fa2c451b57e8388fc78b1023ff41b380", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "325b939e89c420e1b2467d26781af695563bf177", "size": "180", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Maniltoa/Maniltoa schefferi/ Syn. Maniltoa peekelii/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package prometheus import ( "bytes" "fmt" "hash" "sync" ) // MetricVec is a Collector to bundle metrics of the same name that // differ in their label values. MetricVec is usually not used directly but as a // building block for implementations of vectors of a given metric // type. GaugeVec, CounterVec, SummaryVec, and UntypedVec are examples already // provided in this package. type MetricVec struct { mtx sync.RWMutex // Protects not only children, but also hash and buf. children map[uint64]Metric desc *Desc // hash is our own hash instance to avoid repeated allocations. hash hash.Hash64 // buf is used to copy string contents into it for hashing, // again to avoid allocations. buf bytes.Buffer newMetric func(labelValues ...string) Metric } // Describe implements Collector. The length of the returned slice // is always one. func (m *MetricVec) Describe(ch chan<- *Desc) { ch <- m.desc } // Collect implements Collector. func (m *MetricVec) Collect(ch chan<- Metric) { m.mtx.RLock() defer m.mtx.RUnlock() for _, metric := range m.children { ch <- metric } } // GetMetricWithLabelValues returns the Metric for the given slice of label // values (same order as the VariableLabels in Desc). If that combination of // label values is accessed for the first time, a new Metric is created. // Keeping the Metric for later use is possible (and should be considered if // performance is critical), but keep in mind that Reset, DeleteLabelValues and // Delete can be used to delete the Metric from the MetricVec. In that case, the // Metric will still exist, but it will not be exported anymore, even if a // Metric with the same label values is created later. See also the CounterVec // example. // // An error is returned if the number of label values is not the same as the // number of VariableLabels in Desc. // // Note that for more than one label value, this method is prone to mistakes // caused by an incorrect order of arguments. Consider GetMetricWith(Labels) as // an alternative to avoid that type of mistake. For higher label numbers, the // latter has a much more readable (albeit more verbose) syntax, but it comes // with a performance overhead (for creating and processing the Labels map). // See also the GaugeVec example. func (m *MetricVec) GetMetricWithLabelValues(lvs ...string) (Metric, error) { m.mtx.Lock() defer m.mtx.Unlock() h, err := m.hashLabelValues(lvs) if err != nil { return nil, err } return m.getOrCreateMetric(h, lvs...), nil } // GetMetricWith returns the Metric for the given Labels map (the label names // must match those of the VariableLabels in Desc). If that label map is // accessed for the first time, a new Metric is created. Implications of keeping // the Metric are the same as for GetMetricWithLabelValues. // // An error is returned if the number and names of the Labels are inconsistent // with those of the VariableLabels in Desc. // // This method is used for the same purpose as // GetMetricWithLabelValues(...string). See there for pros and cons of the two // methods. func (m *MetricVec) GetMetricWith(labels Labels) (Metric, error) { m.mtx.Lock() defer m.mtx.Unlock() h, err := m.hashLabels(labels) if err != nil { return nil, err } lvs := make([]string, len(labels)) for i, label := range m.desc.variableLabels { lvs[i] = labels[label] } return m.getOrCreateMetric(h, lvs...), nil } // WithLabelValues works as GetMetricWithLabelValues, but panics if an error // occurs. The method allows neat syntax like: // httpReqs.WithLabelValues("404", "POST").Inc() func (m *MetricVec) WithLabelValues(lvs ...string) Metric { metric, err := m.GetMetricWithLabelValues(lvs...) if err != nil { panic(err) } return metric } // With works as GetMetricWith, but panics if an error occurs. The method allows // neat syntax like: // httpReqs.With(Labels{"status":"404", "method":"POST"}).Inc() func (m *MetricVec) With(labels Labels) Metric { metric, err := m.GetMetricWith(labels) if err != nil { panic(err) } return metric } // DeleteLabelValues removes the metric where the variable labels are the same // as those passed in as labels (same error as the VariableLabels in Desc). It // returns true if a metric was deleted. // // It is not an error if the number of label values is not the same as the // number of VariableLabels in Desc. However, such inconsistent label count can // never match an actual Metric, so the method will always return false in that // case. // // Note that for more than one label value, this method is prone to mistakes // caused by an incorrect order of arguments. Consider Delete(Labels) as an // alternative to avoid that type of mistake. For higher label numbers, the // latter has a much more readable (albeit more verbose) syntax, but it comes // with a performance overhead (for creating and processing the Labels map). // See also the CounterVec example. func (m *MetricVec) DeleteLabelValues(lvs ...string) bool { m.mtx.Lock() defer m.mtx.Unlock() h, err := m.hashLabelValues(lvs) if err != nil { return false } if _, has := m.children[h]; !has { return false } delete(m.children, h) return true } // Delete deletes the metric where the variable labels are the same as those // passed in as labels. It returns true if a metric was deleted. // // It is not an error if the number and names of the Labels are inconsistent // with those of the VariableLabels in the Desc of the MetricVec. However, such // inconsistent Labels can never match an actual Metric, so the method will // always return false in that case. // // This method is used for the same purpose as DeleteLabelValues(...string). See // there for pros and cons of the two methods. func (m *MetricVec) Delete(labels Labels) bool { m.mtx.Lock() defer m.mtx.Unlock() h, err := m.hashLabels(labels) if err != nil { return false } if _, has := m.children[h]; !has { return false } delete(m.children, h) return true } // Reset deletes all metrics in this vector. func (m *MetricVec) Reset() { m.mtx.Lock() defer m.mtx.Unlock() for h := range m.children { delete(m.children, h) } } func (m *MetricVec) hashLabelValues(vals []string) (uint64, error) { if len(vals) != len(m.desc.variableLabels) { return 0, errInconsistentCardinality } m.hash.Reset() for _, val := range vals { m.buf.Reset() m.buf.WriteString(val) m.hash.Write(m.buf.Bytes()) } return m.hash.Sum64(), nil } func (m *MetricVec) hashLabels(labels Labels) (uint64, error) { if len(labels) != len(m.desc.variableLabels) { return 0, errInconsistentCardinality } m.hash.Reset() for _, label := range m.desc.variableLabels { val, ok := labels[label] if !ok { return 0, fmt.Errorf("label name %q missing in label map", label) } m.buf.Reset() m.buf.WriteString(val) m.hash.Write(m.buf.Bytes()) } return m.hash.Sum64(), nil } func (m *MetricVec) getOrCreateMetric(hash uint64, labelValues ...string) Metric { metric, ok := m.children[hash] if !ok { // Copy labelValues. Otherwise, they would be allocated even if we don't go // down this code path. copiedLabelValues := append(make([]string, 0, len(labelValues)), labelValues...) metric = m.newMetric(copiedLabelValues...) m.children[hash] = metric } return metric }
{ "content_hash": "44e955bfb2ed4f1a020fe87fc3c4e8c8", "timestamp": "", "source": "github", "line_count": 228, "max_line_length": 82, "avg_line_length": 31.982456140350877, "alnum_prop": 0.7165386725178278, "repo_name": "soundcloud/roshi", "id": "899aace962f9491988f67f58547c7b2e9674d095", "size": "7878", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "_vendor/src/github.com/prometheus/client_golang/prometheus/vec.go", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Go", "bytes": "198431" }, { "name": "Makefile", "bytes": "476" } ], "symlink_target": "" }
<tr class="board-swimlane-columns-first"> <?php foreach ($swimlane['columns'] as $column): ?> <th class="board-column-header board-column-header-first board-column-header-<?= $column['id'] ?>" data-column-id="<?= $column['id'] ?>"> <!-- column in collapsed mode --> <div class="board-column-collapsed"> </div> <!-- column in expanded mode --> <div class="board-column-expanded-header"> <span class="board-column-title"> </span> <span class="pull-right"> </span> </div> </th> <?php endforeach ?> </tr>
{ "content_hash": "75e6ce0a2824477d9408821b63aade8c", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 141, "avg_line_length": 30.85, "alnum_prop": 0.5380875202593193, "repo_name": "renothing/kanboard", "id": "6a2e1e8ae17ff127d14d987ad767cfd565e6a336", "size": "617", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "app/Template/board/table_column_first.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "50469" }, { "name": "Dockerfile", "bytes": "1947" }, { "name": "JavaScript", "bytes": "128122" }, { "name": "Makefile", "bytes": "2646" }, { "name": "PHP", "bytes": "8050873" }, { "name": "Shell", "bytes": "516" } ], "symlink_target": "" }
<?php // src/Acme/DemoBundle/Admin/PostAdmin.php namespace Fiscalite\GestionFiscaliteBundle\Admin; use Sonata\AdminBundle\Admin\Admin; use Sonata\AdminBundle\Datagrid\ListMapper; use Sonata\AdminBundle\Datagrid\DatagridMapper; use Sonata\AdminBundle\Form\FormMapper; class ArticleAdmin extends Admin { // Fields to be shown on create/edit forms protected function configureFormFields(FormMapper $formMapper) { $formMapper ->add('id') ->add('numerosequentiel') ->add('codeArticle') ; } // Fields to be shown on filter forms protected function configureDatagridFilters(DatagridMapper $datagridMapper) { $datagridMapper ->add('id') ->add('numerosequentiel') ->add('codeArticle') ; } // Fields to be shown on lists protected function configureListFields(ListMapper $listMapper) { $listMapper ->add('id') ->add('numerosequentiel') ->add('codeArticle') ; } }
{ "content_hash": "41af008535a2cb5dc19dc1e3df6838a8", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 79, "avg_line_length": 24.38095238095238, "alnum_prop": 0.650390625, "repo_name": "chadyred/fiscalite", "id": "86adf71da1e424403475c873a86f7796d3e12868", "size": "1024", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Fiscalite/GestionFiscaliteBundle/Admin/ArticleAdmin.php", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "355983" }, { "name": "JavaScript", "bytes": "12468384" }, { "name": "PHP", "bytes": "852394" }, { "name": "Perl", "bytes": "23" }, { "name": "Shell", "bytes": "10147238" } ], "symlink_target": "" }
static const char *kImageType = "public.png"; static const char *kPNGSoftwareValue = "AmazeKit"; @interface AKFileManager() { NSFileManager *_fileManager; NSOperationQueue *_imageIOQueue; NSCache *_renderedImageCache; } - (NSString *)cacheKeyForHash:(NSString *)hash atSize:(CGSize)size withScale:(CGFloat)scale; - (NSString *)dimensionsRepresentationWithSize:(CGSize)size scale:(CGFloat)scale; - (NSFileManager *)fileManager; - (NSOperationQueue *)imageIOQueue; - (NSString *)pathForHash:(NSString *)hash atSize:(CGSize)size withScale:(CGFloat)scale; - (NSCache *)renderedImageCache; @end @implementation AKFileManager #pragma mark - Object Lifecycle + (id)defaultManager { static id sharedInstance = nil; if (sharedInstance == nil) { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedInstance = [[self alloc] init]; }); } return sharedInstance; } + (NSString *)amazeKitCachePath { static NSString *amazeKitCachePath = nil; if (amazeKitCachePath == nil) { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ amazeKitCachePath = [[self amazeKitCacheURL] path]; }); } return amazeKitCachePath; } + (NSURL *)amazeKitCacheURL { static NSURL *amazeKitCacheURL = nil; if (amazeKitCacheURL == nil) { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ NSError *error = nil; NSURL *cachesURL = [[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:&error]; if (cachesURL != nil) { amazeKitCacheURL = [cachesURL URLByAppendingPathComponent:@"__AmazeKitCache__" isDirectory:YES]; BOOL isDirectory = NO; if ([[NSFileManager defaultManager] fileExistsAtPath:[amazeKitCacheURL absoluteString] isDirectory:&isDirectory] == NO) { NSError *directoryCreationError = nil; BOOL success = [[NSFileManager defaultManager] createDirectoryAtURL:amazeKitCacheURL withIntermediateDirectories:YES attributes:nil error:&directoryCreationError]; if (success == NO) { NSLog(@"Could not create directory at URL %@, error: %@", amazeKitCacheURL, directoryCreationError); } } } else { NSLog(@"Error finding caches URL: %@", error); } }); } return amazeKitCacheURL; } #pragma mark - - (BOOL)cachedImageExistsForHash:(NSString *)descriptionHash atSize:(CGSize)size withScale:(CGFloat)scale { __block BOOL imageExists = NO; NSString *cacheKey = [self cacheKeyForHash:descriptionHash atSize:size withScale:scale]; imageExists = ([[self renderedImageCache] objectForKey:cacheKey] != nil); if (imageExists == NO) { NSString *path = [self pathForHash:descriptionHash atSize:size withScale:scale]; NSBlockOperation *imageExistsOperation = [NSBlockOperation blockOperationWithBlock:^{ imageExists = [[self fileManager] fileExistsAtPath:path]; }]; [[self imageIOQueue] addOperation:imageExistsOperation]; [imageExistsOperation waitUntilFinished]; } return imageExists; } - (UIImage *)cachedImageForHash:(NSString *)descriptionHash atSize:(CGSize)size withScale:(CGFloat)scale { __block UIImage *cachedImage = nil; if ([self cachedImageExistsForHash:descriptionHash atSize:size withScale:scale] == YES) { NSString *cacheKey = [self cacheKeyForHash:descriptionHash atSize:size withScale:scale]; cachedImage = [[self renderedImageCache] objectForKey:cacheKey]; if (cachedImage == nil) { NSBlockOperation *imageLoadOperation = [NSBlockOperation blockOperationWithBlock:^{ NSString *path = [self pathForHash:descriptionHash atSize:size withScale:scale]; NSURL *url = [NSURL fileURLWithPath:path]; CFStringRef myKeys[2]; CFTypeRef myValues[2]; myKeys[0] = kCGImageSourceShouldCache; myValues[0] = (CFTypeRef)kCFBooleanTrue; myKeys[1] = kCGImageSourceShouldAllowFloat; myValues[1] = (CFTypeRef)kCFBooleanTrue; CFDictionaryRef options = CFDictionaryCreate(kCFAllocatorDefault, (const void **) myKeys, (const void **) myValues, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CGImageSourceRef imageSource = CGImageSourceCreateWithURL((__bridge CFURLRef)url, options); CFRelease(options); if (imageSource != NULL) { // Create an image from the first item in the image source. CGImageRef baseImage = CGImageSourceCreateImageAtIndex(imageSource, 0, NULL); if (baseImage != NULL) { cachedImage = [[UIImage alloc] initWithCGImage:baseImage scale:scale orientation:UIImageOrientationUp]; CGImageRelease(baseImage); } CFRelease(imageSource); } }]; [[self imageIOQueue] addOperation:imageLoadOperation]; [imageLoadOperation waitUntilFinished]; if (cachedImage != nil) { [[self renderedImageCache] setObject:cachedImage forKey:[self cacheKeyForHash:descriptionHash atSize:size withScale:scale]]; } } } return cachedImage; } - (void)cacheImage:(UIImage *)image forHash:(NSString *)descriptionHash { CGSize imageSize = [image size]; CGFloat imageScale = [image scale]; NSString *path = [self pathForHash:descriptionHash atSize:imageSize withScale:imageScale]; NSURL *url = [NSURL fileURLWithPath:path]; static CFStringRef type = NULL; if (type == NULL) { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ type = CFStringCreateWithCString(kCFAllocatorDefault, kImageType, kCFStringEncodingASCII); }); } static CFDictionaryRef imageOptions = NULL; if (imageOptions == NULL) { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ CFStringRef values[1]; CFStringRef keys[1]; CFStringRef softwareValue = CFStringCreateWithCString(kCFAllocatorDefault, kPNGSoftwareValue, kCFStringEncodingASCII); keys[0] = kCGImagePropertyPNGSoftware; values[0] = softwareValue; imageOptions = CFDictionaryCreate(kCFAllocatorDefault, (const void **)keys, (const void **)values, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFRelease(softwareValue); }); } NSBlockOperation *imageWritingOperation = [NSBlockOperation blockOperationWithBlock:^{ CGImageDestinationRef destination = CGImageDestinationCreateWithURL((__bridge CFURLRef)url, type, 1, NULL); CGImageDestinationAddImage(destination, [image CGImage], imageOptions); __block bool success = false; success = CGImageDestinationFinalize(destination); CFRelease(destination); if (success == false) { NSLog(@"Could not cache image with size %@ and scale %.0f to path: %@", NSStringFromCGSize(imageSize), imageScale, path); } }]; // We want writing operations to have a higher priority to minimize the chance that multiple // threads would try to render the same image. [imageWritingOperation setQueuePriority:NSOperationQueuePriorityHigh]; [[self imageIOQueue] addOperation:imageWritingOperation]; [[self renderedImageCache] setObject:image forKey:[self cacheKeyForHash:descriptionHash atSize:imageSize withScale:imageScale]]; } - (NSString *)cacheKeyForHash:(NSString *)hash atSize:(CGSize)size withScale:(CGFloat)scale { return [NSString stringWithFormat:@"%@%@", hash, [self dimensionsRepresentationWithSize:size scale:scale]]; } - (NSString *)dimensionsRepresentationWithSize:(CGSize)size scale:(CGFloat)scale { NSString *dimensionsRepresentation = [NSString stringWithFormat:@"{%dx%dx%d}", (int)size.width, (int)size.height, (int)scale]; return dimensionsRepresentation; } - (NSFileManager *)fileManager { if (_fileManager == nil) { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _fileManager = [[NSFileManager alloc] init]; }); } return _fileManager; } - (NSOperationQueue *)imageIOQueue { if (_imageIOQueue == nil) { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _imageIOQueue = [[NSOperationQueue alloc] init]; [_imageIOQueue setName:@"AmazeKit Image I/O Queue"]; }); } return _imageIOQueue; } - (NSString *)pathForHash:(NSString *)hash atSize:(CGSize)size withScale:(CGFloat)scale { NSString *cachePath = [[self class] amazeKitCachePath]; NSString *baseHashPath = [[cachePath stringByAppendingPathComponent:@"__RenderedImageCache__"] stringByAppendingPathComponent:hash]; __block BOOL isDirectory; __block BOOL directoryExists = NO; NSBlockOperation *directoryExistsOperation = [NSBlockOperation blockOperationWithBlock:^{ directoryExists = [[self fileManager] fileExistsAtPath:baseHashPath isDirectory:&isDirectory]; }]; [[self imageIOQueue] addOperation:directoryExistsOperation]; [directoryExistsOperation waitUntilFinished]; if (directoryExists == YES && isDirectory == NO) { __block BOOL success = NO; NSBlockOperation *removeItemOperation = [NSBlockOperation blockOperationWithBlock:^{ success = [[self fileManager] removeItemAtPath:baseHashPath error:NULL]; }]; [[self imageIOQueue] addOperation:removeItemOperation]; [removeItemOperation waitUntilFinished]; if (success == YES) { directoryExists = NO; } } if (directoryExists == NO) { NSBlockOperation *createDirectoryOperation = [NSBlockOperation blockOperationWithBlock:^{ [[self fileManager] createDirectoryAtPath:baseHashPath withIntermediateDirectories:YES attributes:nil error:NULL]; }]; [[self imageIOQueue] addOperation:createDirectoryOperation]; [createDirectoryOperation waitUntilFinished]; } NSString *dimensionsRepresentation = [self dimensionsRepresentationWithSize:size scale:scale]; NSString *imagePath = [[baseHashPath stringByAppendingPathComponent:dimensionsRepresentation] stringByAppendingPathExtension:@"png"]; return imagePath; } - (NSCache *)renderedImageCache { if (_renderedImageCache == nil) { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _renderedImageCache = [[NSCache alloc] init]; [_renderedImageCache setName:@"AmazeKit Rendered Image Cache"]; }); } return _renderedImageCache; } #pragma mark - @end
{ "content_hash": "000b11c9856c9c0b98e735016bcff3a5", "timestamp": "", "source": "github", "line_count": 399, "max_line_length": 133, "avg_line_length": 27.531328320802004, "alnum_prop": 0.6752844788347747, "repo_name": "detroit-labs/AmazeKit", "id": "5fc2853fef3791dc0c0deda0e6cfb0a15f73c49f", "size": "11794", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AmazeKit/AmazeKit/AKFileManager.m", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Objective-C", "bytes": "158416" }, { "name": "Ruby", "bytes": "599" }, { "name": "Shell", "bytes": "1234" } ], "symlink_target": "" }
from helper_bot.settings import ErrorReply async def set_alert(chat, **kwargs): redis = kwargs.get('redis') info = kwargs.get('info') msg = chat.message['text'].split(' ') if len(msg) != 3: return await chat.reply(ErrorReply.INCORRECT_SYNTAX.format('/setalert nomeoggetto prezzomassimo')) item = await redis.hget('items', msg[1].capitalize()) if item: item_id, value = item.split(',') else: return await chat.reply(f"Errore!\nNon ho trovato un oggetto chiamato: {msg[1]}") try: max_ = int(msg[2]) except ValueError: return await chat.reply('Errore!\nIl prezzo massimo non è un numero') if max_ < int(value): return await chat.reply(f"Errore!\nIl prezzo massimo è minore del prezzo base dell'oggetto: {value}") new_alert = f'{item_id},{msg[2]},{msg[1]}' if await redis.hexists('alert', info.get('username')): other_alerts = await redis.hget('alert', info.get('username')) if msg[1] not in other_alerts: alerts = other_alerts + ':' + new_alert else: alerts = other_alerts.split(':') for i, alert in enumerate(alerts): if msg[1] in alert: alerts[i] = new_alert alerts = ":".join(alerts) await redis.hset('alert', info.get('username'), alerts) else: await redis.hset('alert', info.get('username'), new_alert) await chat.reply(f'Successo!Hai messo un alert su {msg[1]} al prezzo massimo di {msg[2]}') async def show_alerts(chat, **kwargs): redis = kwargs.get('redis') info = kwargs.get('info') alerts = await redis.hget('alert', info.get('username')) if not alerts: return await chat.reply('Non hai alerts settate --> /setalert') msg = 'Le tue alert sono:\n' for alert in alerts.split(':'): _, max_, name = alert.split(',') msg += f'{name}-->{max_}\n' await chat.reply(msg) async def unset_alert(chat, **kwargs): redis = kwargs.get('redis') info = kwargs.get('info') msg = chat.message['text'].split(' ') if len(msg) != 2: return await chat.reply(ErrorReply.INCORRECT_SYNTAX.format('/unsetalert nomeoggetto')) alerts = await redis.hget('alert', info.get('username')) other_alerts = alerts.split(':') if not other_alerts: return await chat.reply('Non hai alerts settate --> /setalert') found = False for i, alert in enumerate(other_alerts): if msg[1] in alert: other_alerts.pop(i) found = True if found: await redis.hset('alert', info.get('username'), ':'.join(other_alerts)) return await chat.reply(f'{msg[1]} rimosso dalle tue alerts!') await chat.reply(f'{msg[1]} non presente nelle tur alerts!')
{ "content_hash": "e24a644879387f848c9217f27bd2a75a", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 109, "avg_line_length": 39.28169014084507, "alnum_prop": 0.6030835424883471, "repo_name": "akita8/helper_bot", "id": "a4a539956c57ce34eb9a820877afc6cd7a5dd040", "size": "2791", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "helper_bot/commands/alerts.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "44590" } ], "symlink_target": "" }
<?xml version="1.0" standalone="no"?> <NetConnectResponse> <CompletionCode>4000</CompletionCode> <ErrorMessage>System error. Call Experian Technical Support at 1-800-854-7201.</ErrorMessage> <ReferenceId>userabc001</ReferenceId> </NetConnectResponse>
{ "content_hash": "e81aa2acb69096e6f5de37a265235437", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 95, "avg_line_length": 42.833333333333336, "alnum_prop": 0.7782101167315175, "repo_name": "sittercity/experian", "id": "01711c24105e9124f8eee6afff6d04bb6f59c3e2", "size": "257", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/fixtures/errors/system-error.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "35001" } ], "symlink_target": "" }
#ifndef _PVRTGLES2EXT_H_ #define _PVRTGLES2EXT_H_ #include "CC3PVROpenGLFoundation.h" // patched for Cocos3D by Bill Hollings #if CC3_OGLES_2 // patched for Cocos3D by Bill Hollings #ifdef __APPLE__ #if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE==1 #import <OpenGLES/ES2/gl.h> #import <OpenGLES/ES2/glext.h> // No binary shaders are allowed on the iphone and so this value is not defined // Defining here allows for a more graceful fail of binary shader loading at runtime // which can be recovered from instead of fail at compile time // #define GL_SGX_BINARY_IMG 0 // patched for Cocos3D by Bill Hollings #else #include <EGL/egl.h> #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> #include <GLES2/gl2extimg.h> #endif #else #if !defined(EGL_NOT_PRESENT) #include <EGL/egl.h> #endif #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> #include <GLES2/gl2extimg.h> #endif #if defined(TARGET_OS_IPHONE) // the extensions supported on the iPhone are treated as core functions of gl // so use this macro to assign the function pointers in this class appropriately. #define PVRGetProcAddress(x) ::x #else #if defined(EGL_NOT_PRESENT) #if defined(__PALMPDK__) #include "SDL.h" #define PVRGetProcAddress(x) SDL_GLES_GetProcAddress(#x) #else #define PVRGetProcAddress(x) NULL #endif #else #define PVRGetProcAddress(x) eglGetProcAddress(#x) #endif #endif /**************************************************************************** ** Build options ****************************************************************************/ #define GL_PVRTGLESEXT_VERSION 2 /************************************************************************** ****************************** GL EXTENSIONS ****************************** **************************************************************************/ /*!************************************************************************ @class CPVRTgles2Ext @brief A class for initialising and managing OGLES2 extensions **************************************************************************/ class CPVRTgles2Ext { public: // Type definitions for pointers to functions returned by eglGetProcAddress typedef void (GL_APIENTRY *PFNGLMULTIDRAWELEMENTS) (GLenum mode, GLsizei *count, GLenum type, const GLvoid **indices, GLsizei primcount); // glvoid typedef void* (GL_APIENTRY *PFNGLMAPBUFFEROES)(GLenum target, GLenum access); typedef GLboolean (GL_APIENTRY *PFNGLUNMAPBUFFEROES)(GLenum target); typedef void (GL_APIENTRY *PFNGLGETBUFFERPOINTERVOES)(GLenum target, GLenum pname, void** params); typedef void (GL_APIENTRY * PFNGLMULTIDRAWARRAYS) (GLenum mode, GLint *first, GLsizei *count, GLsizei primcount); // glvoid typedef void (GL_APIENTRY * PFNGLDISCARDFRAMEBUFFEREXT)(GLenum target, GLsizei numAttachments, const GLenum *attachments); typedef void (GL_APIENTRY *PFNGLGENQUERIESEXT) (GLsizei n, GLuint *ids); typedef void (GL_APIENTRY *PFNGLDELETEQUERIESEXT) (GLsizei n, const GLuint *ids); typedef GLboolean (GL_APIENTRY *PFNGLISQUERYEXT) (GLuint id); typedef void (GL_APIENTRY *PFNGLBEGINQUERYEXT) (GLenum target, GLuint id); typedef void (GL_APIENTRY *PFNGLENDQUERYEXT) (GLenum target); typedef void (GL_APIENTRY *PFNGLGETQUERYIVEXT) (GLenum target, GLenum pname, GLint *params); typedef void (GL_APIENTRY *PFNGLGETQUERYOBJECTUIVEXT) (GLuint id, GLenum pname, GLuint *params); typedef void (GL_APIENTRYP PFNGLBINDVERTEXARRAYOES) (GLuint vertexarray); typedef void (GL_APIENTRYP PFNGLDELETEVERTEXARRAYSOES) (GLsizei n, const GLuint *vertexarrays); typedef void (GL_APIENTRYP PFNGLGENVERTEXARRAYSOES) (GLsizei n, GLuint *vertexarrays); typedef GLboolean (GL_APIENTRYP PFNGLISVERTEXARRAYOES) (GLuint vertexarray); typedef void (GL_APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEIMG) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DMULTISAMPLEIMG) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLsizei samples); typedef void (GL_APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEEXT) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DMULTISAMPLEEXT) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLsizei samples); typedef void (GL_APIENTRYP PFNGLDRAWBUFFERSEXT) (GLsizei n, const GLenum *bufs); // GL_EXT_multi_draw_arrays PFNGLMULTIDRAWELEMENTS glMultiDrawElementsEXT; PFNGLMULTIDRAWARRAYS glMultiDrawArraysEXT; // GL_EXT_multi_draw_arrays PFNGLMAPBUFFEROES glMapBufferOES; PFNGLUNMAPBUFFEROES glUnmapBufferOES; PFNGLGETBUFFERPOINTERVOES glGetBufferPointervOES; // GL_EXT_discard_framebuffer PFNGLDISCARDFRAMEBUFFEREXT glDiscardFramebufferEXT; // GL_EXT_occlusion_query_boolean #if !defined(GL_EXT_occlusion_query_boolean) #define GL_ANY_SAMPLES_PASSED_EXT 0x8C2F #define GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT 0x8D6A #define GL_CURRENT_QUERY_EXT 0x8865 #define GL_QUERY_RESULT_EXT 0x8866 #define GL_QUERY_RESULT_AVAILABLE_EXT 0x886 #endif PFNGLGENQUERIESEXT glGenQueriesEXT; PFNGLDELETEQUERIESEXT glDeleteQueriesEXT; PFNGLISQUERYEXT glIsQueryEXT; PFNGLBEGINQUERYEXT glBeginQueryEXT; PFNGLENDQUERYEXT glEndQueryEXT; PFNGLGETQUERYIVEXT glGetQueryivEXT; PFNGLGETQUERYOBJECTUIVEXT glGetQueryObjectuivEXT; // GL_OES_vertex_array_object #if !defined(GL_OES_vertex_array_object) #define GL_VERTEX_ARRAY_BINDING_OES 0x85B5 #endif PFNGLBINDVERTEXARRAYOES glBindVertexArrayOES; PFNGLDELETEVERTEXARRAYSOES glDeleteVertexArraysOES; PFNGLGENVERTEXARRAYSOES glGenVertexArraysOES; PFNGLISVERTEXARRAYOES glIsVertexArrayOES; // GL_IMG_multisampled_render_to_texture #if !defined(GL_IMG_multisampled_render_to_texture) #define GL_RENDERBUFFER_SAMPLES_IMG 0x9133 #define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_IMG 0x9134 #define GL_MAX_SAMPLES_IMG 0x9135 #define GL_TEXTURE_SAMPLES_IMG 0x9136 #endif PFNGLRENDERBUFFERSTORAGEMULTISAMPLEIMG glRenderbufferStorageMultisampleIMG; PFNGLFRAMEBUFFERTEXTURE2DMULTISAMPLEIMG glFramebufferTexture2DMultisampleIMG; // GL_EXT_multisampled_render_to_texture #if !defined(GL_EXT_multisampled_render_to_texture) #define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_SAMPLES_EXT 0x8D6C #define GL_RENDERBUFFER_SAMPLES_EXT 0x8CAB #define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_EXT 0x8D56 #define GL_MAX_SAMPLES_EXT 0x8D57 #endif PFNGLRENDERBUFFERSTORAGEMULTISAMPLEEXT glRenderbufferStorageMultisampleEXT; PFNGLFRAMEBUFFERTEXTURE2DMULTISAMPLEEXT glFramebufferTexture2DMultisampleEXT; // GL_EXT_draw_buffers #if !defined(GL_EXT_draw_buffers) #define GL_MAX_COLOR_ATTACHMENTS_EXT 0x8CDF #define GL_MAX_DRAW_BUFFERS_EXT 0x8824 #define GL_DRAW_BUFFER0_EXT 0x8825 #define GL_DRAW_BUFFER1_EXT 0x8826 #define GL_DRAW_BUFFER2_EXT 0x8827 #define GL_DRAW_BUFFER3_EXT 0x8828 #define GL_DRAW_BUFFER4_EXT 0x8829 #define GL_DRAW_BUFFER5_EXT 0x882A #define GL_DRAW_BUFFER6_EXT 0x882B #define GL_DRAW_BUFFER7_EXT 0x882C #define GL_DRAW_BUFFER8_EXT 0x882D #define GL_DRAW_BUFFER9_EXT 0x882E #define GL_DRAW_BUFFER10_EXT 0x882F #define GL_DRAW_BUFFER11_EXT 0x8830 #define GL_DRAW_BUFFER12_EXT 0x8831 #define GL_DRAW_BUFFER13_EXT 0x8832 #define GL_DRAW_BUFFER14_EXT 0x8833 #define GL_DRAW_BUFFER15_EXT 0x8834 #define GL_COLOR_ATTACHMENT0_EXT 0x8CE0 #define GL_COLOR_ATTACHMENT1_EXT 0x8CE1 #define GL_COLOR_ATTACHMENT2_EXT 0x8CE2 #define GL_COLOR_ATTACHMENT3_EXT 0x8CE3 #define GL_COLOR_ATTACHMENT4_EXT 0x8CE4 #define GL_COLOR_ATTACHMENT5_EXT 0x8CE5 #define GL_COLOR_ATTACHMENT6_EXT 0x8CE6 #define GL_COLOR_ATTACHMENT7_EXT 0x8CE7 #define GL_COLOR_ATTACHMENT8_EXT 0x8CE8 #define GL_COLOR_ATTACHMENT9_EXT 0x8CE9 #define GL_COLOR_ATTACHMENT10_EXT 0x8CEA #define GL_COLOR_ATTACHMENT11_EXT 0x8CEB #define GL_COLOR_ATTACHMENT12_EXT 0x8CEC #define GL_COLOR_ATTACHMENT13_EXT 0x8CED #define GL_COLOR_ATTACHMENT14_EXT 0x8CEE #define GL_COLOR_ATTACHMENT15_EXT 0x8CEF #endif PFNGLDRAWBUFFERSEXT glDrawBuffersEXT; public: /*!*********************************************************************** @brief Initialises IMG extensions *************************************************************************/ void LoadExtensions(); /*!*********************************************************************** @brief Queries for support of an extension @param[in] extension extension to query for @return True if the extension is supported *************************************************************************/ static bool IsGLExtensionSupported(const char* extension); // patched for Cocos3D by Bill Hollings }; /*! @} */ #endif /* _PVRTGLES2EXT_H_ */ /***************************************************************************** End of file (PVRTgles2Ext.h) *****************************************************************************/ #endif // CC3_OGLES_2 // patched for Cocos3D by Bill Hollings
{ "content_hash": "b8e75f741144597c12c62ebb3fc2b247", "timestamp": "", "source": "github", "line_count": 225, "max_line_length": 168, "avg_line_length": 46.888888888888886, "alnum_prop": 0.5992417061611375, "repo_name": "cocos3d/cocos3d", "id": "ea93d2b44e2071ffc8e60d696f52f7943de7ab5b", "size": "10877", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cocos3d/cc3PVR/PVRT/OGLES2/PVRTgles2Ext.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "704192" }, { "name": "C++", "bytes": "643553" }, { "name": "CSS", "bytes": "361" }, { "name": "Matlab", "bytes": "14669" }, { "name": "Objective-C", "bytes": "4861617" }, { "name": "Objective-C++", "bytes": "117329" }, { "name": "Perl", "bytes": "2207" }, { "name": "Python", "bytes": "8959" }, { "name": "Shell", "bytes": "22023" } ], "symlink_target": "" }
USE [msdb] GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[MaintenanceConfig]( [ConfigurationType] [varchar](50) NOT NULL, [ConfigurationSettings] [xml] NULL, CONSTRAINT [pk_MaintenanceConfig_ConfigurationType] PRIMARY KEY CLUSTERED ( [ConfigurationType] ASC) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)) GO
{ "content_hash": "10f5231d79a30f85b37508e4f6971371", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 122, "avg_line_length": 26, "alnum_prop": 0.75, "repo_name": "empiricaldataman/DB2LS", "id": "23c325f9c613a2f39b9f1a6e070de0483aadd234", "size": "416", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SQL/IndexMaintenance/CT_MaintenanceConfig.sql", "mode": "33188", "license": "mit", "language": [ { "name": "PLSQL", "bytes": "21058" }, { "name": "PLpgSQL", "bytes": "217839" }, { "name": "PowerShell", "bytes": "78993" }, { "name": "TSQL", "bytes": "451254" } ], "symlink_target": "" }
package dk.nversion.copybook.annotations; import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) @Repeatable(CopyBookLines.class) public @interface CopyBookLine { String value(); }
{ "content_hash": "fd2c199bf73f70b49d5b4353d0931d56", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 41, "avg_line_length": 17.615384615384617, "alnum_prop": 0.7816593886462883, "repo_name": "tlbdk/copybook4java", "id": "b72403451961d22fd19cbd2df11f469896e0533c", "size": "345", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "copybook4java/src/main/java/dk/nversion/copybook/annotations/CopyBookLine.java", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "17453" }, { "name": "Java", "bytes": "294668" }, { "name": "Shell", "bytes": "211" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <artifactId>drools-assemblies</artifactId> <groupId>org.pentaho.di.plugins</groupId> <version>8.3.0.0-SNAPSHOT</version> </parent> <artifactId>kettle-drools5-plugin</artifactId> <packaging>pom</packaging> <name>PDI Drools Plugin Distribution</name> <properties> <resources.directory>${project.basedir}/src/main/resources</resources.directory> </properties> <dependencies> <dependency> <groupId>org.pentaho.di.plugins</groupId> <artifactId>kettle-drools5-core</artifactId> <version>${project.version}</version> </dependency> </dependencies> </project>
{ "content_hash": "c3b828b24b5f0bbdb74d1447d1929f1e", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 108, "avg_line_length": 31.862068965517242, "alnum_prop": 0.6904761904761905, "repo_name": "lgrill-pentaho/pentaho-kettle", "id": "046a75f8f24bc5f64cf22bbc57d707935b0b4d02", "size": "924", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "plugins/drools/assemblies/plugin/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "41477" }, { "name": "CSS", "bytes": "50137" }, { "name": "GAP", "bytes": "4005" }, { "name": "HTML", "bytes": "57257" }, { "name": "Java", "bytes": "42923919" }, { "name": "JavaScript", "bytes": "366761" }, { "name": "Shell", "bytes": "45854" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_26) on Mon Nov 21 10:31:10 CST 2011 --> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE> 类 com.teleca.jamendo.activity.BrowsePlaylistActivity.RemotePlaylistTask 的使用 </TITLE> <META NAME="date" CONTENT="2011-11-21"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="类 com.teleca.jamendo.activity.BrowsePlaylistActivity.RemotePlaylistTask 的使用"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="跳过导航链接"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>概述</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>软件包</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../com/teleca/jamendo/activity/BrowsePlaylistActivity.RemotePlaylistTask.html" title="com.teleca.jamendo.activity 中的类"><FONT CLASS="NavBarFont1"><B>类</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>使用</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>树</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>已过时</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>索引</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>帮助</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;上一个&nbsp; &nbsp;下一个</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?com/teleca/jamendo/activity/\class-useBrowsePlaylistActivity.RemotePlaylistTask.html" target="_top"><B>框架</B></A> &nbsp; &nbsp;<A HREF="BrowsePlaylistActivity.RemotePlaylistTask.html" target="_top"><B>无框架</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>所有类</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>所有类</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>类 com.teleca.jamendo.activity.BrowsePlaylistActivity.RemotePlaylistTask<br>的使用</B></H2> </CENTER> 没有 com.teleca.jamendo.activity.BrowsePlaylistActivity.RemotePlaylistTask 的用法 <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="跳过导航链接"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>概述</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>软件包</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../com/teleca/jamendo/activity/BrowsePlaylistActivity.RemotePlaylistTask.html" title="com.teleca.jamendo.activity 中的类"><FONT CLASS="NavBarFont1"><B>类</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>使用</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>树</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>已过时</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>索引</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>帮助</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;上一个&nbsp; &nbsp;下一个</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?com/teleca/jamendo/activity/\class-useBrowsePlaylistActivity.RemotePlaylistTask.html" target="_top"><B>框架</B></A> &nbsp; &nbsp;<A HREF="BrowsePlaylistActivity.RemotePlaylistTask.html" target="_top"><B>无框架</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>所有类</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>所有类</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
{ "content_hash": "6c0d4c8122dc92fe3e50ed8ebe756b60", "timestamp": "", "source": "github", "line_count": 145, "max_line_length": 244, "avg_line_length": 43.186206896551724, "alnum_prop": 0.6106675183647396, "repo_name": "LiTingchang/jamendo", "id": "158319bcc9ca63b871854775237682e7e90e4323", "size": "6464", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "doc/com/teleca/jamendo/activity/class-use/BrowsePlaylistActivity.RemotePlaylistTask.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1399" }, { "name": "Java", "bytes": "382923" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_45) on Fri Mar 06 22:13:00 CST 2015 --> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE> org.apache.hadoop.hdfs.server.journalservice Class Hierarchy (Apache Hadoop HDFS 2.3.0 API) </TITLE> <META NAME="date" CONTENT="2015-03-06"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="org.apache.hadoop.hdfs.server.journalservice Class Hierarchy (Apache Hadoop HDFS 2.3.0 API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../../org/apache/hadoop/hdfs/server/datanode/web/resources/package-tree.html"><B>PREV</B></A>&nbsp; &nbsp;<A HREF="../../../../../../org/apache/hadoop/hdfs/server/namenode/package-tree.html"><B>NEXT</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/apache/hadoop/hdfs/server/journalservice/package-tree.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> Hierarchy For Package org.apache.hadoop.hdfs.server.journalservice </H2> </CENTER> <DL> <DT><B>Package Hierarchies:</B><DD><A HREF="../../../../../../overview-tree.html">All Packages</A></DL> <HR> <H2> Class Hierarchy </H2> <UL> <LI TYPE="circle">java.lang.<A HREF="http://download.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><B>Object</B></A><UL> <LI TYPE="circle">javax.servlet.GenericServlet (implements java.io.<A HREF="http://download.oracle.com/javase/6/docs/api/java/io/Serializable.html?is-external=true" title="class or interface in java.io">Serializable</A>, javax.servlet.Servlet, javax.servlet.ServletConfig) <UL> <LI TYPE="circle">javax.servlet.http.HttpServlet (implements java.io.<A HREF="http://download.oracle.com/javase/6/docs/api/java/io/Serializable.html?is-external=true" title="class or interface in java.io">Serializable</A>) <UL> <LI TYPE="circle">org.apache.jasper.runtime.HttpJspBase (implements javax.servlet.jsp.HttpJspPage) <UL> <LI TYPE="circle">org.apache.hadoop.hdfs.server.journalservice.<A HREF="../../../../../../org/apache/hadoop/hdfs/server/journalservice/journalstatus_jsp.html" title="class in org.apache.hadoop.hdfs.server.journalservice"><B>journalstatus_jsp</B></A> (implements org.apache.jasper.runtime.JspSourceDependent) </UL> </UL> </UL> </UL> </UL> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../../org/apache/hadoop/hdfs/server/datanode/web/resources/package-tree.html"><B>PREV</B></A>&nbsp; &nbsp;<A HREF="../../../../../../org/apache/hadoop/hdfs/server/namenode/package-tree.html"><B>NEXT</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/apache/hadoop/hdfs/server/journalservice/package-tree.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright &#169; 2015 <a href="http://www.apache.org">Apache Software Foundation</a>. All Rights Reserved. </BODY> </HTML>
{ "content_hash": "469b6d8077db2e719a86b3e7594e96e0", "timestamp": "", "source": "github", "line_count": 164, "max_line_length": 307, "avg_line_length": 45.8719512195122, "alnum_prop": 0.6347201914130002, "repo_name": "jsrudani/HadoopHDFSProject", "id": "3d45d02c8050bc9a3af74bd3f29e4379f4469d46", "size": "7523", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "hadoop-hdfs-project/hadoop-hdfs/target/org/apache/hadoop/hdfs/server/journalservice/package-tree.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AspectJ", "bytes": "31146" }, { "name": "C", "bytes": "1198902" }, { "name": "C++", "bytes": "164551" }, { "name": "CMake", "bytes": "131069" }, { "name": "CSS", "bytes": "131494" }, { "name": "Erlang", "bytes": "464" }, { "name": "HTML", "bytes": "485534855" }, { "name": "Java", "bytes": "37974886" }, { "name": "JavaScript", "bytes": "80446" }, { "name": "Makefile", "bytes": "104088" }, { "name": "Perl", "bytes": "18992" }, { "name": "Protocol Buffer", "bytes": "159216" }, { "name": "Python", "bytes": "11309" }, { "name": "Shell", "bytes": "724779" }, { "name": "TeX", "bytes": "19322" }, { "name": "XSLT", "bytes": "91404" } ], "symlink_target": "" }
package org.springframework.remoting.jaxws; import javax.annotation.Resource; import javax.jws.WebService; import javax.xml.ws.WebServiceContext; import org.springframework.util.Assert; /** * @author Juergen Hoeller */ @WebService(serviceName="OrderService", portName="OrderService", endpointInterface = "org.springframework.remoting.jaxws.OrderService") public class OrderServiceImpl implements OrderService { @Resource private WebServiceContext webServiceContext; @Override public String getOrder(int id) throws OrderNotFoundException { Assert.notNull(this.webServiceContext, "WebServiceContext has not been injected"); if (id == 0) { throw new OrderNotFoundException("Order 0 not found"); } return "order " + id; } }
{ "content_hash": "4018dfce0e09c0a514018cb35dffbb3f", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 135, "avg_line_length": 25.724137931034484, "alnum_prop": 0.7788203753351206, "repo_name": "shivpun/spring-framework", "id": "b109cdcd6da467128c0cd09f85a70db62ee705c1", "size": "1366", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "spring-web/src/test/java/org/springframework/remoting/jaxws/OrderServiceImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "GAP", "bytes": "6137" }, { "name": "Groovy", "bytes": "3685" }, { "name": "HTML", "bytes": "713" }, { "name": "Java", "bytes": "9777605" } ], "symlink_target": "" }
/* * Do not modify this file. This file is generated from the codepipeline-2015-07-09.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.CodePipeline.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.CodePipeline.Model.Internal.MarshallTransformations { /// <summary> /// ActionRevision Marshaller /// </summary> public class ActionRevisionMarshaller : IRequestMarshaller<ActionRevision, JsonMarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="requestObject"></param> /// <param name="context"></param> /// <returns></returns> public void Marshall(ActionRevision requestObject, JsonMarshallerContext context) { if(requestObject.IsSetCreated()) { context.Writer.WritePropertyName("created"); context.Writer.Write(requestObject.Created); } if(requestObject.IsSetRevisionChangeId()) { context.Writer.WritePropertyName("revisionChangeId"); context.Writer.Write(requestObject.RevisionChangeId); } if(requestObject.IsSetRevisionId()) { context.Writer.WritePropertyName("revisionId"); context.Writer.Write(requestObject.RevisionId); } } /// <summary> /// Singleton Marshaller. /// </summary> public readonly static ActionRevisionMarshaller Instance = new ActionRevisionMarshaller(); } }
{ "content_hash": "a739395d67cdb269f8395eb384a02ece", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 110, "avg_line_length": 30.983606557377048, "alnum_prop": 0.6433862433862434, "repo_name": "mwilliamson-firefly/aws-sdk-net", "id": "ec289e14b6342efd58f2200c7aa2a3601a28f405", "size": "2477", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "sdk/src/Services/CodePipeline/Generated/Model/Internal/MarshallTransformations/ActionRevisionMarshaller.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "73553647" }, { "name": "CSS", "bytes": "18119" }, { "name": "HTML", "bytes": "24362" }, { "name": "JavaScript", "bytes": "6576" }, { "name": "PowerShell", "bytes": "12587" }, { "name": "XSLT", "bytes": "7010" } ], "symlink_target": "" }
import os import win32com.client xl = win32com.client.Dispatch('Excel.Application') wb = xl.Workbooks.Open(os.path.realpath('book3.xlsx')) ws = wb.Worksheets(1) ws.Cells(6,5).Value = "XXX" ws.Cells(6,6).Formula = "=E1" wb.SaveAs(os.path.realpath('book4.xlsx')) wb.Close(True)
{ "content_hash": "c913e36c334181cfc0e984d3a01714b8", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 54, "avg_line_length": 23.25, "alnum_prop": 0.7168458781362007, "repo_name": "frederick623/HTI", "id": "d2e2502937719e35fa5dda0fe4cfe535dceea664", "size": "279", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "option_exercise/excel_trial.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "420" }, { "name": "CSS", "bytes": "5828" }, { "name": "HTML", "bytes": "9823483" }, { "name": "JavaScript", "bytes": "3758" }, { "name": "Python", "bytes": "1831337" }, { "name": "Shell", "bytes": "2154" }, { "name": "Visual Basic", "bytes": "873872" } ], "symlink_target": "" }
package bluebot.commands.fun; import bluebot.utils.Command; import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import java.util.Random; /** * @file CyanideHapinessCommand.java * @author Blue * @version 0.2 * @brief Posts a Cyanide & Hapiness comic */ public class CyanideHapinessCommand implements Command { private final String HELP = "The command `c&h` posts a Cyanide & Hapiness comic from explosm.net. \n\nUsage : `!c&h latest` - posts the latest comic, `!c&h random` - posts a random comic"; @Override public boolean called(String[] args, MessageReceivedEvent event) { if(args.length == 0 || args[0].equals("help")) {return false;} else return true; } @Override public void action(String[] args, MessageReceivedEvent event) { if(args[0].equals("latest")) { event.getTextChannel().sendMessage("http://explosm.net/comics/latest").queue(); } else if(args[0].equals("random")) { Random r = new Random(); int result = r.nextInt(3500) + 1000; event.getTextChannel().sendMessage("http://explosm.net/comics/" + result).queue(); } else { event.getTextChannel().sendMessage(help()).queue(); } } @Override public String help() { return HELP; } @Override public void executed(boolean success, MessageReceivedEvent event) { if(!success) { event.getTextChannel().sendMessage(help()).queue(); } } }
{ "content_hash": "b1bb27dd6156d56dae541c58c7e2e4d0", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 192, "avg_line_length": 31, "alnum_prop": 0.6300197498354181, "repo_name": "thibautbessone/DiscordBlueBot", "id": "6bd21778a28530aaf5102326c09365694a6dc587", "size": "1519", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/bluebot/commands/fun/CyanideHapinessCommand.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3110" }, { "name": "Java", "bytes": "167871" } ], "symlink_target": "" }
package org.apache.storm.mqtt; import java.io.Serializable; import java.net.URI; import java.util.Arrays; import org.apache.activemq.broker.BrokerService; import org.apache.storm.Config; import org.apache.storm.LocalCluster; import org.apache.storm.LocalCluster.LocalTopology; import org.apache.storm.generated.StormTopology; import org.apache.storm.mqtt.bolt.MqttBolt; import org.apache.storm.mqtt.common.MqttOptions; import org.apache.storm.mqtt.common.MqttPublisher; import org.apache.storm.mqtt.mappers.StringMessageMapper; import org.apache.storm.mqtt.spout.MqttSpout; import org.apache.storm.testing.IntegrationTest; import org.apache.storm.topology.TopologyBuilder; import org.apache.storm.tuple.ITuple; import org.fusesource.mqtt.client.BlockingConnection; import org.fusesource.mqtt.client.MQTT; import org.fusesource.mqtt.client.Message; import org.fusesource.mqtt.client.QoS; import org.fusesource.mqtt.client.Topic; import org.junit.Assert; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @IntegrationTest public class StormMqttIntegrationTest implements Serializable { private static final Logger LOG = LoggerFactory.getLogger(StormMqttIntegrationTest.class); private static final String TEST_TOPIC = "/mqtt-topology"; private static final String RESULT_TOPIC = "/integration-result"; private static final String RESULT_PAYLOAD = "Storm MQTT Spout"; static boolean spoutActivated = false; private static BrokerService broker; @AfterAll public static void cleanup() throws Exception { broker.stop(); } @BeforeAll public static void start() throws Exception { LOG.warn("Starting broker..."); broker = new BrokerService(); broker.addConnector("mqtt://localhost:1883"); broker.setDataDirectory("target"); broker.start(); LOG.debug("MQTT broker started"); } @Test public void testMqttTopology() throws Exception { MQTT client = new MQTT(); client.setTracer(new MqttLogger()); URI uri = URI.create("tcp://localhost:1883"); client.setHost(uri); client.setClientId("MQTTSubscriber"); client.setCleanSession(false); BlockingConnection connection = client.blockingConnection(); connection.connect(); Topic[] topics = { new Topic("/integration-result", QoS.AT_LEAST_ONCE) }; byte[] qoses = connection.subscribe(topics); try (LocalCluster cluster = new LocalCluster(); LocalTopology topo = cluster.submitTopology("test", new Config(), buildMqttTopology());) { LOG.info("topology started"); while (!spoutActivated) { Thread.sleep(500); } // publish a retained message to the broker MqttOptions options = new MqttOptions(); options.setCleanConnection(false); MqttPublisher publisher = new MqttPublisher(options, true); publisher.connectMqtt("MqttPublisher"); publisher.publish(new MqttMessage(TEST_TOPIC, "test".getBytes())); LOG.info("published message"); Message message = connection.receive(); LOG.info("Message recieved on topic: {}", message.getTopic()); LOG.info("Payload: {}", new String(message.getPayload())); message.ack(); Assert.assertArrayEquals(message.getPayload(), RESULT_PAYLOAD.getBytes()); Assert.assertEquals(message.getTopic(), RESULT_TOPIC); } } public StormTopology buildMqttTopology() { TopologyBuilder builder = new TopologyBuilder(); MqttOptions options = new MqttOptions(); options.setTopics(Arrays.asList(TEST_TOPIC)); options.setCleanConnection(false); TestSpout spout = new TestSpout(new StringMessageMapper(), options); MqttBolt bolt = new MqttBolt(options, new MqttTupleMapper() { @Override public MqttMessage toMessage(ITuple tuple) { LOG.info("Received: {}", tuple); return new MqttMessage(RESULT_TOPIC, RESULT_PAYLOAD.getBytes()); } }); builder.setSpout("mqtt-spout", spout); builder.setBolt("mqtt-bolt", bolt).shuffleGrouping("mqtt-spout"); return builder.createTopology(); } public static class TestSpout extends MqttSpout { public TestSpout(MqttMessageMapper type, MqttOptions options) { super(type, options); } @Override public void activate() { super.activate(); LOG.info("Spout activated."); spoutActivated = true; } } }
{ "content_hash": "55e95d5eb56930c266f56dedc7efd0a2", "timestamp": "", "source": "github", "line_count": 133, "max_line_length": 103, "avg_line_length": 36.02255639097744, "alnum_prop": 0.6727196827384679, "repo_name": "hmcl/storm-apache", "id": "f1e0a2304542f95dcb0ef0e0b9d2b150a02c7cca", "size": "5575", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "external/storm-mqtt/src/test/java/org/apache/storm/mqtt/StormMqttIntegrationTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "54084" }, { "name": "CSS", "bytes": "12597" }, { "name": "Clojure", "bytes": "323393" }, { "name": "Fancy", "bytes": "6234" }, { "name": "FreeMarker", "bytes": "3512" }, { "name": "HTML", "bytes": "193952" }, { "name": "Java", "bytes": "12471832" }, { "name": "JavaScript", "bytes": "74893" }, { "name": "M4", "bytes": "1522" }, { "name": "Makefile", "bytes": "1302" }, { "name": "PowerShell", "bytes": "3405" }, { "name": "Python", "bytes": "1072987" }, { "name": "Ruby", "bytes": "15824" }, { "name": "Shell", "bytes": "24778" }, { "name": "Thrift", "bytes": "31772" }, { "name": "XSLT", "bytes": "1365" } ], "symlink_target": "" }
package us.kbase.integrateprobableannotation; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Generated; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; /** * <p>Original spec-file type: missingRoleHits</p> * * */ @JsonInclude(JsonInclude.Include.NON_NULL) @Generated("com.googlecode.jsonschema2pojo") @JsonPropertyOrder({ "missingRoles" }) public class MissingRoleHits { @JsonProperty("missingRoles") private List<MissingRolesData> missingRoles; private Map<String, Object> additionalProperties = new HashMap<String, Object>(); @JsonProperty("missingRoles") public List<MissingRolesData> getMissingRoles() { return missingRoles; } @JsonProperty("missingRoles") public void setMissingRoles(List<MissingRolesData> missingRoles) { this.missingRoles = missingRoles; } public MissingRoleHits withMissingRoles(List<MissingRolesData> missingRoles) { this.missingRoles = missingRoles; return this; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperties(String name, Object value) { this.additionalProperties.put(name, value); } @Override public String toString() { return ((((("MissingRoleHits"+" [missingRoles=")+ missingRoles)+", additionalProperties=")+ additionalProperties)+"]"); } }
{ "content_hash": "711240f973c54f8435764d0da423e753", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 127, "avg_line_length": 28.18032786885246, "alnum_prop": 0.7341477603257708, "repo_name": "janakagithub/IntegrateMissingAnnotation", "id": "80e793ced51e4ff41b4b756d099e7baa957d0c2d", "size": "1719", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/src/us/kbase/integrateprobableannotation/MissingRoleHits.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "14035" }, { "name": "JavaScript", "bytes": "4205" }, { "name": "Makefile", "bytes": "2888" }, { "name": "Perl", "bytes": "51089" }, { "name": "Python", "bytes": "8026" }, { "name": "Shell", "bytes": "1463" } ], "symlink_target": "" }
require 'uri' require 'yaml' require 'socket' class Service attr_reader :base_uri attr_accessor :name attr_accessor :auth_scheme def initialize(name, options) options = options.symbolize_keys self.name = name.to_s self.base_uri = options.delete(:uri) self.auth_scheme = options.delete(:auth_scheme) @daemon_options = options end def base_uri=(base_uri) case base_uri when String base_uri += '/' unless base_uri.ends_with?('/') @base_uri = URI.parse(base_uri) when nil raise ArgumentError, "base URI cannot be nil" else @base_uri = base_uri end end def get(path, &block) request :get, path, &block end def post(path, params, &block) request :post, path, params, &block end def put(path, params, &block) request :put, path, params, &block end def delete(path, &block) request :delete, path, &block end def request(method, path, params={}, &block) request_for(path, params, &block).__send__(method.to_s.downcase) end def running? daemon.running? end def start daemon.start end def stop daemon.stop end private def daemon @daemon ||= DaemonController.new(@daemon_options.merge( :identifier => name, :ping_command => lambda { TCPSocket.new(base_uri.host, base_uri.port) } )) end def request_for(path, params={}) # strip leading slashes for URI#+ path = path[1..-1] if path.starts_with?('/') Request.new(@base_uri + path) do |req| req.auth_scheme = auth_scheme if auth_scheme req.params = params yield req if block_given? end end def self.get(name) named_config = config[name] || config[:default] new(name, named_config) end def self.config @config ||= begin YAML.load_file(config_path).with_indifferent_access[Rails.env] end end def self.config_path Rails.root.join('config/services.yml') end def self.logger Rails.logger end class Request attr_reader :uri, :headers attr_accessor :timeout, :retries, :user, :auth_scheme, :proxy_url, :params def initialize(uri) # set defaults @headers = {} @proxy_url = nil # disable proxy @retries = 2 @auth_scheme = 'Basic' @params = {} yield self if block_given? @uri = uri end def get perform :get end def put perform :put end def post perform :post end def delete perform :delete end private def perform(method) retries = @retries old_proxy = RestClient.proxy res = nil begin RestClient.proxy = proxy_url.blank?? nil : proxy_url res = [:put, :post].include?(method) ? resource.__send__(method, params) : resource.__send__(method) rescue RestClient::Exception => e if retries > 0 Service.logger.warn { ["#{e.class}: #{e.message}", *e.backtrace].join("\n") } retries -= 1 retry else # return error response Service.logger.error { ["#{e.class}: #{e.message}", *e.backtrace].join("\n") } res = e.response end ensure RestClient.proxy = old_proxy end return Response.new(res.code, res.headers, res.body, res.headers[:content_type]) if res end def resource RestClient::Resource.new(uri.to_s, :timeout => timeout.to_i, :headers => headers_for_rest_client ) end def headers_for_rest_client headers = @headers.dup headers[:accept] ||= 'application/json' headers['Authorization'] ||= "#{auth_scheme} #{["#{user.id}:#{user.account_key}"].pack("m").strip.gsub("\n", "")}" if user return headers end end class Response attr_reader :code, :headers, :body, :content_type def initialize(code, headers, body, content_type) @code, @headers, @body, @content_type = code, headers, body, content_type end def self.error(sym) case sym when :gateway_timeout Response.new(504, "Gateway Timeout", "", "text/plain") else Response.new(500, "Internal Server Error", "", "text/plain") end end end end
{ "content_hash": "cb9bc124723df94d03bd3a44ddc5f8e3", "timestamp": "", "source": "github", "line_count": 196, "max_line_length": 128, "avg_line_length": 21.867346938775512, "alnum_prop": 0.5905272981801213, "repo_name": "wesabe/pfc", "id": "87730957d1d52ce902ff0d145ea4fa2467eba009", "size": "4286", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/service.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "173718" }, { "name": "JavaScript", "bytes": "966220" }, { "name": "Ruby", "bytes": "1178613" } ], "symlink_target": "" }
namespace JelloScrum.Model.Tests.Model { using Entities; using Enumerations; using NUnit.Framework; [TestFixture] public class GebruikerSprintGebruikerTest : TestBase { private Sprint sprint; public override void SetUp() { sprint = new Sprint(); base.SetUp(); } [Test] public void TestVindSprintGebruikerVanGebruikerVoorSprint() { User gb = new User(); sprint.AddUser(gb, SprintRole.Developer); SprintUser sg = gb.GetSprintUserFor(sprint); Assert.AreEqual(gb, sg.User); } [Test] public void TestVindGeenSprintGebruikerVanAndereSprints() { User gb = new User(); Sprint sprint2 = new Sprint(); sprint2.AddUser(gb, SprintRole.Developer); sprint.AddUser(gb, SprintRole.Developer); SprintUser sg = gb.GetSprintUserFor(sprint); Assert.AreEqual(sprint, sg.Sprint); } [Test] public void TestGeefActieveSprintGebruikerVanGebruiker() { User gb = new User(); gb.ActiveSprint = sprint; sprint.AddUser(gb, SprintRole.Developer); SprintUser sg = gb.GetActiveSprintUser(); Assert.AreEqual(sg.User, gb); } [Test] public void TestGeefActieveSprintGebruikerVanGebruikerTerwijlDezeNogNietGezetIs() { User gb = new User(); sprint.AddUser(gb, SprintRole.Developer); SprintUser sg = gb.GetActiveSprintUser(); Assert.AreEqual(null, sg); } } }
{ "content_hash": "e2f8f1611af83d6190ac5f052dc496f4", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 89, "avg_line_length": 26.125, "alnum_prop": 0.5711722488038278, "repo_name": "auxilium/JelloScrum", "id": "a0673e3774d611175c0150208bf963efc700fbdc", "size": "2292", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "JelloScrum/JelloScrum.Model.Tests/Model/GebruikerSprintGebruikerTest.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "398" }, { "name": "C#", "bytes": "565772" }, { "name": "JavaScript", "bytes": "676735" } ], "symlink_target": "" }
""" Copyright (c) 2016 Gabriel Esteban Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from django.contrib import admin from django.db import models from tinymce.widgets import TinyMCE from problem.models import Problem from problem.models import TestCase class TestCaseInline(admin.StackedInline): model = TestCase extra = 0 formfield_overrides = { models.TextField: {'widget': TinyMCE}, } class ProblemAdmin(admin.ModelAdmin): formfield_overrides = { models.TextField: {'widget': TinyMCE}, } inlines = [TestCaseInline] admin.site.register(Problem, ProblemAdmin)
{ "content_hash": "a35fad3b02529d8bba9e7be2a814960b", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 120, "avg_line_length": 39.875, "alnum_prop": 0.774294670846395, "repo_name": "galaxyfeeder/CodeSubmission", "id": "dc6e5775e3a764a4b7ac949930c2aaff1fb3b246", "size": "1595", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "problem/admin.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "167302" }, { "name": "HTML", "bytes": "18821" }, { "name": "Python", "bytes": "60959" } ], "symlink_target": "" }
package h2o.common.thirdparty.spring.transaction; import org.springframework.transaction.TransactionStatus; public interface TransactionCallbackWithoutResult { void doInTransaction(TransactionStatus status); }
{ "content_hash": "39e6aeef17d93f19cb95d7ee26854474", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 57, "avg_line_length": 24.22222222222222, "alnum_prop": 0.8440366972477065, "repo_name": "sixshot626/h2o", "id": "64c1994487442e69467b361f3fb845c2b92a8136", "size": "218", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "h2o-common/src/main/java/h2o/common/thirdparty/spring/transaction/TransactionCallbackWithoutResult.java", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "HTML", "bytes": "2262" }, { "name": "Java", "bytes": "3423449" }, { "name": "Shell", "bytes": "1002" } ], "symlink_target": "" }
use yaml_rust::{YamlLoader,Yaml}; use yaml_rust::yaml; use std::path::PathBuf; use std::net::SocketAddr; use std::io::Error as IoError; use std::fs::File; use std::io::prelude::*; use std::str::FromStr; #[derive(Debug)] pub struct Config { path:String, uris:Vec<SocketAddr>, fs_name: String } static CONFIG_FILE:&'static str = "dsefs-rs.yaml"; impl Config { pub fn build() -> Result<Self,IoError> { let mut yaml_file = try!(File::open(CONFIG_FILE)); let mut yaml_string = String::new(); try!(yaml_file.read_to_string(&mut yaml_string)); let yaml_config = &YamlLoader::load_from_str(&mut yaml_string).unwrap().clone()[0]; let yaml_config = yaml_config.as_hash().expect("bad config"); let mut uris = vec!(); let mut fs_name = String::new(); for (k,v) in yaml_config.iter() { match k { &Yaml::String(ref key) => match key.as_ref() { "fs_name" => { fs_name = v.as_str().expect("bad_config").to_owned(); }, "endpoints" => { for uri in v.as_vec().expect("bad_config") { uris.push(SocketAddr::from_str(uri.as_str().expect("bad_config")).unwrap()); } }, other => panic!("other: {}", other) }, _ => panic!() } }; Ok(Config{path:CONFIG_FILE.to_owned(),uris:uris, fs_name:fs_name}) } pub fn uris(&self) -> Vec<SocketAddr> { self.uris.clone() } }
{ "content_hash": "361a8ae96d778574c9ac22b2153b2448", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 85, "avg_line_length": 25.807692307692307, "alnum_prop": 0.6058122205663189, "repo_name": "tupshin/dsefs-rs", "id": "50fbd55d1336044b7f8fac542be9b5e1b284cca4", "size": "1342", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/dsefs/config.rs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Rust", "bytes": "1546" } ], "symlink_target": "" }
using UnityEngine; using System.Collections; public class Enemy2 : MonoBehaviour { private float moveSpeed = 0.5f; // Use this for initialization void Start () { GetComponent<Rigidbody> ().freezeRotation = true; } // Update is called once per frame void Update () { var MovePoint3 = GameObject.Find("MovePoint3").transform.position; var MovePoint4 = GameObject.Find("MovePoint4").transform.position; transform.position = Vector3.Lerp (MovePoint3, MovePoint4, Mathf.PingPong(Time.time * moveSpeed, 1f)); } }
{ "content_hash": "60ecc5c97a95b287ced3c6f8d00b8432", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 104, "avg_line_length": 24.09090909090909, "alnum_prop": 0.7320754716981132, "repo_name": "yeukfei02/3Dgame", "id": "180143b601dad662ca0333cc275fe3d23e645c92", "size": "532", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Assets/Scripts/Enemy2.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "18025" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "dba2b03aacdd9bdb70e802e1d42c3fbf", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "9567a0c745bdd982a926bcdcbcce0ccd7bb3ca2a", "size": "183", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Euphorbiaceae/Euphorbia/Euphorbia carniolica/ Syn. Euphorbia mehadiensis/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
from __future__ import print_function import sys, os sys.path.insert(1, os.path.join("..","..","..")) import h2o from tests import pyunit_utils def deepLearningDemo(): # Training data train_data = h2o.import_file(path=pyunit_utils.locate("smalldata/gbm_test/ecology_model.csv")) train_data = train_data.drop('Site') train_data['Angaus'] = train_data['Angaus'].asfactor() print(train_data.describe()) train_data.head() # Testing data test_data = h2o.import_file(path=pyunit_utils.locate("smalldata/gbm_test/ecology_eval.csv")) test_data['Angaus'] = test_data['Angaus'].asfactor() print(test_data.describe()) test_data.head() # Run GBM gbm = h2o.gbm(x = train_data[1:], y = train_data['Angaus'], validation_x= test_data [1:] , validation_y= test_data ['Angaus'], ntrees=100, distribution="bernoulli") gbm.show() # Run DeepLearning dl = h2o.deeplearning(x = train_data[1:], y = train_data['Angaus'], validation_x= test_data [1:] , validation_y= test_data ['Angaus'], loss = 'CrossEntropy', epochs = 1000, hidden = [20, 20, 20]) dl.show() if __name__ == "__main__": pyunit_utils.standalone_test(deepLearningDemo) else: deepLearningDemo()
{ "content_hash": "ec682a82da5ec5aa8cfad8bfbc336863", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 96, "avg_line_length": 28.529411764705884, "alnum_prop": 0.5484536082474227, "repo_name": "nilbody/h2o-3", "id": "0dba35f738b317475217b5a250a638f072e89b98", "size": "1455", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "h2o-py/tests/testdir_algos/deeplearning/pyunit_DEPRECATED_demoDeeplearning.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "5090" }, { "name": "CSS", "bytes": "162399" }, { "name": "CoffeeScript", "bytes": "267048" }, { "name": "Emacs Lisp", "bytes": "8966" }, { "name": "HTML", "bytes": "140849" }, { "name": "Java", "bytes": "6084118" }, { "name": "JavaScript", "bytes": "38932" }, { "name": "Jupyter Notebook", "bytes": "6756015" }, { "name": "Makefile", "bytes": "34048" }, { "name": "Python", "bytes": "3788960" }, { "name": "R", "bytes": "1745563" }, { "name": "Rebol", "bytes": "7059" }, { "name": "Ruby", "bytes": "3506" }, { "name": "Scala", "bytes": "22834" }, { "name": "Shell", "bytes": "61644" }, { "name": "TeX", "bytes": "533885" } ], "symlink_target": "" }
""" File metadata management ------------------------ The `trac.mimeview` package centralizes the intelligence related to file metadata, principally concerning the `type` (MIME type) of the content and, if relevant, concerning the text encoding (charset) used by the content. There are primarily two approaches for getting the MIME type of a given file, either taking advantage of existing conventions for the file name, or examining the file content and applying various heuristics. The module also knows how to convert the file content from one type to another type. In some cases, only the `url` pointing to the file's content is actually needed, that's why we avoid to read the file's content when it's not needed. The actual `content` to be converted might be a `unicode` object, but it can also be the raw byte string (`str`) object, or simply an object that can be `read()`. .. note:: (for plugin developers) The Mimeview API is quite complex and many things there are currently a bit difficult to work with (e.g. what an actual `content` might be, see the last paragraph of this description). So this area is mainly in a ''work in progress'' state, which will be improved along the lines described in :teo:`#3332`. In particular, if you are interested in writing `IContentConverter` and `IHTMLPreviewRenderer` components, note that those interfaces will be merged into a new style `IContentConverter`. Feel free to contribute remarks and suggestions for improvements to the corresponding ticket (#3332 as well). """ import re from StringIO import StringIO from genshi import Markup, Stream from genshi.core import TEXT, START, END, START_NS, END_NS from genshi.builder import Fragment, tag from genshi.input import HTMLParser from trac.config import IntOption, ListOption, Option from trac.core import * from trac.resource import Resource from trac.util import Ranges, content_disposition from trac.util.text import exception_to_unicode, to_utf8, to_unicode from trac.util.translation import _, tag_ __all__ = ['Context', 'Mimeview', 'RenderingContext', 'get_mimetype', 'is_binary', 'detect_unicode', 'content_to_unicode', 'ct_mimetype'] class RenderingContext(object): """ A rendering context specifies ''how'' the content should be rendered. It holds together all the needed contextual information that will be needed by individual renderer components. To that end, a context keeps track of the Href instance (`.href`) which should be used as a base for building URLs. It also provides a `PermissionCache` (`.perm`) which can be used to restrict the output so that only the authorized information is shown. A rendering context may also be associated to some Trac resource which will be used as the implicit reference when rendering relative links or for retrieving relative content and can be used to retrieve related metadata. Rendering contexts can be nested, and a new context can be created from an existing context using the call syntax. The previous context can be retrieved using the `.parent` attribute. For example, when rendering a wiki text of a wiki page, the context will be associated to a resource identifying that wiki page. If that wiki text contains a `[[TicketQuery]]` wiki macro, the macro will set up nested contexts for each matching ticket that will be used for rendering the ticket descriptions. :since: version 0.11 """ def __init__(self, resource, href=None, perm=None): """Directly create a `RenderingContext`. :param resource: the associated resource :type resource: `Resource` :param href: an `Href` object suitable for creating URLs :param perm: a `PermissionCache` object used for restricting the generated output to "authorized" information only. The actual `.perm` attribute of the rendering context will be bound to the given `resource` so that fine-grained permission checks will apply to that. """ self.parent = None #: The parent context, if any self.resource = resource self.href = href self.perm = perm(resource) if perm and resource else perm self._hints = None @staticmethod def from_request(*args, **kwargs): """:deprecated: since 1.0, use `web_context` instead.""" from trac.web.chrome import web_context return web_context(*args, **kwargs) def __repr__(self): path = [] context = self while context: if context.resource.realm: # skip toplevel resource path.append(repr(context.resource)) context = context.parent return '<%s %s>' % (type(self).__name__, ' - '.join(reversed(path))) def child(self, resource=None, id=False, version=False, parent=False): """Create a nested rendering context. `self` will be the parent for the new nested context. :param resource: either a `Resource` object or the realm string for a resource specification to be associated to the new context. If `None`, the resource will be the same as the resource of the parent context. :param id: the identifier part of the resource specification :param version: the version of the resource specification :return: the new context object :rtype: `RenderingContext` >>> context = RenderingContext('wiki', 'WikiStart') >>> ticket1 = Resource('ticket', 1) >>> context.child('ticket', 1).resource == ticket1 True >>> context.child(ticket1).resource is ticket1 True >>> context.child(ticket1)().resource is ticket1 True """ if resource: resource = Resource(resource, id=id, version=version, parent=parent) else: resource = self.resource context = RenderingContext(resource, href=self.href, perm=self.perm) context.parent = self # hack for context instances created by from_request() # this is needed because various parts of the code rely on a request # object being available, but that will hopefully improve in the # future if hasattr(self, 'req'): context.req = self.req return context __call__ = child def __contains__(self, resource): """Check whether a resource is in the rendering path. The primary use for this check is to avoid to render the content of a resource if we're already embedded in a context associated to that resource. :param resource: a `Resource` specification which will be checked for """ context = self while context: if context.resource and \ context.resource.realm == resource.realm and \ context.resource.id == resource.id: # we don't care about version here return True context = context.parent # Rendering hints # # A rendering hint is a key/value pairs that can influence renderers, # wiki formatters and processors in the way they produce their output. # The keys are strings, but the values could be anything. # # In nested contexts, the hints are inherited from their parent context, # unless overriden locally. def set_hints(self, **keyvalues): """Set rendering hints for this rendering context. >>> ctx = RenderingContext('timeline') >>> ctx.set_hints(wiki_flavor='oneliner', shorten_lines=True) >>> t_ctx = ctx('ticket', 1) >>> t_ctx.set_hints(wiki_flavor='html', preserve_newlines=True) >>> (t_ctx.get_hint('wiki_flavor'), t_ctx.get_hint('shorten_lines'), \ t_ctx.get_hint('preserve_newlines')) ('html', True, True) >>> (ctx.get_hint('wiki_flavor'), ctx.get_hint('shorten_lines'), \ ctx.get_hint('preserve_newlines')) ('oneliner', True, None) """ if self._hints is None: self._hints = {} hints = self._parent_hints() if hints is not None: self._hints.update(hints) self._hints.update(keyvalues) def get_hint(self, hint, default=None): """Retrieve a rendering hint from this context or an ancestor context. >>> ctx = RenderingContext('timeline') >>> ctx.set_hints(wiki_flavor='oneliner') >>> t_ctx = ctx('ticket', 1) >>> t_ctx.get_hint('wiki_flavor') 'oneliner' >>> t_ctx.get_hint('preserve_newlines', True) True """ hints = self._hints if hints is None: hints = self._parent_hints() if hints is None: return default return hints.get(hint, default) def has_hint(self, hint): """Test whether a rendering hint is defined in this context or in some ancestor context. >>> ctx = RenderingContext('timeline') >>> ctx.set_hints(wiki_flavor='oneliner') >>> t_ctx = ctx('ticket', 1) >>> t_ctx.has_hint('wiki_flavor') True >>> t_ctx.has_hint('preserve_newlines') False """ hints = self._hints if hints is None: hints = self._parent_hints() if hints is None: return False return hint in hints def _parent_hints(self): p = self.parent while p and p._hints is None: p = p.parent return p and p._hints class Context(RenderingContext): """:deprecated: old name kept for compatibility, use `RenderingContext`.""" # Some common MIME types and their associated keywords and/or file extensions KNOWN_MIME_TYPES = { 'application/javascript': 'js', 'application/msword': 'doc dot', 'application/pdf': 'pdf', 'application/postscript': 'ps', 'application/rtf': 'rtf', 'application/x-sh': 'sh', 'application/x-csh': 'csh', 'application/x-troff': 'nroff roff troff', 'application/x-yaml': 'yml yaml', 'application/rss+xml': 'rss', 'application/xsl+xml': 'xsl', 'application/xslt+xml': 'xslt', 'image/x-icon': 'ico', 'image/svg+xml': 'svg', 'model/vrml': 'vrml wrl', 'text/css': 'css', 'text/html': 'html htm', 'text/plain': 'txt TXT text README INSTALL ' 'AUTHORS COPYING ChangeLog RELEASE', 'text/xml': 'xml', # see also TEXT_X_TYPES below 'text/x-csrc': 'c xs', 'text/x-chdr': 'h', 'text/x-c++src': 'cc CC cpp C c++ C++', 'text/x-c++hdr': 'hh HH hpp H', 'text/x-csharp': 'cs c# C#', 'text/x-diff': 'patch', 'text/x-eiffel': 'e', 'text/x-elisp': 'el', 'text/x-fortran': 'f', 'text/x-haskell': 'hs', 'text/x-ini': 'ini cfg', 'text/x-objc': 'm mm', 'text/x-ocaml': 'ml mli', 'text/x-makefile': 'make mk Makefile GNUMakefile', 'text/x-pascal': 'pas', 'text/x-perl': 'pl pm PL', 'text/x-php': 'php3 php4', 'text/x-python': 'py', 'text/x-pyrex': 'pyx', 'text/x-ruby': 'rb', 'text/x-scheme': 'scm', 'text/x-textile': 'txtl', 'text/x-vba': 'vb vba bas', 'text/x-verilog': 'v', 'text/x-vhdl': 'vhd', } for t in KNOWN_MIME_TYPES.keys(): types = KNOWN_MIME_TYPES[t].split() if t.startswith('text/x-'): types.append(t[len('text/x-'):]) KNOWN_MIME_TYPES[t] = types # extend the above with simple (text/x-<something>: <something>) mappings TEXT_X_TYPES = """ ada asm asp awk idl inf java ksh lua m4 mail psp rfc rst sql tcl tex zsh """ for x in TEXT_X_TYPES.split(): KNOWN_MIME_TYPES.setdefault('text/x-%s' % x, []).append(x) # Default mapping from keywords/extensions to known MIME types: MIME_MAP = {} for t, exts in KNOWN_MIME_TYPES.items(): MIME_MAP[t] = t for e in exts: MIME_MAP[e] = t # Simple builtin autodetection from the content using a regexp MODE_RE = re.compile(r""" \#!.+?env\s+(\w+) # 1. look for shebang with env | \#!(?:[/\w.-_]+/)?(\w+) # 2. look for regular shebang | -\*-\s*(?:mode:\s*)?([\w+-]+)\s*-\*- # 3. look for Emacs' -*- mode -*- | vim:.*?(?:syntax|filetype|ft)=(\w+) # 4. look for VIM's syntax=<n> """, re.VERBOSE) def get_mimetype(filename, content=None, mime_map=MIME_MAP, mime_map_patterns={}): """Guess the most probable MIME type of a file with the given name. `filename` is either a filename (the lookup will then use the suffix) or some arbitrary keyword. `content` is either a `str` or an `unicode` string. """ # 0) mimetype from filename pattern (most specific) for mimetype, regexp in mime_map_patterns.iteritems(): if regexp.match(filename): return mimetype suffix = filename.split('.')[-1] if suffix in mime_map: # 1) mimetype from the suffix, using the `mime_map` return mime_map[suffix] else: mimetype = None try: import mimetypes # 2) mimetype from the suffix, using the `mimetypes` module mimetype = mimetypes.guess_type(filename)[0] except Exception: pass if not mimetype and content: match = re.search(MODE_RE, content[:1000] + content[-1000:]) if match: mode = match.group(1) or match.group(2) or match.group(4) or \ match.group(3).lower() if mode in mime_map: # 3) mimetype from the content, using the `MODE_RE` return mime_map[mode] else: if is_binary(content): # 4) mimetype from the content, using`is_binary` return 'application/octet-stream' return mimetype def ct_mimetype(content_type): """Return the mimetype part of a content type.""" return (content_type or '').split(';')[0].strip() def is_binary(data): """Detect binary content by checking the first thousand bytes for zeroes. Operate on either `str` or `unicode` strings. """ if isinstance(data, str) and detect_unicode(data): return False return '\0' in data[:1000] def detect_unicode(data): """Detect different unicode charsets by looking for BOMs (Byte Order Mark). Operate obviously only on `str` objects. """ if data.startswith('\xff\xfe'): return 'utf-16-le' elif data.startswith('\xfe\xff'): return 'utf-16-be' elif data.startswith('\xef\xbb\xbf'): return 'utf-8' else: return None def content_to_unicode(env, content, mimetype): """Retrieve an `unicode` object from a `content` to be previewed. In case the raw content had an unicode BOM, we remove it. >>> from trac.test import EnvironmentStub >>> env = EnvironmentStub() >>> content_to_unicode(env, u"\ufeffNo BOM! h\u00e9 !", '') u'No BOM! h\\xe9 !' >>> content_to_unicode(env, "\xef\xbb\xbfNo BOM! h\xc3\xa9 !", '') u'No BOM! h\\xe9 !' """ mimeview = Mimeview(env) if hasattr(content, 'read'): content = content.read(mimeview.max_preview_size) u = mimeview.to_unicode(content, mimetype) if u and u[0] == u'\ufeff': u = u[1:] return u class IHTMLPreviewRenderer(Interface): """Extension point interface for components that add HTML renderers of specific content types to the `Mimeview` component. .. note:: This interface will be merged with IContentConverter, as conversion to text/html will simply be a particular content conversion. Note however that the IHTMLPreviewRenderer will still be supported for a while through an adapter, whereas the IContentConverter interface itself will be changed. So if all you want to do is convert to HTML and don't feel like following the API changes, you should rather implement this interface for the time being. """ #: implementing classes should set this property to True if they #: support text content where Trac should expand tabs into spaces expand_tabs = False #: indicate whether the output of this renderer is source code that can #: be decorated with annotations returns_source = False def get_extra_mimetypes(): """Augment the Mimeview system with new mimetypes associations. This is an optional method. Not implementing the method or returning nothing is fine, the component will still be asked via `get_quality_ratio` if it supports a known mimetype. But implementing it can be useful when the component knows about additional mimetypes which may augment the list of already mimetype to keywords associations. Generate ``(mimetype, keywords)`` pairs for each additional mimetype, with ``keywords`` being a list of keywords or extensions that can be used as aliases for the mimetype (typically file suffixes or Wiki processor keys). .. versionadded:: 1.0 """ def get_quality_ratio(mimetype): """Return the level of support this renderer provides for the `content` of the specified MIME type. The return value must be a number between 0 and 9, where 0 means no support and 9 means "perfect" support. """ def render(context, mimetype, content, filename=None, url=None): """Render an XHTML preview of the raw `content` in a RenderingContext. The `content` might be: * a `str` object * an `unicode` string * any object with a `read` method, returning one of the above It is assumed that the content will correspond to the given `mimetype`. Besides the `content` value, the same content may eventually be available through the `filename` or `url` parameters. This is useful for renderers that embed objects, using <object> or <img> instead of including the content inline. Can return the generated XHTML text as a single string or as an iterable that yields strings. In the latter case, the list will be considered to correspond to lines of text in the original content. """ class IHTMLPreviewAnnotator(Interface): """Extension point interface for components that can annotate an XHTML representation of file contents with additional information.""" def get_annotation_type(): """Return a (type, label, description) tuple that defines the type of annotation and provides human readable names. The `type` element should be unique to the annotator. The `label` element is used as column heading for the table, while `description` is used as a display name to let the user toggle the appearance of the annotation type. """ def get_annotation_data(context): """Return some metadata to be used by the `annotate_row` method below. This will be called only once, before lines are processed. If this raises an error, that annotator won't be used. """ def annotate_row(context, row, number, line, data): """Return the XHTML markup for the table cell that contains the annotation data. `context` is the context corresponding to the content being annotated, `row` is the tr Element being built, `number` is the line number being processed and `line` is the line's actual content. `data` is whatever additional data the `get_annotation_data` method decided to provide. """ class IContentConverter(Interface): """An extension point interface for generic MIME based content conversion. .. note:: This api will likely change in the future (see :teo:`#3332`) """ def get_supported_conversions(): """Return an iterable of tuples in the form (key, name, extension, in_mimetype, out_mimetype, quality) representing the MIME conversions supported and the quality ratio of the conversion in the range 0 to 9, where 0 means no support and 9 means "perfect" support. eg. ('latex', 'LaTeX', 'tex', 'text/x-trac-wiki', 'text/plain', 8)""" def convert_content(req, mimetype, content, key): """Convert the given content from mimetype to the output MIME type represented by key. Returns a tuple in the form (content, output_mime_type) or None if conversion is not possible.""" class Content(object): """A lazy file-like object that only reads `input` if necessary.""" def __init__(self, input, max_size): self.input = input self.max_size = max_size self.content = None def read(self, size=-1): if size == 0: return '' if self.content is None: self.content = StringIO(self.input.read(self.max_size)) return self.content.read(size) def reset(self): if self.content is not None: self.content.seek(0) class Mimeview(Component): """Generic HTML renderer for data, typically source code.""" required = True renderers = ExtensionPoint(IHTMLPreviewRenderer) annotators = ExtensionPoint(IHTMLPreviewAnnotator) converters = ExtensionPoint(IContentConverter) default_charset = Option('trac', 'default_charset', 'utf-8', """Charset to be used when in doubt.""") tab_width = IntOption('mimeviewer', 'tab_width', 8, """Displayed tab width in file preview. (''since 0.9'')""") max_preview_size = IntOption('mimeviewer', 'max_preview_size', 262144, """Maximum file size for HTML preview. (''since 0.9'')""") mime_map = ListOption('mimeviewer', 'mime_map', 'text/x-dylan:dylan, text/x-idl:ice, text/x-ada:ads:adb', doc="""List of additional MIME types and keyword mappings. Mappings are comma-separated, and for each MIME type, there's a colon (":") separated list of associated keywords or file extensions. (''since 0.10'')""") mime_map_patterns = ListOption('mimeviewer', 'mime_map_patterns', 'text/plain:README|INSTALL|COPYING.*', doc="""List of additional MIME types associated to filename patterns. Mappings are comma-separated, and each mapping consists of a MIME type and a Python regexp used for matching filenames, separated by a colon (":"). (''since 1.0'')""") treat_as_binary = ListOption('mimeviewer', 'treat_as_binary', 'application/octet-stream, application/pdf, application/postscript, ' 'application/msword,application/rtf,', doc="""Comma-separated list of MIME types that should be treated as binary data. (''since 0.11.5'')""") def __init__(self): self._mime_map = None self._mime_map_patterns = None # Public API def get_supported_conversions(self, mimetype): """Return a list of target MIME types in same form as `IContentConverter.get_supported_conversions()`, but with the converter component appended. Output is ordered from best to worst quality.""" converters = [] for converter in self.converters: conversions = converter.get_supported_conversions() or [] for k, n, e, im, om, q in conversions: if im == mimetype and q > 0: converters.append((k, n, e, im, om, q, converter)) converters = sorted(converters, key=lambda i: i[-2], reverse=True) return converters def convert_content(self, req, mimetype, content, key, filename=None, url=None): """Convert the given content to the target MIME type represented by `key`, which can be either a MIME type or a key. Returns a tuple of (content, output_mime_type, extension).""" if not content: return ('', 'text/plain;charset=utf-8', '.txt') # Ensure we have a MIME type for this content full_mimetype = mimetype if not full_mimetype: if hasattr(content, 'read'): content = content.read(self.max_preview_size) full_mimetype = self.get_mimetype(filename, content) if full_mimetype: mimetype = ct_mimetype(full_mimetype) # split off charset else: mimetype = full_mimetype = 'text/plain' # fallback if not binary # Choose best converter candidates = list(self.get_supported_conversions(mimetype) or []) candidates = [c for c in candidates if key in (c[0], c[4])] if not candidates: raise TracError( _("No available MIME conversions from %(old)s to %(new)s", old=mimetype, new=key)) # First successful conversion wins for ck, name, ext, input_mimettype, output_mimetype, quality, \ converter in candidates: output = converter.convert_content(req, mimetype, content, ck) if output: return (output[0], output[1], ext) raise TracError( _("No available MIME conversions from %(old)s to %(new)s", old=mimetype, new=key)) def get_annotation_types(self): """Generator that returns all available annotation types.""" for annotator in self.annotators: yield annotator.get_annotation_type() def render(self, context, mimetype, content, filename=None, url=None, annotations=None, force_source=False): """Render an XHTML preview of the given `content`. `content` is the same as an `IHTMLPreviewRenderer.render`'s `content` argument. The specified `mimetype` will be used to select the most appropriate `IHTMLPreviewRenderer` implementation available for this MIME type. If not given, the MIME type will be infered from the filename or the content. Return a string containing the XHTML text. When rendering with an `IHTMLPreviewRenderer` fails, a warning is added to the request associated with the context (if any), unless the `disable_warnings` hint is set to `True`. """ if not content: return '' if not isinstance(context, RenderingContext): raise TypeError("RenderingContext expected (since 0.11)") # Ensure we have a MIME type for this content full_mimetype = mimetype if not full_mimetype: if hasattr(content, 'read'): content = content.read(self.max_preview_size) full_mimetype = self.get_mimetype(filename, content) if full_mimetype: mimetype = ct_mimetype(full_mimetype) # split off charset else: mimetype = full_mimetype = 'text/plain' # fallback if not binary # Determine candidate `IHTMLPreviewRenderer`s candidates = [] for renderer in self.renderers: qr = renderer.get_quality_ratio(mimetype) if qr > 0: candidates.append((qr, renderer)) candidates.sort(lambda x, y: cmp(y[0], x[0])) # Wrap file-like object so that it can be read multiple times if hasattr(content, 'read'): content = Content(content, self.max_preview_size) # First candidate which renders successfully wins. # Also, we don't want to expand tabs more than once. expanded_content = None for qr, renderer in candidates: if force_source and not getattr(renderer, 'returns_source', False): continue # skip non-source renderers in force_source mode if isinstance(content, Content): content.reset() try: ann_names = ', '.join(annotations) if annotations else \ 'no annotations' self.log.debug('Trying to render HTML preview using %s [%s]', renderer.__class__.__name__, ann_names) # check if we need to perform a tab expansion rendered_content = content if getattr(renderer, 'expand_tabs', False): if expanded_content is None: content = content_to_unicode(self.env, content, full_mimetype) expanded_content = content.expandtabs(self.tab_width) rendered_content = expanded_content result = renderer.render(context, full_mimetype, rendered_content, filename, url) if not result: continue if not (force_source or getattr(renderer, 'returns_source', False)): # Direct rendering of content if isinstance(result, basestring): if not isinstance(result, unicode): result = to_unicode(result) return Markup(to_unicode(result)) elif isinstance(result, Fragment): return result.generate() else: return result # Render content as source code if annotations: m = context.req.args.get('marks') if context.req else None return self._render_source(context, result, annotations, m and Ranges(m)) else: if isinstance(result, list): result = Markup('\n').join(result) return tag.div(class_='code')(tag.pre(result)).generate() except Exception, e: self.log.warning('HTML preview using %s failed: %s', renderer.__class__.__name__, exception_to_unicode(e, traceback=True)) if context.req and not context.get_hint('disable_warnings'): from trac.web.chrome import add_warning add_warning(context.req, _("HTML preview using %(renderer)s failed (%(err)s)", renderer=renderer.__class__.__name__, err=exception_to_unicode(e))) def _render_source(self, context, stream, annotations, marks=None): from trac.web.chrome import add_warning annotators, labels, titles = {}, {}, {} for annotator in self.annotators: atype, alabel, atitle = annotator.get_annotation_type() if atype in annotations: labels[atype] = alabel titles[atype] = atitle annotators[atype] = annotator annotations = [a for a in annotations if a in annotators] if isinstance(stream, list): stream = HTMLParser(StringIO(u'\n'.join(stream))) elif isinstance(stream, unicode): text = stream def linesplitter(): for line in text.splitlines(True): yield TEXT, line, (None, -1, -1) stream = linesplitter() annotator_datas = [] for a in annotations: annotator = annotators[a] try: data = (annotator, annotator.get_annotation_data(context)) except TracError, e: self.log.warning("Can't use annotator '%s': %s", a, e.message) add_warning(context.req, tag.strong( tag_("Can't use %(annotator)s annotator: %(error)s", annotator=tag.em(a), error=tag.pre(e.message)))) data = (None, None) annotator_datas.append(data) def _head_row(): return tag.tr( [tag.th(labels[a], class_=a, title=titles[a]) for a in annotations] + [tag.th(u'\xa0', class_='content')] ) def _body_rows(): for idx, line in enumerate(_group_lines(stream)): row = tag.tr() if marks and idx + 1 in marks: row(class_='hilite') for annotator, data in annotator_datas: if annotator: annotator.annotate_row(context, row, idx+1, line, data) else: row.append(tag.td()) row.append(tag.td(line)) yield row return tag.table(class_='code')( tag.thead(_head_row()), tag.tbody(_body_rows()) ) def get_max_preview_size(self): """:deprecated: use `max_preview_size` attribute directly.""" return self.max_preview_size def get_charset(self, content='', mimetype=None): """Infer the character encoding from the `content` or the `mimetype`. `content` is either a `str` or an `unicode` object. The charset will be determined using this order: * from the charset information present in the `mimetype` argument * auto-detection of the charset from the `content` * the configured `default_charset` """ if mimetype: ctpos = mimetype.find('charset=') if ctpos >= 0: return mimetype[ctpos + 8:].strip() if isinstance(content, str): utf = detect_unicode(content) if utf is not None: return utf return self.default_charset @property def mime_map(self): # Extend default extension to MIME type mappings with configured ones if not self._mime_map: self._mime_map = MIME_MAP.copy() # augment mime_map from `IHTMLPreviewRenderer`s for renderer in self.renderers: if hasattr(renderer, 'get_extra_mimetypes'): for mimetype, kwds in renderer.get_extra_mimetypes() or []: self._mime_map[mimetype] = mimetype for keyword in kwds: self._mime_map[keyword] = mimetype # augment/override mime_map from trac.ini for mapping in self.config['mimeviewer'].getlist('mime_map'): if ':' in mapping: assocations = mapping.split(':') for keyword in assocations: # Note: [0] kept on purpose self._mime_map[keyword] = assocations[0] return self._mime_map def get_mimetype(self, filename, content=None): """Infer the MIME type from the `filename` or the `content`. `content` is either a `str` or an `unicode` object. Return the detected MIME type, augmented by the charset information (i.e. "<mimetype>; charset=..."), or `None` if detection failed. """ mimetype = get_mimetype(filename, content, self.mime_map, self.mime_map_patterns) charset = None if mimetype: charset = self.get_charset(content, mimetype) if mimetype and charset and not 'charset' in mimetype: mimetype += '; charset=' + charset return mimetype @property def mime_map_patterns(self): if not self._mime_map_patterns: self._mime_map_patterns = {} for mapping in self.config['mimeviewer'] \ .getlist('mime_map_patterns'): if ':' in mapping: mimetype, regexp = mapping.split(':', 1) try: self._mime_map_patterns[mimetype] = re.compile(regexp) except re.error, e: self.log.warning("mime_map_patterns contains invalid " "regexp '%s' for mimetype '%s' (%s)", regexp, mimetype, exception_to_unicode(e)) return self._mime_map_patterns def is_binary(self, mimetype=None, filename=None, content=None): """Check if a file must be considered as binary.""" if not mimetype and filename: mimetype = self.get_mimetype(filename, content) if mimetype: mimetype = ct_mimetype(mimetype) if mimetype in self.treat_as_binary: return True if content is not None and is_binary(content): return True return False def to_utf8(self, content, mimetype=None): """Convert an encoded `content` to utf-8. :deprecated: since 0.10, you should use `unicode` strings only. """ return to_utf8(content, self.get_charset(content, mimetype)) def to_unicode(self, content, mimetype=None, charset=None): """Convert `content` (an encoded `str` object) to an `unicode` object. This calls `trac.util.to_unicode` with the `charset` provided, or the one obtained by `Mimeview.get_charset()`. """ if not charset: charset = self.get_charset(content, mimetype) return to_unicode(content, charset) def configured_modes_mapping(self, renderer): """Return a MIME type to `(mode,quality)` mapping for given `option`""" types, option = {}, '%s_modes' % renderer for mapping in self.config['mimeviewer'].getlist(option): if not mapping: continue try: mimetype, mode, quality = mapping.split(':') types[mimetype] = (mode, int(quality)) except (TypeError, ValueError): self.log.warning("Invalid mapping '%s' specified in '%s' " "option.", mapping, option) return types def preview_data(self, context, content, length, mimetype, filename, url=None, annotations=None, force_source=False): """Prepares a rendered preview of the given `content`. Note: `content` will usually be an object with a `read` method. """ data = {'raw_href': url, 'size': length, 'max_file_size': self.max_preview_size, 'max_file_size_reached': False, 'rendered': None, } if length >= self.max_preview_size: data['max_file_size_reached'] = True else: result = self.render(context, mimetype, content, filename, url, annotations, force_source=force_source) data['rendered'] = result return data def send_converted(self, req, in_type, content, selector, filename='file'): """Helper method for converting `content` and sending it directly. `selector` can be either a key or a MIME Type.""" from trac.web.api import RequestDone content, output_type, ext = self.convert_content(req, in_type, content, selector) if isinstance(content, unicode): content = content.encode('utf-8') req.send_response(200) req.send_header('Content-Type', output_type) req.send_header('Content-Length', len(content)) if filename: req.send_header('Content-Disposition', content_disposition('attachment', '%s.%s' % (filename, ext))) req.end_headers() req.write(content) raise RequestDone def _group_lines(stream): space_re = re.compile('(?P<spaces> (?: +))|^(?P<tag><\w+.*?>)?( )') def pad_spaces(match): m = match.group('spaces') if m: div, mod = divmod(len(m), 2) return div * u'\xa0 ' + mod * u'\xa0' return (match.group('tag') or '') + u'\xa0' def _generate(): stack = [] def _reverse(): for event in reversed(stack): if event[0] is START: yield END, event[1][0], event[2] else: yield END_NS, event[1][0], event[2] for kind, data, pos in stream: if kind is TEXT: lines = data.split('\n') if lines: # First element for e in stack: yield e yield kind, lines.pop(0), pos for e in _reverse(): yield e # Subsequent ones, prefix with \n for line in lines: yield TEXT, '\n', pos for e in stack: yield e yield kind, line, pos for e in _reverse(): yield e else: if kind is START or kind is START_NS: stack.append((kind, data, pos)) elif kind is END or kind is END_NS: stack.pop() else: yield kind, data, pos buf = [] # Fix the \n at EOF. if not isinstance(stream, list): stream = list(stream) found_text = False for i in range(len(stream)-1, -1, -1): if stream[i][0] is TEXT: e = stream[i] # One chance to strip a \n if not found_text and e[1].endswith('\n'): stream[i] = (e[0], e[1][:-1], e[2]) if len(e[1]): found_text = True break if not found_text: raise StopIteration for kind, data, pos in _generate(): if kind is TEXT and data == '\n': yield Stream(buf[:]) del buf[:] else: if kind is TEXT: data = space_re.sub(pad_spaces, data) buf.append((kind, data, pos)) if buf: yield Stream(buf[:]) # -- Default annotators class LineNumberAnnotator(Component): """Text annotator that adds a column with line numbers.""" implements(IHTMLPreviewAnnotator) # ITextAnnotator methods def get_annotation_type(self): return 'lineno', _('Line'), _('Line numbers') def get_annotation_data(self, context): return None def annotate_row(self, context, row, lineno, line, data): row.append(tag.th(id='L%s' % lineno)( tag.a(lineno, href='#L%s' % lineno) )) # -- Default renderers class PlainTextRenderer(Component): """HTML preview renderer for plain text, and fallback for any kind of text for which no more specific renderer is available. """ implements(IHTMLPreviewRenderer) expand_tabs = True returns_source = True def get_quality_ratio(self, mimetype): if mimetype in Mimeview(self.env).treat_as_binary: return 0 return 1 def render(self, context, mimetype, content, filename=None, url=None): if is_binary(content): self.log.debug("Binary data; no preview available") return self.log.debug("Using default plain text mimeviewer") return content_to_unicode(self.env, content, mimetype) class ImageRenderer(Component): """Inline image display. This component doesn't need the `content` at all. """ implements(IHTMLPreviewRenderer) def get_quality_ratio(self, mimetype): if mimetype.startswith('image/'): return 8 return 0 def render(self, context, mimetype, content, filename=None, url=None): if url: return tag.div(tag.img(src=url, alt=filename), class_='image-file') class WikiTextRenderer(Component): """HTML renderer for files containing Trac's own Wiki formatting markup.""" implements(IHTMLPreviewRenderer) def get_quality_ratio(self, mimetype): if mimetype in ('text/x-trac-wiki', 'application/x-trac-wiki'): return 8 return 0 def render(self, context, mimetype, content, filename=None, url=None): from trac.wiki.formatter import format_to_html return format_to_html(self.env, context, content_to_unicode(self.env, content, mimetype))
{ "content_hash": "01ca24cbececa5abd5cd96294b50232d", "timestamp": "", "source": "github", "line_count": 1160, "max_line_length": 79, "avg_line_length": 38.75603448275862, "alnum_prop": 0.5805325088417822, "repo_name": "trac-ja/trac-ja", "id": "1e2e37e3d0d38a80c2f4ea02b64af59495b6689d", "size": "45769", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "trac/mimeview/api.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "78123" }, { "name": "JavaScript", "bytes": "79829" }, { "name": "Perl", "bytes": "2617" }, { "name": "Python", "bytes": "2818601" }, { "name": "Shell", "bytes": "11347" } ], "symlink_target": "" }
class TaskProvider { public: TaskProvider(); ~TaskProvider(); void addTask(const Task&); void markUsed(const Task&); const std::list<const Task*>& getRecentTasks() const; std::list<const Task*> findTasksByName(const std::string& name) const; private: void updateRecentTasks(); private: std::list<const Task*> recentTasks; std::list<Task> tasks; }; #endif // TASKPROVIDER_H
{ "content_hash": "f208530442ce90b62b19055ca08e8dc6", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 74, "avg_line_length": 20.65, "alnum_prop": 0.6731234866828087, "repo_name": "alex-under/yatt", "id": "41880bbcfcdbf5fc28063b0b4072df5554a9ba09", "size": "495", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "yatt-core/include/task-provider.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "6669211" }, { "name": "C++", "bytes": "429500" }, { "name": "CMake", "bytes": "1330" } ], "symlink_target": "" }
<html><head><meta http-equiv="Content-type" content="text/html; charset=utf-8"> <title>Student Seeking Mentor</title> <link href="/static/spreadsheets/client/css/2761485455-embedded_form_compiled.css" type="text/css" rel="stylesheet"> <style type="text/css"> </style><style type="text/css"></style></head> <body class="ss-base-body" dir="ltr" itemscope="" itemtype="http://schema.org/CreativeWork/FormObject" marginwidth="0" marginheight="0"><meta itemprop="name" content="Student Seeking Mentor"> <meta itemprop="description" content="This is for any college group student who is interested in receiving a mentor."> <meta itemprop="url" content="https://docs.google.com/spreadsheet/viewform?formkey=dFREd21Ec0VHamxCSkZIRElLSXNtQnc6MQ"> <meta itemprop="embedUrl" content="https://docs.google.com/spreadsheet/embeddedform?formkey=dFREd21Ec0VHamxCSkZIRElLSXNtQnc6MQ"> <meta itemprop="faviconUrl" content="//ssl.gstatic.com/docs/spreadsheets/forms/favicon_jfk2.png"> <div class="ss-form-container"><div class="ss-form-heading"><h1 class="ss-form-title">Student Seeking Mentor</h1> <p></p> <div class="ss-form-desc ss-no-ignore-whitespace">This is for any college group student who is interested in receiving a mentor.</div> <hr class="ss-email-break" style="display:none;"> <div class="ss-required-asterisk">* Required</div></div> <div class="ss-form"><form action="https://docs.google.com/a/shinymayhem.com/spreadsheet/formResponse?formkey=dFREd21Ec0VHamxCSkZIRElLSXNtQnc6MQ&amp;embedded=true&amp;ifq" method="POST" id="ss-form" _lpchecked="1"> <br> <div class="errorbox-good"> <div class="ss-item ss-item-required ss-text"><div class="ss-form-entry"><label class="ss-q-title" for="entry_0">Name <span class="ss-required-asterisk">*</span></label> <label class="ss-q-help" for="entry_0"></label> <input type="text" name="entry.0.single" value="" class="ss-q-short" id="entry_0"></div></div></div> <br> <div class="errorbox-good"> <div class="ss-item ss-item-required ss-text"><div class="ss-form-entry"><label class="ss-q-title" for="entry_20">e-mail <span class="ss-required-asterisk">*</span></label> <label class="ss-q-help" for="entry_20"></label> <input type="text" name="entry.20.single" value="" class="ss-q-short" id="entry_20"></div></div></div> <br> <div class="errorbox-good"> <div class="ss-item ss-item-required ss-paragraph-text"><div class="ss-form-entry"><label class="ss-q-title" for="entry_1">General Availability <span class="ss-required-asterisk">*</span></label> <label class="ss-q-help" for="entry_1">Please provide the day of the week followed by your available or preferred times.</label> <textarea name="entry.1.single" rows="8" cols="75" class="ss-q-long" id="entry_1"></textarea></div></div></div> <br> <div class="errorbox-good"> <div class="ss-item ss-item-required ss-paragraph-text"><div class="ss-form-entry"><label class="ss-q-title" for="entry_10">Mentor Expectations <span class="ss-required-asterisk">*</span></label> <label class="ss-q-help" for="entry_10">Share a little about why you are looking for a mentor. Do you want someone to walk through scripture with, do you have a specific need or conversation you would like to have, or just seeking wisdom in general.</label> <textarea name="entry.10.single" rows="8" cols="75" class="ss-q-long" id="entry_10"></textarea></div></div></div> <br> <div class="errorbox-good"> <div class="ss-item ss-item-required ss-paragraph-text"><div class="ss-form-entry"><label class="ss-q-title" for="entry_19">Personal Bio <span class="ss-required-asterisk">*</span></label> <label class="ss-q-help" for="entry_19">Any interests, hobbies, career choices or favorite movies you would like to share that may be helpful in pairing you with a mentor. </label> <textarea name="entry.19.single" rows="8" cols="75" class="ss-q-long" id="entry_19"></textarea></div></div></div> <br> <input type="hidden" name="pageNumber" value="0"> <input type="hidden" name="backupCache" value=""> <div class="ss-item ss-navigate"><div class="ss-form-entry"> <input type="submit" name="submit" value="Submit"></div></div></form> </div> <div class="ss-footer"><div class="ss-attribution"></div> <div class="ss-legal"><span class="ss-powered-by">Powered by <a href="http://docs.google.com">Google Docs</a></span> <span class="ss-terms"><small><a href="https://docs.google.com/spreadsheet/reportabuse?formkey=dFREd21Ec0VHamxCSkZIRElLSXNtQnc6MQ&amp;source=https://docs.google.com/a/shinymayhem.com/spreadsheet/embeddedform?formkey%3DdFREd21Ec0VHamxCSkZIRElLSXNtQnc6MQ">Report Abuse</a> - <a href="http://www.google.com/accounts/TOS">Terms of Service</a> - <a href="http://www.google.com/google-d-s/terms.html">Additional Terms</a></small></span></div></div></div><div style="display: none;" id="hiddenlpsubmitdiv"></div><script>try{for(var lastpass_iter=0; lastpass_iter < document.forms.length; lastpass_iter++){ var lastpass_f = document.forms[lastpass_iter]; if(typeof(lastpass_f.lpsubmitorig2)=="undefined"){ lastpass_f.lpsubmitorig2 = lastpass_f.submit; lastpass_f.submit = function(){ var form=this; var customEvent = document.createEvent("Event"); customEvent.initEvent("lpCustomEvent", true, true); var d = document.getElementById("hiddenlpsubmitdiv"); for(var i = 0; i < document.forms.length; i++){ if(document.forms[i]==form){ d.innerText=i; } } d.dispatchEvent(customEvent); form.lpsubmitorig2(); } } }}catch(e){}</script></body></html>
{ "content_hash": "56ef3f190bbb245af0147fcb7c6e4ea5", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 797, "avg_line_length": 86.01538461538462, "alnum_prop": 0.7057771418350921, "repo_name": "shinymayhem/imago-dei-college", "id": "16367c8e44ec2d020e254f13204922ae4c930213", "size": "5591", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/mentee-application.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "JavaScript", "bytes": "56265" }, { "name": "PHP", "bytes": "9183" } ], "symlink_target": "" }
describe('Filter: localizeNumber', function () { beforeEach(module('ngTools')); var filter; beforeEach(inject(function ($filter) { filter = $filter('localizeNumber'); })); it('should give us a string formatted according to national setting of the browser', function () { expect(filter(21598.489)).toEqual('21598.489'); }); });
{ "content_hash": "26476037a9a728a9300641d88267647d", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 99, "avg_line_length": 24.357142857142858, "alnum_prop": 0.6891495601173021, "repo_name": "capaj/ng-tools", "id": "948268f7700eb393e5440bae5a5298655049f496", "size": "342", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/spec/filters.spec.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "5275" }, { "name": "JavaScript", "bytes": "27441" } ], "symlink_target": "" }
package com.bitdubai.android_core.app.common.version_1.navigation_drawer; import android.content.Context; import android.graphics.Typeface; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bitdubai.android_core.app.ApplicationSession; import com.bitdubai.fermat.R; import java.util.List; public class NavigationDrawerArrayAdapter extends ArrayAdapter<String> { private final Context context; private final List<String> values; public NavigationDrawerArrayAdapter(Context context, List<String> values) { super(context, R.layout.wallet_framework_activity_main_navigation_drawer_row_layout_empty, values); try { this.context = context; this.values = values; } catch (Exception e) { throw e; } } @Override public View getView(int position, View convertView, ViewGroup parent) { Typeface tf=Typeface.createFromAsset(context.getAssets(), "fonts/CaviarDreams.ttf"); View rowView = convertView; try { if (position == 0) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); //testing rowView = inflater.inflate(R.layout.wallet_manager_desktop_activity_navigation_drawer_first_row, parent, false); /*switch (ApplicationSession.getActivityId()) { case "DesktopActivity": rowView = inflater.inflate(R.layout.wallet_manager_desktop_activity_navigation_drawer_first_row, parent, false); break; default: rowView = inflater.inflate(R.layout.wallet_manager_main_activity_navigation_drawer_first_row_empty, parent, false); break; }*/ TextView txtView_description = (TextView) rowView.findViewById(R.id.txtView_description); if(txtView_description != null){ txtView_description.setTypeface(tf, 1); //ImageView imageView = (ImageView) rowView.findViewById(R.id.icon); txtView_description.setText("Tessa Crankston"); } ImageView iconEdit = (ImageView) rowView.findViewById(R.id.icon_change_profile); iconEdit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(context,"cambiando de ususario proximamente",Toast.LENGTH_SHORT).show(); } }); } else { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); rowView = inflater.inflate(R.layout.wallet_framework_activity_framework_navigation_drawer_row_layout, parent, false); //test mati rowView = inflater.inflate(R.layout.wallet_manager_desktop_activity_framework_navigation_drawer_row_layout, parent, false); /*switch (ApplicationSession.getActivityId()) { case "DesktopActivity": rowView = inflater.inflate(R.layout.wallet_manager_desktop_activity_framework_navigation_drawer_row_layout, parent, false); break; default: rowView = inflater.inflate(R.layout.wallet_framework_activity_main_navigation_drawer_row_layout_empty, parent, false); break; } */ ImageView imageView = null; imageView = (ImageView) rowView.findViewById(R.id.icon); if(rowView.findViewById(R.id.label) != null) { TextView textView = (TextView) rowView.findViewById(R.id.label); textView.setTypeface(tf, 1); textView.setText(values.get(position)); } //if (ApplicationSession.getActivityId() == "DesktopActivity") { switch (position) { case 1: imageView.setImageResource(R.drawable.ic_action_store); break; case 2: imageView.setImageResource(R.drawable.ic_action_wallet); break; case 3: imageView.setImageResource(R.drawable.ic_action_factory); break; case 4: imageView.setImageResource(R.drawable.ic_action_wallet_published); break; case 5: imageView.setImageResource(R.drawable.ic_action_wallet); break; case 6: imageView.setImageResource(R.drawable.ic_action_exit); break; default: imageView.setImageResource(R.drawable.unknown_icon); } } //} } catch (Exception e){ throw e; } return rowView; } }
{ "content_hash": "c146bcef941ac79d286747b4a47aa671", "timestamp": "", "source": "github", "line_count": 157, "max_line_length": 147, "avg_line_length": 35.152866242038215, "alnum_prop": 0.5522739626743975, "repo_name": "fvasquezjatar/fermat-unused", "id": "f13d45a30f122052650da2378a7bb5bf5afcda77", "size": "5519", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "fermat-android-core/src/main/java/com/bitdubai/android_core/app/common/version_1/navigation_drawer/NavigationDrawerArrayAdapter.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1204" }, { "name": "Groovy", "bytes": "76309" }, { "name": "HTML", "bytes": "322840" }, { "name": "Java", "bytes": "14027288" }, { "name": "Scala", "bytes": "1353" } ], "symlink_target": "" }
import unittest from mesonwrap import version class VersionTest(unittest.TestCase): def test_semantic(self): versions = [ ('1.2.3', 8), ('1.2.11', 1), ('1.2.11', 2), ('11.2.3', 9), ('11.2.3', 11), ] sorted_versions = sorted(versions, key=version.version_key) self.assertEqual(versions, sorted_versions) def test_non_semantic(self): versions = [ ('1.2', 1), ('1.3', 5), ('1.7', 2), ] sorted_versions = sorted(versions, key=version.version_key) self.assertEqual(versions, sorted_versions) def test_non_semantic_single_number(self): versions = [ ('12345', 1), ('212345', 1), ] sorted_versions = sorted(versions, key=version.version_key) self.assertEqual(versions, sorted_versions) def test_non_semantic_version_letters(self): versions = [ ('2b', 1), ('17a', 1), ] sorted_versions = sorted(versions, key=version.version_key) self.assertEqual(versions, sorted_versions) if __name__ == '__main__': unittest.main()
{ "content_hash": "28d8e17d45099d9c1f388390b1ff9fc8", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 57, "avg_line_length": 26.82, "alnum_prop": 0.47054436987322895, "repo_name": "mesonbuild/wrapweb", "id": "ff932f0f3b5b12eba6b30ba3e4e94aa3b6aee70f", "size": "1341", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "mesonwrap/version_test.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "298" }, { "name": "HTML", "bytes": "3074" }, { "name": "JavaScript", "bytes": "484" }, { "name": "Python", "bytes": "99665" } ], "symlink_target": "" }
 namespace FrwSoftware { partial class SimpleHtmlTextEditDialog { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SimpleHtmlTextEditDialog)); this.cancelButtion = new System.Windows.Forms.Button(); this.okButton = new System.Windows.Forms.Button(); this.textEditorControl = new FrwSoftware.TextEditorControl(); this.SuspendLayout(); // // cancelButtion // resources.ApplyResources(this.cancelButtion, "cancelButtion"); this.cancelButtion.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.cancelButtion.Name = "cancelButtion"; this.cancelButtion.UseVisualStyleBackColor = true; // // okButton // resources.ApplyResources(this.okButton, "okButton"); this.okButton.DialogResult = System.Windows.Forms.DialogResult.OK; this.okButton.Name = "okButton"; this.okButton.UseVisualStyleBackColor = true; this.okButton.Click += new System.EventHandler(this.okButton_Click); // // textEditorControl // resources.ApplyResources(this.textEditorControl, "textEditorControl"); this.textEditorControl.EditedText = ""; this.textEditorControl.Name = "textEditorControl"; // // SimpleHtmlTextEditDialog // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.textEditorControl); this.Controls.Add(this.cancelButtion); this.Controls.Add(this.okButton); this.MinimizeBox = false; this.Name = "SimpleHtmlTextEditDialog"; this.ShowIcon = false; this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button cancelButtion; private System.Windows.Forms.Button okButton; private TextEditorControl textEditorControl; } }
{ "content_hash": "a1a5edfadd611103ade305939a88d9d2", "timestamp": "", "source": "github", "line_count": 79, "max_line_length": 156, "avg_line_length": 38.51898734177215, "alnum_prop": 0.5987512323365101, "repo_name": "frwsoftware/FrwSimpleWinCRUD", "id": "d2ec23ab415bb4de1329834c4e251153cc66868b", "size": "3045", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "FrwSimpleWinCRUD/HTMLEditorControl/SimpleHtmlTextEditDialog.Designer.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "94" }, { "name": "C#", "bytes": "1449633" } ], "symlink_target": "" }
package net.dv8tion.jda.core.handle; import gnu.trove.map.TLongIntMap; import gnu.trove.map.TLongObjectMap; import gnu.trove.map.hash.TLongIntHashMap; import gnu.trove.map.hash.TLongObjectHashMap; import net.dv8tion.jda.core.entities.impl.JDAImpl; import org.json.JSONArray; import org.json.JSONObject; import java.util.LinkedList; import java.util.List; public class GuildMembersChunkHandler extends SocketHandler { private final TLongIntMap expectedGuildMembers = new TLongIntHashMap(); private final TLongObjectMap<List<JSONArray>> memberChunksCache = new TLongObjectHashMap<>(); public GuildMembersChunkHandler(JDAImpl api) { super(api); } @Override protected Long handleInternally(JSONObject content) { final long guildId = content.getLong("guild_id"); List<JSONArray> memberChunks = memberChunksCache.get(guildId); int expectMemberCount = expectedGuildMembers.get(guildId); JSONArray members = content.getJSONArray("members"); JDAImpl.LOG.debug("GUILD_MEMBER_CHUNK for: " + guildId + " \tMembers: " + members.length()); memberChunks.add(members); int currentTotal = 0; for (JSONArray arr : memberChunks) { currentTotal += arr.length(); } if (currentTotal >= expectMemberCount) { JDAImpl.LOG.debug("Finished chunking for: " + guildId); api.getEntityBuilder().createGuildSecondPass(guildId, memberChunks); memberChunksCache.remove(guildId); expectedGuildMembers.remove(guildId); } return null; } public void setExpectedGuildMembers(long guildId, int count) { if (expectedGuildMembers.containsKey(guildId)) JDAImpl.LOG.warn("Set the count of expected users from GuildMembersChunk even though a value already exists! GuildId: " + guildId); expectedGuildMembers.put(guildId, count); if (memberChunksCache.containsKey(guildId)) JDAImpl.LOG.warn("Set the memberChunks for MemberChunking for a guild that was already setup for chunking! GuildId: " + guildId); memberChunksCache.put(guildId, new LinkedList<>()); } public void modifyExpectedGuildMember(long guildId, int changeAmount) { try { Integer i = expectedGuildMembers.get(guildId); i += changeAmount; expectedGuildMembers.put(guildId, i); } //Ignore. If one of the above things doesn't exist, causing an NPE, then we don't need to worry. catch (NullPointerException ignored) {} } public void clearCache() { expectedGuildMembers.clear(); memberChunksCache.clear(); } }
{ "content_hash": "9aac9f17543d332269031e019fd5112d", "timestamp": "", "source": "github", "line_count": 83, "max_line_length": 143, "avg_line_length": 33, "alnum_prop": 0.674333698430084, "repo_name": "mentlerd/JDA", "id": "0c3e611619f632993549985f48640d6c7869ac60", "size": "3378", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/net/dv8tion/jda/core/handle/GuildMembersChunkHandler.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "2463756" } ], "symlink_target": "" }
#ifndef __domPhysics_model_h__ #define __domPhysics_model_h__ #include <dom/domTypes.h> #include <dom/domElements.h> #include <dom/domAsset.h> #include <dom/domRigid_body.h> #include <dom/domRigid_constraint.h> #include <dom/domInstance_physics_model.h> #include <dom/domExtra.h> /** * This element allows for building complex combinations of rigid-bodies and * constraints that may be instantiated multiple times. */ class domPhysics_model : public daeElement { public: COLLADA_TYPE::TypeEnum getElementType() const { return COLLADA_TYPE::PHYSICS_MODEL; } protected: // Attributes /** * The id attribute is a text string containing the unique identifier of * this element. This value must be unique within the instance document. * Optional attribute. */ xsID attrId; /** * The name attribute is the text string name of this element. Optional attribute. */ xsNCName attrName; protected: // Elements /** * The physics_model element may contain an asset element. @see domAsset */ domAssetRef elemAsset; /** * The physics_model may define any number of rigid_body elements. @see * domRigid_body */ domRigid_body_Array elemRigid_body_array; /** * The physics_model may define any number of rigid_constraint elements. * @see domRigid_constraint */ domRigid_constraint_Array elemRigid_constraint_array; /** * The physics_model may instance any number of other physics_model elements. * @see domInstance_physics_model */ domInstance_physics_model_Array elemInstance_physics_model_array; /** * The extra element may appear any number of times. @see domExtra */ domExtra_Array elemExtra_array; public: //Accessors and Mutators /** * Gets the id attribute. * @return Returns a xsID of the id attribute. */ xsID getId() const { return attrId; } /** * Sets the id attribute. * @param atId The new value for the id attribute. */ void setId( xsID atId ) { *(daeStringRef*)&attrId = atId; _validAttributeArray[0] = true; } /** * Gets the name attribute. * @return Returns a xsNCName of the name attribute. */ xsNCName getName() const { return attrName; } /** * Sets the name attribute. * @param atName The new value for the name attribute. */ void setName( xsNCName atName ) { *(daeStringRef*)&attrName = atName; _validAttributeArray[1] = true; } /** * Gets the asset element. * @return a daeSmartRef to the asset element. */ const domAssetRef getAsset() const { return elemAsset; } /** * Gets the rigid_body element array. * @return Returns a reference to the array of rigid_body elements. */ domRigid_body_Array &getRigid_body_array() { return elemRigid_body_array; } /** * Gets the rigid_body element array. * @return Returns a constant reference to the array of rigid_body elements. */ const domRigid_body_Array &getRigid_body_array() const { return elemRigid_body_array; } /** * Gets the rigid_constraint element array. * @return Returns a reference to the array of rigid_constraint elements. */ domRigid_constraint_Array &getRigid_constraint_array() { return elemRigid_constraint_array; } /** * Gets the rigid_constraint element array. * @return Returns a constant reference to the array of rigid_constraint elements. */ const domRigid_constraint_Array &getRigid_constraint_array() const { return elemRigid_constraint_array; } /** * Gets the instance_physics_model element array. * @return Returns a reference to the array of instance_physics_model elements. */ domInstance_physics_model_Array &getInstance_physics_model_array() { return elemInstance_physics_model_array; } /** * Gets the instance_physics_model element array. * @return Returns a constant reference to the array of instance_physics_model elements. */ const domInstance_physics_model_Array &getInstance_physics_model_array() const { return elemInstance_physics_model_array; } /** * Gets the extra element array. * @return Returns a reference to the array of extra elements. */ domExtra_Array &getExtra_array() { return elemExtra_array; } /** * Gets the extra element array. * @return Returns a constant reference to the array of extra elements. */ const domExtra_Array &getExtra_array() const { return elemExtra_array; } protected: /** * Constructor */ domPhysics_model() : attrId(), attrName(), elemAsset(), elemRigid_body_array(), elemRigid_constraint_array(), elemInstance_physics_model_array(), elemExtra_array() {} /** * Destructor */ virtual ~domPhysics_model() {} /** * Copy Constructor */ domPhysics_model( const domPhysics_model &cpy ) : daeElement() { (void)cpy; } /** * Overloaded assignment operator */ virtual domPhysics_model &operator=( const domPhysics_model &cpy ) { (void)cpy; return *this; } public: // STATIC METHODS /** * Creates an instance of this class and returns a daeElementRef referencing it. * @param bytes The size allocated for this instance. * @return a daeElementRef referencing an instance of this object. */ static DLLSPEC daeElementRef create(daeInt bytes); /** * Creates a daeMetaElement object that describes this element in the meta object reflection framework. * If a daeMetaElement already exists it will return that instead of creating a new one. * @return A daeMetaElement describing this COLLADA element. */ static DLLSPEC daeMetaElement* registerElement(); public: // STATIC MEMBERS /** * The daeMetaElement that describes this element in the meta object reflection framework. */ static DLLSPEC daeMetaElement* _Meta; }; #endif
{ "content_hash": "0888b48a2b5765de1625219919787062", "timestamp": "", "source": "github", "line_count": 169, "max_line_length": 167, "avg_line_length": 32.81656804733728, "alnum_prop": 0.72304363505229, "repo_name": "palestar/medusa", "id": "54a1d6f0217597c427103be0beab1e19c2bc857c", "size": "6180", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "ThirdParty/bullet-2.75/Extras/COLLADA_DOM/include/1.4/dom/domPhysics_model.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "864803" }, { "name": "C++", "bytes": "12938688" }, { "name": "Clarion", "bytes": "80976" }, { "name": "Lua", "bytes": "4055" }, { "name": "Makefile", "bytes": "37934" }, { "name": "Objective-C", "bytes": "3178" }, { "name": "R", "bytes": "3909" }, { "name": "Shell", "bytes": "4892" } ], "symlink_target": "" }
package com.dihanov.musiq.models; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.List; public class Albummatches { @SerializedName("album") @Expose private List<Album> album = null; public List<Album> getAlbum() { return album; } public void setAlbum(List<Album> album) { this.album = album; } }
{ "content_hash": "d3cc8f680ddd3c85f989693dceb8d8cc", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 50, "avg_line_length": 19.523809523809526, "alnum_prop": 0.6804878048780488, "repo_name": "DDihanov/musiQ", "id": "c0acbbe5a984018994944639737734edd6f3f35b", "size": "411", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/dihanov/musiq/models/Albummatches.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "453590" } ], "symlink_target": "" }
package org.onlab.packet; import org.onlab.packet.pim.PIMHello; import org.onlab.packet.pim.PIMJoinPrune; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.Map; import static com.google.common.base.MoreObjects.toStringHelper; import static org.onlab.packet.PacketUtils.checkInput; /** * Implements PIM control packet format. */ public class PIM extends BasePacket { public static final IpAddress PIM_ADDRESS = IpAddress.valueOf("224.0.0.13"); public static final byte TYPE_HELLO = 0x00; public static final byte TYPE_REGISTER = 0x01; public static final byte TYPE_REGISTER_STOP = 0x02; public static final byte TYPE_JOIN_PRUNE_REQUEST = 0x03; public static final byte TYPE_BOOTSTRAP = 0x04; public static final byte TYPE_ASSERT = 0x05; public static final byte TYPE_GRAFT = 0x06; public static final byte TYPE_GRAFT_ACK = 0x07; public static final byte TYPE_CANDIDATE_RP_ADV = 0x08; public static final int PIM_HEADER_LEN = 4; public static final byte ADDRESS_FAMILY_IP4 = 0x1; public static final byte ADDRESS_FAMILY_IP6 = 0x2; public static final Map<Byte, Deserializer<? extends IPacket>> PROTOCOL_DESERIALIZER_MAP = new HashMap<>(); static { PIM.PROTOCOL_DESERIALIZER_MAP.put(PIM.TYPE_HELLO, PIMHello.deserializer()); PIM.PROTOCOL_DESERIALIZER_MAP.put(PIM.TYPE_JOIN_PRUNE_REQUEST, PIMJoinPrune.deserializer()); } /* * PIM Header fields */ protected byte version; protected byte type; protected byte reserved; protected short checksum; /** * Default constructor. */ public PIM() { super(); this.version = 2; this.reserved = 0; } /** * Return the PIM message type. * * @return the pimMsgType */ public byte getPimMsgType() { return this.type; } /** * Set the PIM message type. Currently PIMJoinPrune and PIMHello are * supported. * * @param type PIM message type * @return PIM Header */ public PIM setPIMType(final byte type) { this.type = type; return this; } /** * Get the version of PIM. * * @return the PIM version. Must be 2. */ public byte getVersion() { return version; } /** * Set the PIM version type. Should not change from 2. * * @param version PIM version */ public void setVersion(byte version) { this.version = version; } /** * Get the reserved field. * * @return the reserved field. Must be ignored. */ public byte getReserved() { return reserved; } /** * Set the reserved field. * * @param reserved should be 0 */ public void setReserved(byte reserved) { this.reserved = reserved; } /** * Get the checksum of this packet. * * @return the checksum */ public short getChecksum() { return checksum; } /** * Set the checksum. * * @param checksum the checksum */ public void setChecksum(short checksum) { this.checksum = checksum; } /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 5807; int result = super.hashCode(); result = prime * result + this.type; result = prime * result + this.version; result = prime * result + this.checksum; return result; } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (!(obj instanceof PIM)) { return false; } final PIM other = (PIM) obj; if (this.type != other.type) { return false; } if (this.version != other.version) { return false; } if (this.checksum != other.checksum) { return false; } return true; } /** * Serializes the packet. Will compute and set the following fields if they * are set to specific values at the time serialize is called: -checksum : 0 * -length : 0 * * @return will return the serialized packet */ @Override public byte[] serialize() { int length = 4; byte[] payloadData = null; if (this.payload != null) { this.payload.setParent(this); payloadData = this.payload.serialize(); length += payloadData.length; } final byte[] data = new byte[length]; final ByteBuffer bb = ByteBuffer.wrap(data); bb.put((byte) ((this.version & 0xf) << 4 | this.type & 0xf)); bb.put(this.reserved); bb.putShort(this.checksum); if (payloadData != null) { bb.put(payloadData); } if (this.parent != null && this.parent instanceof PIM) { ((PIM) this.parent).setPIMType(TYPE_JOIN_PRUNE_REQUEST); } // compute checksum if needed if (this.checksum == 0) { bb.rewind(); int accumulation = 0; for (int i = 0; i < length / 2; ++i) { accumulation += 0xffff & bb.getShort(); } // pad to an even number of shorts if (length % 2 > 0) { accumulation += (bb.get() & 0xff) << 8; } accumulation = (accumulation >> 16 & 0xffff) + (accumulation & 0xffff); this.checksum = (short) (~accumulation & 0xffff); bb.putShort(2, this.checksum); } return data; } /** * Deserialize the PIM packet. * * @param data bytes to deserialize. * @param offset offset to start deserializing from * @param length length of the data to deserialize * * @return the deserialized PIM packet. */ @Override public IPacket deserialize(final byte[] data, final int offset, final int length) { final ByteBuffer bb = ByteBuffer.wrap(data, offset, length); this.type = bb.get(); this.version = bb.get(); this.checksum = bb.getShort(); //this.payload = new Data(); this.payload = this.payload.deserialize(data, bb.position(), bb.limit() - bb.position()); this.payload.setParent(this); return this; } /** * Deserializer function for IPv4 packets. * * @return deserializer function */ public static Deserializer<PIM> deserializer() { return (data, offset, length) -> { checkInput(data, offset, length, PIM_HEADER_LEN); PIM pim = new PIM(); final ByteBuffer bb = ByteBuffer.wrap(data, offset, length); byte versionByte = bb.get(); pim.version = (byte) (versionByte >> 4 & 0xf); pim.setPIMType((byte) (versionByte & 0xf)); pim.reserved = bb.get(); pim.checksum = bb.getShort(); Deserializer<? extends IPacket> deserializer; if (PIM.PROTOCOL_DESERIALIZER_MAP.containsKey(pim.getPimMsgType())) { deserializer = PIM.PROTOCOL_DESERIALIZER_MAP.get(pim.getPimMsgType()); } else { deserializer = Data.deserializer(); } pim.payload = deserializer.deserialize(data, bb.position(), bb.limit() - bb.position()); pim.payload.setParent(pim); return pim; }; } @Override public String toString() { return toStringHelper(getClass()) .add("version", Byte.toString(version)) .add("type", Byte.toString(type)) .add("reserved", Byte.toString(reserved)) .add("checksum", Short.toString(reserved)) .toString(); } }
{ "content_hash": "314cfb01f3c934ee0ac66455dc8c4fde", "timestamp": "", "source": "github", "line_count": 296, "max_line_length": 100, "avg_line_length": 27.37162162162162, "alnum_prop": 0.5620834361885954, "repo_name": "sdnwiselab/onos", "id": "df55318c3234538be4abbb4e8ceadb30e7ab08f6", "size": "8719", "binary": false, "copies": "1", "ref": "refs/heads/onos-sdn-wise-1.10", "path": "utils/misc/src/main/java/org/onlab/packet/PIM.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "222318" }, { "name": "HTML", "bytes": "148718" }, { "name": "Java", "bytes": "34889939" }, { "name": "JavaScript", "bytes": "3818724" }, { "name": "Python", "bytes": "492716" }, { "name": "Ruby", "bytes": "4052" }, { "name": "Shell", "bytes": "205831" } ], "symlink_target": "" }
package cellularAutomata.cellState.view; import java.awt.Color; import java.awt.Shape; import java.awt.geom.Point2D; import cellularAutomata.cellState.model.CellState; import cellularAutomata.cellState.model.IntegerVectorState; import cellularAutomata.graphics.colors.ColorScheme; import cellularAutomata.util.Arrow; import cellularAutomata.util.Coordinate; /** * Provides vector (arrow) graphics for the IntegerVectorState class. These * graphics are suitable for simulations where each component of the vector * state indicates the maginitude of a vector along a lattice direction. This * class is not useful for lattice gas simulations because the last element of * the vector represents the presence or absence of a wall rather than the * magnitude of a vector. * <p> * Also see IntegerVectorDefaultView. * * @author David Bahr */ public class IntegerVectorArrowView extends CellStateView { /** * Returns the endpoint of the vector representing the given state. * * @param The * state for which the vector position is beiong calculated. * @param The * width of the bounding box that conpatins the vector. * @return The x and y coordinates of the endpoint of the vector state. * @see cellularAutomaton.cellState.IntegerVectorState#getDisplayShape */ private Point2D.Double getLineCoordinates(IntegerVectorState vectorState, int width) { // each array index is a vector with a magnitude given by the array // value int[] state = (int[]) vectorState.getValue(); // the change in angle created by each array indices' vector. double deltaDegrees = 360.0 / state.length; double deltaRadians = deltaDegrees * (Math.PI / 180.0); // x is the adjacent side of the triangle created by each // array indices' vector. double x = 0.0; // y is the opposite side of the triangle created by each // array indices' vector. double y = 0.0; for(int i = 0; i < state.length; i++) { // The angle created by each array indices' vector. // (Note we subtract from 0.0*deltaRadians because the first array // position is the vector pointing along the x-axis.) double thetaRadians = (0.0 * deltaRadians) - (i * deltaRadians); // the magnitude is the hypotenuse of the triangle created by each // array indices' vector. double hyp = state[i]; // but this magnitude (hypotenuse) needs to be rescaled. A value of // 1 really means that the vector spans the distance from a cell to // its neighbor. This span is given by "width". hyp *= width; // We add the contribution of each vector. // (Actually, we subtract y, so that the coordinates are consistent // with the Java graphics coordinates that point y downwards.) x += hyp * Math.cos(thetaRadians); y -= hyp * Math.sin(thetaRadians); } return new Point2D.Double(x, y); } /** * Creates an average of all the vectors represented by the cell states. * <br> * Child classes should override this method if they need a different * average shape. * * @param width * The width of the rectangle that bounds this Shape. May be * ignored. * @param height * The height of the rectangle that bounds this Shape. May be * ignored. * @param rowAndCol * The row and col of the shape being displayed. May be ignored. * @return The shape to be displayed. May be null (in which case the CA * graphics should use a default shape). * @see cellularAutomata.cellState.view.CellStateView#getAverageDisplayShape( * cellularAutomata.cellState.model.CellState[], int, int, Coordinate) */ public Shape getAverageDisplayShape(CellState[] states, int width, int height, Coordinate rowAndCol) { // the shape we will return Shape arrow = null; if(states != null) { // get the average vector double x = 0; double y = 0; for(int i = 0; i < states.length; i++) { // get the end point of the vector/arrow Point2D.Double endPoint = getLineCoordinates( (IntegerVectorState) states[i], width); x += endPoint.x; y += endPoint.y; } x /= states.length; y /= states.length; arrow = Arrow.createArrow(0.0, 0.0, x, y); } return arrow; } /** * Get a color for the arrows. * * @param state * The cell state that will be displayed. * @param numStates * If relevant, the number of possible states (which may not be * the same as the currently active number of states) -- may be * null which indicates that the number of states is inapplicable * or that the currently active number of states should be used. * (See for example, createProbabilityChoosers() method in * InitialStatesPanel class.) * @param rowAndCol * The row and col of the cell being displayed. May be ignored. * @return The color to be displayed. */ public Color getColor(CellState state, Integer numStates, Coordinate rowAndCol) { return ColorScheme.FILLED_COLOR; } /** * Creates a two-dimensional vector from the state array (of length N). This * is not the normal way of mapping arrays to vectors, but this classes' * array has to be meaningful in two dimensions (not N dimensions for an * N-dimensional array). Assumes that each array position is a vector of the * given magnitude (the array value). The vector points in a direction that * increases by 360/N degrees for each index. Each of these vectors are * summed together. <br> * Child classes should override this method if they need different * graphics. In fact this code assumes that the first coordinate of the * vector corresponds to a direction along the x-axis. This may not be the * case for a child class (such as the hexagonal lattice gas which assumes * that the first index points to the neighbor in the northwest direction.). * * @param state * The cell state that will be displayed. * @param width * The width of the rectangle that bounds this Shape. May be * ignored. * @param height * The height of the rectangle that bounds this Shape. May be * ignored. * @param rowAndCol * The row and col of the shape being displayed. May be ignored. * @return The vector to be displayed. May be null (in which case the CA * graphics should use a default shape). */ public Shape getDisplayShape(CellState state, int width, int height, Coordinate rowAndCol) { // Each array index is a vector with a magnitude given by the array // value. Get the end point of the vector/arrow Point2D.Double endPoint = getLineCoordinates( (IntegerVectorState) state, width); // create the vector/arrow shape Shape arrow = Arrow.createArrow(0.0, 0.0, endPoint.x, endPoint.y); return arrow; } }
{ "content_hash": "025cb407385308aaef242c8534e5bf8f", "timestamp": "", "source": "github", "line_count": 195, "max_line_length": 78, "avg_line_length": 36.35897435897436, "alnum_prop": 0.6702397743300423, "repo_name": "KEOpenSource/CAExplorer", "id": "a34738b37dfd93cad3a73c81fe68d3dd7a8c1147", "size": "7953", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cellularAutomata/cellState/view/IntegerVectorArrowView.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1420" }, { "name": "Java", "bytes": "5802939" } ], "symlink_target": "" }
package armcompute_test import ( "context" "log" "time" "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/sdk/azidentity" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v4" ) // Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2022-08-01/examples/virtualMachineScaleSetExamples/VirtualMachineScaleSetVMs_Reimage_MaximumSet_Gen.json func ExampleVirtualMachineScaleSetVMsClient_BeginReimage_virtualMachineScaleSetVMsReimageMaximumSetGen() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() client, err := armcompute.NewVirtualMachineScaleSetVMsClient("{subscription-id}", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } poller, err := client.BeginReimage(ctx, "rgcompute", "aaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaa", &armcompute.VirtualMachineScaleSetVMsClientBeginReimageOptions{VMScaleSetVMReimageInput: &armcompute.VirtualMachineScaleSetVMReimageParameters{ TempDisk: to.Ptr(true), }, }) if err != nil { log.Fatalf("failed to finish the request: %v", err) } _, err = poller.PollUntilDone(ctx, nil) if err != nil { log.Fatalf("failed to pull the result: %v", err) } } // Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2022-08-01/examples/virtualMachineScaleSetExamples/VirtualMachineScaleSetVMs_Reimage_MinimumSet_Gen.json func ExampleVirtualMachineScaleSetVMsClient_BeginReimage_virtualMachineScaleSetVMsReimageMinimumSetGen() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() client, err := armcompute.NewVirtualMachineScaleSetVMsClient("{subscription-id}", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } poller, err := client.BeginReimage(ctx, "rgcompute", "aaaaaaa", "aaaaaaaaaaaaa", &armcompute.VirtualMachineScaleSetVMsClientBeginReimageOptions{VMScaleSetVMReimageInput: nil}) if err != nil { log.Fatalf("failed to finish the request: %v", err) } _, err = poller.PollUntilDone(ctx, nil) if err != nil { log.Fatalf("failed to pull the result: %v", err) } } // Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2022-08-01/examples/virtualMachineScaleSetExamples/VirtualMachineScaleSetVMs_ReimageAll_MaximumSet_Gen.json func ExampleVirtualMachineScaleSetVMsClient_BeginReimageAll_virtualMachineScaleSetVMsReimageAllMaximumSetGen() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() client, err := armcompute.NewVirtualMachineScaleSetVMsClient("{subscription-id}", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } poller, err := client.BeginReimageAll(ctx, "rgcompute", "aaaaaaaaaaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaaaaa", nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) } _, err = poller.PollUntilDone(ctx, nil) if err != nil { log.Fatalf("failed to pull the result: %v", err) } } // Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2022-08-01/examples/virtualMachineScaleSetExamples/VirtualMachineScaleSetVMs_ReimageAll_MinimumSet_Gen.json func ExampleVirtualMachineScaleSetVMsClient_BeginReimageAll_virtualMachineScaleSetVMsReimageAllMinimumSetGen() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() client, err := armcompute.NewVirtualMachineScaleSetVMsClient("{subscription-id}", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } poller, err := client.BeginReimageAll(ctx, "rgcompute", "aaaaaaaaaaaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaaaaaaaaaaaaaa", nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) } _, err = poller.PollUntilDone(ctx, nil) if err != nil { log.Fatalf("failed to pull the result: %v", err) } } // Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2022-08-01/examples/virtualMachineScaleSetExamples/VirtualMachineScaleSetVMs_Deallocate_MaximumSet_Gen.json func ExampleVirtualMachineScaleSetVMsClient_BeginDeallocate_virtualMachineScaleSetVMsDeallocateMaximumSetGen() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() client, err := armcompute.NewVirtualMachineScaleSetVMsClient("{subscription-id}", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } poller, err := client.BeginDeallocate(ctx, "rgcompute", "aaaaaaaaaaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaaaaaaaa", nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) } _, err = poller.PollUntilDone(ctx, nil) if err != nil { log.Fatalf("failed to pull the result: %v", err) } } // Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2022-08-01/examples/virtualMachineScaleSetExamples/VirtualMachineScaleSetVMs_Deallocate_MinimumSet_Gen.json func ExampleVirtualMachineScaleSetVMsClient_BeginDeallocate_virtualMachineScaleSetVMsDeallocateMinimumSetGen() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() client, err := armcompute.NewVirtualMachineScaleSetVMsClient("{subscription-id}", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } poller, err := client.BeginDeallocate(ctx, "rgcompute", "aaaaaaaaaaaaaaaaaaaaaaaa", "aaaaaa", nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) } _, err = poller.PollUntilDone(ctx, nil) if err != nil { log.Fatalf("failed to pull the result: %v", err) } } // Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2022-08-01/examples/virtualMachineScaleSetExamples/VirtualMachineScaleSetVMs_Update_MaximumSet_Gen.json func ExampleVirtualMachineScaleSetVMsClient_BeginUpdate_virtualMachineScaleSetVMsUpdateMaximumSetGen() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() client, err := armcompute.NewVirtualMachineScaleSetVMsClient("{subscription-id}", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } poller, err := client.BeginUpdate(ctx, "rgcompute", "aaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaa", armcompute.VirtualMachineScaleSetVM{ Location: to.Ptr("westus"), Tags: map[string]*string{}, Plan: &armcompute.Plan{ Name: to.Ptr("aaaaaaaaaa"), Product: to.Ptr("aaaaaaaaaaaaaaaaaaaa"), PromotionCode: to.Ptr("aaaaaaaaaaaaaaaaaaaa"), Publisher: to.Ptr("aaaaaaaaaaaaaaaaaaaaaa"), }, Properties: &armcompute.VirtualMachineScaleSetVMProperties{ AdditionalCapabilities: &armcompute.AdditionalCapabilities{ HibernationEnabled: to.Ptr(true), UltraSSDEnabled: to.Ptr(true), }, AvailabilitySet: &armcompute.SubResource{ ID: to.Ptr("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}"), }, DiagnosticsProfile: &armcompute.DiagnosticsProfile{ BootDiagnostics: &armcompute.BootDiagnostics{ Enabled: to.Ptr(true), StorageURI: to.Ptr("aaaaaaaaaaaaa"), }, }, HardwareProfile: &armcompute.HardwareProfile{ VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesBasicA0), VMSizeProperties: &armcompute.VMSizeProperties{ VCPUsAvailable: to.Ptr[int32](9), VCPUsPerCore: to.Ptr[int32](12), }, }, InstanceView: &armcompute.VirtualMachineScaleSetVMInstanceView{ BootDiagnostics: &armcompute.BootDiagnosticsInstanceView{ Status: &armcompute.InstanceViewStatus{ Code: to.Ptr("aaaaaaaaaaaaaaaaaaaaaaa"), DisplayStatus: to.Ptr("aaaaaa"), Level: to.Ptr(armcompute.StatusLevelTypesInfo), Message: to.Ptr("a"), Time: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-11-30T12:58:26.522Z"); return t }()), }, }, Disks: []*armcompute.DiskInstanceView{ { Name: to.Ptr("aaaaaaaaaaa"), EncryptionSettings: []*armcompute.DiskEncryptionSettings{ { DiskEncryptionKey: &armcompute.KeyVaultSecretReference{ SecretURL: to.Ptr("aaaaaaaa"), SourceVault: &armcompute.SubResource{ ID: to.Ptr("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}"), }, }, Enabled: to.Ptr(true), KeyEncryptionKey: &armcompute.KeyVaultKeyReference{ KeyURL: to.Ptr("aaaaaaaaaaaaaa"), SourceVault: &armcompute.SubResource{ ID: to.Ptr("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}"), }, }, }}, Statuses: []*armcompute.InstanceViewStatus{ { Code: to.Ptr("aaaaaaaaaaaaaaaaaaaaaaa"), DisplayStatus: to.Ptr("aaaaaa"), Level: to.Ptr(armcompute.StatusLevelTypesInfo), Message: to.Ptr("a"), Time: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-11-30T12:58:26.522Z"); return t }()), }}, }}, MaintenanceRedeployStatus: &armcompute.MaintenanceRedeployStatus{ IsCustomerInitiatedMaintenanceAllowed: to.Ptr(true), LastOperationMessage: to.Ptr("aaaaaa"), LastOperationResultCode: to.Ptr(armcompute.MaintenanceOperationResultCodeTypesNone), MaintenanceWindowEndTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-11-30T12:58:26.531Z"); return t }()), MaintenanceWindowStartTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-11-30T12:58:26.531Z"); return t }()), PreMaintenanceWindowEndTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-11-30T12:58:26.531Z"); return t }()), PreMaintenanceWindowStartTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-11-30T12:58:26.531Z"); return t }()), }, PlacementGroupID: to.Ptr("aaa"), PlatformFaultDomain: to.Ptr[int32](14), PlatformUpdateDomain: to.Ptr[int32](23), RdpThumbPrint: to.Ptr("aaaaaaaaaaaaaaaaaaaaaaaaaaa"), Statuses: []*armcompute.InstanceViewStatus{ { Code: to.Ptr("aaaaaaaaaaaaaaaaaaaaaaa"), DisplayStatus: to.Ptr("aaaaaa"), Level: to.Ptr(armcompute.StatusLevelTypesInfo), Message: to.Ptr("a"), Time: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-11-30T12:58:26.522Z"); return t }()), }}, VMAgent: &armcompute.VirtualMachineAgentInstanceView{ ExtensionHandlers: []*armcompute.VirtualMachineExtensionHandlerInstanceView{ { Type: to.Ptr("aaaaaaaaaaaaa"), Status: &armcompute.InstanceViewStatus{ Code: to.Ptr("aaaaaaaaaaaaaaaaaaaaaaa"), DisplayStatus: to.Ptr("aaaaaa"), Level: to.Ptr(armcompute.StatusLevelTypesInfo), Message: to.Ptr("a"), Time: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-11-30T12:58:26.522Z"); return t }()), }, TypeHandlerVersion: to.Ptr("aaaaa"), }}, Statuses: []*armcompute.InstanceViewStatus{ { Code: to.Ptr("aaaaaaaaaaaaaaaaaaaaaaa"), DisplayStatus: to.Ptr("aaaaaa"), Level: to.Ptr(armcompute.StatusLevelTypesInfo), Message: to.Ptr("a"), Time: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-11-30T12:58:26.522Z"); return t }()), }}, VMAgentVersion: to.Ptr("aaaaaaaaaaaaaaaaaaaaaaa"), }, VMHealth: &armcompute.VirtualMachineHealthStatus{ Status: &armcompute.InstanceViewStatus{ Code: to.Ptr("aaaaaaaaaaaaaaaaaaaaaaa"), DisplayStatus: to.Ptr("aaaaaa"), Level: to.Ptr(armcompute.StatusLevelTypesInfo), Message: to.Ptr("a"), Time: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-11-30T12:58:26.522Z"); return t }()), }, }, Extensions: []*armcompute.VirtualMachineExtensionInstanceView{ { Name: to.Ptr("aaaaaaaaaaaaaaaaa"), Type: to.Ptr("aaaaaaaaa"), Statuses: []*armcompute.InstanceViewStatus{ { Code: to.Ptr("aaaaaaaaaaaaaaaaaaaaaaa"), DisplayStatus: to.Ptr("aaaaaa"), Level: to.Ptr(armcompute.StatusLevelTypesInfo), Message: to.Ptr("a"), Time: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-11-30T12:58:26.522Z"); return t }()), }}, Substatuses: []*armcompute.InstanceViewStatus{ { Code: to.Ptr("aaaaaaaaaaaaaaaaaaaaaaa"), DisplayStatus: to.Ptr("aaaaaa"), Level: to.Ptr(armcompute.StatusLevelTypesInfo), Message: to.Ptr("a"), Time: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2021-11-30T12:58:26.522Z"); return t }()), }}, TypeHandlerVersion: to.Ptr("aaaaaaaaaaaaaaaaaaaaaaaaaa"), }}, }, LicenseType: to.Ptr("aaaaaaaaaa"), NetworkProfile: &armcompute.NetworkProfile{ NetworkAPIVersion: to.Ptr(armcompute.NetworkAPIVersionTwoThousandTwenty1101), NetworkInterfaceConfigurations: []*armcompute.VirtualMachineNetworkInterfaceConfiguration{ { Name: to.Ptr("aaaaaaaaaaa"), Properties: &armcompute.VirtualMachineNetworkInterfaceConfigurationProperties{ DeleteOption: to.Ptr(armcompute.DeleteOptionsDelete), DNSSettings: &armcompute.VirtualMachineNetworkInterfaceDNSSettingsConfiguration{ DNSServers: []*string{ to.Ptr("aaaaaa")}, }, DscpConfiguration: &armcompute.SubResource{ ID: to.Ptr("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}"), }, EnableAcceleratedNetworking: to.Ptr(true), EnableFpga: to.Ptr(true), EnableIPForwarding: to.Ptr(true), IPConfigurations: []*armcompute.VirtualMachineNetworkInterfaceIPConfiguration{ { Name: to.Ptr("aa"), Properties: &armcompute.VirtualMachineNetworkInterfaceIPConfigurationProperties{ ApplicationGatewayBackendAddressPools: []*armcompute.SubResource{ { ID: to.Ptr("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}"), }}, ApplicationSecurityGroups: []*armcompute.SubResource{ { ID: to.Ptr("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}"), }}, LoadBalancerBackendAddressPools: []*armcompute.SubResource{ { ID: to.Ptr("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}"), }}, Primary: to.Ptr(true), PrivateIPAddressVersion: to.Ptr(armcompute.IPVersionsIPv4), PublicIPAddressConfiguration: &armcompute.VirtualMachinePublicIPAddressConfiguration{ Name: to.Ptr("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa"), Properties: &armcompute.VirtualMachinePublicIPAddressConfigurationProperties{ DeleteOption: to.Ptr(armcompute.DeleteOptionsDelete), DNSSettings: &armcompute.VirtualMachinePublicIPAddressDNSSettingsConfiguration{ DomainNameLabel: to.Ptr("aaaaaaaaaaaaaaaaaaaaaaaaa"), }, IdleTimeoutInMinutes: to.Ptr[int32](2), IPTags: []*armcompute.VirtualMachineIPTag{ { IPTagType: to.Ptr("aaaaaaaaaaaaaaaaaaaaaaaaa"), Tag: to.Ptr("aaaaaaaaaaaaaaaaaaaa"), }}, PublicIPAddressVersion: to.Ptr(armcompute.IPVersionsIPv4), PublicIPAllocationMethod: to.Ptr(armcompute.PublicIPAllocationMethodDynamic), PublicIPPrefix: &armcompute.SubResource{ ID: to.Ptr("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}"), }, }, SKU: &armcompute.PublicIPAddressSKU{ Name: to.Ptr(armcompute.PublicIPAddressSKUNameBasic), Tier: to.Ptr(armcompute.PublicIPAddressSKUTierRegional), }, }, Subnet: &armcompute.SubResource{ ID: to.Ptr("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}"), }, }, }}, NetworkSecurityGroup: &armcompute.SubResource{ ID: to.Ptr("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}"), }, Primary: to.Ptr(true), }, }}, NetworkInterfaces: []*armcompute.NetworkInterfaceReference{ { ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachineScaleSets/{vmss-name}/virtualMachines/0/networkInterfaces/vmsstestnetconfig5415"), Properties: &armcompute.NetworkInterfaceReferenceProperties{ DeleteOption: to.Ptr(armcompute.DeleteOptionsDelete), Primary: to.Ptr(true), }, }}, }, NetworkProfileConfiguration: &armcompute.VirtualMachineScaleSetVMNetworkProfileConfiguration{ NetworkInterfaceConfigurations: []*armcompute.VirtualMachineScaleSetNetworkConfiguration{ { ID: to.Ptr("aaaaaaaa"), Name: to.Ptr("vmsstestnetconfig5415"), Properties: &armcompute.VirtualMachineScaleSetNetworkConfigurationProperties{ DeleteOption: to.Ptr(armcompute.DeleteOptionsDelete), DNSSettings: &armcompute.VirtualMachineScaleSetNetworkConfigurationDNSSettings{ DNSServers: []*string{}, }, EnableAcceleratedNetworking: to.Ptr(true), EnableFpga: to.Ptr(true), EnableIPForwarding: to.Ptr(true), IPConfigurations: []*armcompute.VirtualMachineScaleSetIPConfiguration{ { ID: to.Ptr("aaaaaaaaa"), Name: to.Ptr("vmsstestnetconfig9693"), Properties: &armcompute.VirtualMachineScaleSetIPConfigurationProperties{ ApplicationGatewayBackendAddressPools: []*armcompute.SubResource{ { ID: to.Ptr("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}"), }}, ApplicationSecurityGroups: []*armcompute.SubResource{ { ID: to.Ptr("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}"), }}, LoadBalancerBackendAddressPools: []*armcompute.SubResource{ { ID: to.Ptr("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}"), }}, LoadBalancerInboundNatPools: []*armcompute.SubResource{ { ID: to.Ptr("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}"), }}, Primary: to.Ptr(true), PrivateIPAddressVersion: to.Ptr(armcompute.IPVersionIPv4), PublicIPAddressConfiguration: &armcompute.VirtualMachineScaleSetPublicIPAddressConfiguration{ Name: to.Ptr("aaaaaaaaaaaaaaaaaa"), Properties: &armcompute.VirtualMachineScaleSetPublicIPAddressConfigurationProperties{ DeleteOption: to.Ptr(armcompute.DeleteOptionsDelete), DNSSettings: &armcompute.VirtualMachineScaleSetPublicIPAddressConfigurationDNSSettings{ DomainNameLabel: to.Ptr("aaaaaaaaaaaaaaaaaa"), }, IdleTimeoutInMinutes: to.Ptr[int32](18), IPTags: []*armcompute.VirtualMachineScaleSetIPTag{ { IPTagType: to.Ptr("aaaaaaa"), Tag: to.Ptr("aaaaaaaaaaaaaaaaaaaaaaaaaaa"), }}, PublicIPAddressVersion: to.Ptr(armcompute.IPVersionIPv4), PublicIPPrefix: &armcompute.SubResource{ ID: to.Ptr("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}"), }, }, SKU: &armcompute.PublicIPAddressSKU{ Name: to.Ptr(armcompute.PublicIPAddressSKUNameBasic), Tier: to.Ptr(armcompute.PublicIPAddressSKUTierRegional), }, }, Subnet: &armcompute.APIEntityReference{ ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/virtualNetworks/vn4071/subnets/sn5503"), }, }, }}, NetworkSecurityGroup: &armcompute.SubResource{ ID: to.Ptr("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}"), }, Primary: to.Ptr(true), }, }}, }, OSProfile: &armcompute.OSProfile{ AdminPassword: to.Ptr("aaaaaaaaaaaaaaaa"), AdminUsername: to.Ptr("Foo12"), AllowExtensionOperations: to.Ptr(true), ComputerName: to.Ptr("test000000"), CustomData: to.Ptr("aaaa"), LinuxConfiguration: &armcompute.LinuxConfiguration{ DisablePasswordAuthentication: to.Ptr(true), PatchSettings: &armcompute.LinuxPatchSettings{ AssessmentMode: to.Ptr(armcompute.LinuxPatchAssessmentModeImageDefault), PatchMode: to.Ptr(armcompute.LinuxVMGuestPatchModeImageDefault), }, ProvisionVMAgent: to.Ptr(true), SSH: &armcompute.SSHConfiguration{ PublicKeys: []*armcompute.SSHPublicKey{ { Path: to.Ptr("aaa"), KeyData: to.Ptr("aaaaaa"), }}, }, }, RequireGuestProvisionSignal: to.Ptr(true), Secrets: []*armcompute.VaultSecretGroup{}, WindowsConfiguration: &armcompute.WindowsConfiguration{ AdditionalUnattendContent: []*armcompute.AdditionalUnattendContent{ { ComponentName: to.Ptr("Microsoft-Windows-Shell-Setup"), Content: to.Ptr("aaaaaaaaaaaaaaaaaaaa"), PassName: to.Ptr("OobeSystem"), SettingName: to.Ptr(armcompute.SettingNamesAutoLogon), }}, EnableAutomaticUpdates: to.Ptr(true), PatchSettings: &armcompute.PatchSettings{ AssessmentMode: to.Ptr(armcompute.WindowsPatchAssessmentModeImageDefault), EnableHotpatching: to.Ptr(true), PatchMode: to.Ptr(armcompute.WindowsVMGuestPatchModeManual), }, ProvisionVMAgent: to.Ptr(true), TimeZone: to.Ptr("aaaaaaaaaaaaaaaaaaaaaaaaaaa"), WinRM: &armcompute.WinRMConfiguration{ Listeners: []*armcompute.WinRMListener{ { CertificateURL: to.Ptr("aaaaaaaaaaaaaaaaaaaaaa"), Protocol: to.Ptr(armcompute.ProtocolTypesHTTP), }}, }, }, }, ProtectionPolicy: &armcompute.VirtualMachineScaleSetVMProtectionPolicy{ ProtectFromScaleIn: to.Ptr(true), ProtectFromScaleSetActions: to.Ptr(true), }, SecurityProfile: &armcompute.SecurityProfile{ EncryptionAtHost: to.Ptr(true), SecurityType: to.Ptr(armcompute.SecurityTypesTrustedLaunch), UefiSettings: &armcompute.UefiSettings{ SecureBootEnabled: to.Ptr(true), VTpmEnabled: to.Ptr(true), }, }, StorageProfile: &armcompute.StorageProfile{ DataDisks: []*armcompute.DataDisk{ { Name: to.Ptr("vmss3176_vmss3176_0_disk2_6c4f554bdafa49baa780eb2d128ff39d"), Caching: to.Ptr(armcompute.CachingTypesNone), CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesEmpty), DeleteOption: to.Ptr(armcompute.DiskDeleteOptionTypesDelete), DetachOption: to.Ptr(armcompute.DiskDetachOptionTypesForceDetach), DiskSizeGB: to.Ptr[int32](128), Image: &armcompute.VirtualHardDisk{ URI: to.Ptr("https://{storageAccountName}.blob.core.windows.net/{containerName}/{vhdName}.vhd"), }, Lun: to.Ptr[int32](1), ManagedDisk: &armcompute.ManagedDiskParameters{ ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/vmss3176_vmss3176_0_disk2_6c4f554bdafa49baa780eb2d128ff39d"), DiskEncryptionSet: &armcompute.DiskEncryptionSetParameters{ ID: to.Ptr("aaaaaaaaaaaa"), }, StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS), }, ToBeDetached: to.Ptr(true), Vhd: &armcompute.VirtualHardDisk{ URI: to.Ptr("https://{storageAccountName}.blob.core.windows.net/{containerName}/{vhdName}.vhd"), }, WriteAcceleratorEnabled: to.Ptr(true), }}, ImageReference: &armcompute.ImageReference{ ID: to.Ptr("a"), Offer: to.Ptr("WindowsServer"), Publisher: to.Ptr("MicrosoftWindowsServer"), SharedGalleryImageID: to.Ptr("aaaaaaaaaaaaaaaaaaaa"), SKU: to.Ptr("2012-R2-Datacenter"), Version: to.Ptr("4.127.20180315"), }, OSDisk: &armcompute.OSDisk{ Name: to.Ptr("vmss3176_vmss3176_0_OsDisk_1_6d72b805e50e4de6830303c5055077fc"), Caching: to.Ptr(armcompute.CachingTypesNone), CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage), DeleteOption: to.Ptr(armcompute.DiskDeleteOptionTypesDelete), DiffDiskSettings: &armcompute.DiffDiskSettings{ Option: to.Ptr(armcompute.DiffDiskOptionsLocal), Placement: to.Ptr(armcompute.DiffDiskPlacementCacheDisk), }, DiskSizeGB: to.Ptr[int32](127), EncryptionSettings: &armcompute.DiskEncryptionSettings{ DiskEncryptionKey: &armcompute.KeyVaultSecretReference{ SecretURL: to.Ptr("aaaaaaaa"), SourceVault: &armcompute.SubResource{ ID: to.Ptr("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}"), }, }, Enabled: to.Ptr(true), KeyEncryptionKey: &armcompute.KeyVaultKeyReference{ KeyURL: to.Ptr("aaaaaaaaaaaaaa"), SourceVault: &armcompute.SubResource{ ID: to.Ptr("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}"), }, }, }, Image: &armcompute.VirtualHardDisk{ URI: to.Ptr("https://{storageAccountName}.blob.core.windows.net/{containerName}/{vhdName}.vhd"), }, ManagedDisk: &armcompute.ManagedDiskParameters{ ID: to.Ptr("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/vmss3176_vmss3176_0_OsDisk_1_6d72b805e50e4de6830303c5055077fc"), DiskEncryptionSet: &armcompute.DiskEncryptionSetParameters{ ID: to.Ptr("aaaaaaaaaaaa"), }, StorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS), }, OSType: to.Ptr(armcompute.OperatingSystemTypesWindows), Vhd: &armcompute.VirtualHardDisk{ URI: to.Ptr("https://{storageAccountName}.blob.core.windows.net/{containerName}/{vhdName}.vhd"), }, WriteAcceleratorEnabled: to.Ptr(true), }, }, UserData: to.Ptr("RXhhbXBsZSBVc2VyRGF0YQ=="), }, SKU: &armcompute.SKU{ Name: to.Ptr("Classic"), Capacity: to.Ptr[int64](29), Tier: to.Ptr("aaaaaaaaaaaaaa"), }, }, nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) } res, err := poller.PollUntilDone(ctx, nil) if err != nil { log.Fatalf("failed to pull the result: %v", err) } // TODO: use response item _ = res } // Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2022-08-01/examples/virtualMachineScaleSetExamples/VirtualMachineScaleSetVMs_Update_MinimumSet_Gen.json func ExampleVirtualMachineScaleSetVMsClient_BeginUpdate_virtualMachineScaleSetVMsUpdateMinimumSetGen() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() client, err := armcompute.NewVirtualMachineScaleSetVMsClient("{subscription-id}", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } poller, err := client.BeginUpdate(ctx, "rgcompute", "aaaaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaaaaaa", armcompute.VirtualMachineScaleSetVM{ Location: to.Ptr("westus"), }, nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) } res, err := poller.PollUntilDone(ctx, nil) if err != nil { log.Fatalf("failed to pull the result: %v", err) } // TODO: use response item _ = res } // Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2022-08-01/examples/virtualMachineScaleSetExamples/VirtualMachineScaleSetVM_Delete_Force.json func ExampleVirtualMachineScaleSetVMsClient_BeginDelete() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() client, err := armcompute.NewVirtualMachineScaleSetVMsClient("{subscription-id}", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } poller, err := client.BeginDelete(ctx, "myResourceGroup", "myvmScaleSet", "0", &armcompute.VirtualMachineScaleSetVMsClientBeginDeleteOptions{ForceDeletion: to.Ptr(true)}) if err != nil { log.Fatalf("failed to finish the request: %v", err) } _, err = poller.PollUntilDone(ctx, nil) if err != nil { log.Fatalf("failed to pull the result: %v", err) } } // Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2022-08-01/examples/virtualMachineScaleSetExamples/VirtualMachineScaleSetVM_Get_WithUserData.json func ExampleVirtualMachineScaleSetVMsClient_Get_getVmScaleSetVmWithUserData() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() client, err := armcompute.NewVirtualMachineScaleSetVMsClient("{subscription-id}", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } res, err := client.Get(ctx, "myResourceGroup", "{vmss-name}", "0", &armcompute.VirtualMachineScaleSetVMsClientGetOptions{Expand: nil}) if err != nil { log.Fatalf("failed to finish the request: %v", err) } // TODO: use response item _ = res } // Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2022-08-01/examples/virtualMachineScaleSetExamples/VirtualMachineScaleSetVM_Get_WithVMSizeProperties.json func ExampleVirtualMachineScaleSetVMsClient_Get_getVmScaleSetVmWithVmSizeProperties() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() client, err := armcompute.NewVirtualMachineScaleSetVMsClient("{subscription-id}", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } res, err := client.Get(ctx, "myResourceGroup", "{vmss-name}", "0", &armcompute.VirtualMachineScaleSetVMsClientGetOptions{Expand: nil}) if err != nil { log.Fatalf("failed to finish the request: %v", err) } // TODO: use response item _ = res } // Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2022-08-01/examples/virtualMachineScaleSetExamples/VirtualMachineScaleSetVM_Get_InstanceViewAutoPlacedOnDedicatedHostGroup.json func ExampleVirtualMachineScaleSetVMsClient_GetInstanceView() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() client, err := armcompute.NewVirtualMachineScaleSetVMsClient("{subscription-id}", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } res, err := client.GetInstanceView(ctx, "myResourceGroup", "myVirtualMachineScaleSet", "0", nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) } // TODO: use response item _ = res } // Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2022-08-01/examples/virtualMachineScaleSetExamples/VirtualMachineScaleSetVMs_List_MaximumSet_Gen.json func ExampleVirtualMachineScaleSetVMsClient_NewListPager_virtualMachineScaleSetVMsListMaximumSetGen() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() client, err := armcompute.NewVirtualMachineScaleSetVMsClient("{subscription-id}", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } pager := client.NewListPager("rgcompute", "aaaaaaaaaaaaaaaaaaaaaa", &armcompute.VirtualMachineScaleSetVMsClientListOptions{Filter: to.Ptr("aaaaaaaaaaaaaa"), Select: to.Ptr("aaaaaaaaaaaaaaaaaaaaa"), Expand: to.Ptr("aaaaaaaaaaaaa"), }) for pager.More() { nextResult, err := pager.NextPage(ctx) if err != nil { log.Fatalf("failed to advance page: %v", err) } for _, v := range nextResult.Value { // TODO: use page item _ = v } } } // Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2022-08-01/examples/virtualMachineScaleSetExamples/VirtualMachineScaleSetVMs_List_MinimumSet_Gen.json func ExampleVirtualMachineScaleSetVMsClient_NewListPager_virtualMachineScaleSetVMsListMinimumSetGen() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() client, err := armcompute.NewVirtualMachineScaleSetVMsClient("{subscription-id}", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } pager := client.NewListPager("rgcompute", "aaaaaaaaaaaaaaaaaaaaaaaaaaaa", &armcompute.VirtualMachineScaleSetVMsClientListOptions{Filter: nil, Select: nil, Expand: nil, }) for pager.More() { nextResult, err := pager.NextPage(ctx) if err != nil { log.Fatalf("failed to advance page: %v", err) } for _, v := range nextResult.Value { // TODO: use page item _ = v } } } // Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2022-08-01/examples/virtualMachineScaleSetExamples/VirtualMachineScaleSetVMs_PowerOff_MaximumSet_Gen.json func ExampleVirtualMachineScaleSetVMsClient_BeginPowerOff_virtualMachineScaleSetVMsPowerOffMaximumSetGen() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() client, err := armcompute.NewVirtualMachineScaleSetVMsClient("{subscription-id}", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } poller, err := client.BeginPowerOff(ctx, "rgcompute", "aaaaaa", "aaaaaaaaa", &armcompute.VirtualMachineScaleSetVMsClientBeginPowerOffOptions{SkipShutdown: to.Ptr(true)}) if err != nil { log.Fatalf("failed to finish the request: %v", err) } _, err = poller.PollUntilDone(ctx, nil) if err != nil { log.Fatalf("failed to pull the result: %v", err) } } // Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2022-08-01/examples/virtualMachineScaleSetExamples/VirtualMachineScaleSetVMs_PowerOff_MinimumSet_Gen.json func ExampleVirtualMachineScaleSetVMsClient_BeginPowerOff_virtualMachineScaleSetVMsPowerOffMinimumSetGen() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() client, err := armcompute.NewVirtualMachineScaleSetVMsClient("{subscription-id}", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } poller, err := client.BeginPowerOff(ctx, "rgcompute", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaaaaaaaa", &armcompute.VirtualMachineScaleSetVMsClientBeginPowerOffOptions{SkipShutdown: nil}) if err != nil { log.Fatalf("failed to finish the request: %v", err) } _, err = poller.PollUntilDone(ctx, nil) if err != nil { log.Fatalf("failed to pull the result: %v", err) } } // Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2022-08-01/examples/virtualMachineScaleSetExamples/VirtualMachineScaleSetVMs_Restart_MaximumSet_Gen.json func ExampleVirtualMachineScaleSetVMsClient_BeginRestart_virtualMachineScaleSetVMsRestartMaximumSetGen() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() client, err := armcompute.NewVirtualMachineScaleSetVMsClient("{subscription-id}", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } poller, err := client.BeginRestart(ctx, "rgcompute", "aa", "aaaaaaaaaaaaaaaaa", nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) } _, err = poller.PollUntilDone(ctx, nil) if err != nil { log.Fatalf("failed to pull the result: %v", err) } } // Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2022-08-01/examples/virtualMachineScaleSetExamples/VirtualMachineScaleSetVMs_Restart_MinimumSet_Gen.json func ExampleVirtualMachineScaleSetVMsClient_BeginRestart_virtualMachineScaleSetVMsRestartMinimumSetGen() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() client, err := armcompute.NewVirtualMachineScaleSetVMsClient("{subscription-id}", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } poller, err := client.BeginRestart(ctx, "rgcompute", "aaaaaaaaaaaa", "aaaaaa", nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) } _, err = poller.PollUntilDone(ctx, nil) if err != nil { log.Fatalf("failed to pull the result: %v", err) } } // Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2022-08-01/examples/virtualMachineScaleSetExamples/VirtualMachineScaleSetVMs_Start_MaximumSet_Gen.json func ExampleVirtualMachineScaleSetVMsClient_BeginStart_virtualMachineScaleSetVMsStartMaximumSetGen() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() client, err := armcompute.NewVirtualMachineScaleSetVMsClient("{subscription-id}", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } poller, err := client.BeginStart(ctx, "rgcompute", "aaaaaaaaaaaaaa", "aaaaaaaaaaaaa", nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) } _, err = poller.PollUntilDone(ctx, nil) if err != nil { log.Fatalf("failed to pull the result: %v", err) } } // Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2022-08-01/examples/virtualMachineScaleSetExamples/VirtualMachineScaleSetVMs_Start_MinimumSet_Gen.json func ExampleVirtualMachineScaleSetVMsClient_BeginStart_virtualMachineScaleSetVMsStartMinimumSetGen() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() client, err := armcompute.NewVirtualMachineScaleSetVMsClient("{subscription-id}", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } poller, err := client.BeginStart(ctx, "rgcompute", "aaaaaaaaaaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaaa", nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) } _, err = poller.PollUntilDone(ctx, nil) if err != nil { log.Fatalf("failed to pull the result: %v", err) } } // Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2022-08-01/examples/virtualMachineScaleSetExamples/VirtualMachineScaleSetVMs_Redeploy_MaximumSet_Gen.json func ExampleVirtualMachineScaleSetVMsClient_BeginRedeploy_virtualMachineScaleSetVMsRedeployMaximumSetGen() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() client, err := armcompute.NewVirtualMachineScaleSetVMsClient("{subscription-id}", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } poller, err := client.BeginRedeploy(ctx, "rgcompute", "aaaaaaaaaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaa", nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) } _, err = poller.PollUntilDone(ctx, nil) if err != nil { log.Fatalf("failed to pull the result: %v", err) } } // Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2022-08-01/examples/virtualMachineScaleSetExamples/VirtualMachineScaleSetVMs_Redeploy_MinimumSet_Gen.json func ExampleVirtualMachineScaleSetVMsClient_BeginRedeploy_virtualMachineScaleSetVMsRedeployMinimumSetGen() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() client, err := armcompute.NewVirtualMachineScaleSetVMsClient("{subscription-id}", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } poller, err := client.BeginRedeploy(ctx, "rgcompute", "aaaaaaaaaaaaa", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaa", nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) } _, err = poller.PollUntilDone(ctx, nil) if err != nil { log.Fatalf("failed to pull the result: %v", err) } } // Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2022-08-01/examples/virtualMachineScaleSetExamples/VirtualMachineScaleSetVM_RetrieveBootDiagnosticsData.json func ExampleVirtualMachineScaleSetVMsClient_RetrieveBootDiagnosticsData() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() client, err := armcompute.NewVirtualMachineScaleSetVMsClient("{subscription-id}", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } res, err := client.RetrieveBootDiagnosticsData(ctx, "ResourceGroup", "myvmScaleSet", "0", &armcompute.VirtualMachineScaleSetVMsClientRetrieveBootDiagnosticsDataOptions{SasURIExpirationTimeInMinutes: to.Ptr[int32](60)}) if err != nil { log.Fatalf("failed to finish the request: %v", err) } // TODO: use response item _ = res } // Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2022-08-01/examples/virtualMachineScaleSetExamples/VirtualMachineScaleSetVMs_PerformMaintenance_MaximumSet_Gen.json func ExampleVirtualMachineScaleSetVMsClient_BeginPerformMaintenance_virtualMachineScaleSetVMsPerformMaintenanceMaximumSetGen() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() client, err := armcompute.NewVirtualMachineScaleSetVMsClient("{subscription-id}", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } poller, err := client.BeginPerformMaintenance(ctx, "rgcompute", "aaaaaaaaaaaaaa", "aaaaaaaaaaaa", nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) } _, err = poller.PollUntilDone(ctx, nil) if err != nil { log.Fatalf("failed to pull the result: %v", err) } } // Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2022-08-01/examples/virtualMachineScaleSetExamples/VirtualMachineScaleSetVMs_PerformMaintenance_MinimumSet_Gen.json func ExampleVirtualMachineScaleSetVMsClient_BeginPerformMaintenance_virtualMachineScaleSetVMsPerformMaintenanceMinimumSetGen() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() client, err := armcompute.NewVirtualMachineScaleSetVMsClient("{subscription-id}", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } poller, err := client.BeginPerformMaintenance(ctx, "rgcompute", "aaaaaaaaaa", "aaaa", nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) } _, err = poller.PollUntilDone(ctx, nil) if err != nil { log.Fatalf("failed to pull the result: %v", err) } } // Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2022-08-01/examples/virtualMachineScaleSetExamples/VirtualMachineScaleSetVM_SimulateEviction.json func ExampleVirtualMachineScaleSetVMsClient_SimulateEviction() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() client, err := armcompute.NewVirtualMachineScaleSetVMsClient("{subscription-id}", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } _, err = client.SimulateEviction(ctx, "ResourceGroup", "VmScaleSetName", "InstanceId", nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) } } // Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2022-08-01/examples/runCommandExamples/VirtualMachineScaleSetVMRunCommand.json func ExampleVirtualMachineScaleSetVMsClient_BeginRunCommand() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() client, err := armcompute.NewVirtualMachineScaleSetVMsClient("{subscription-id}", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } poller, err := client.BeginRunCommand(ctx, "myResourceGroup", "myVirtualMachineScaleSet", "0", armcompute.RunCommandInput{ CommandID: to.Ptr("RunPowerShellScript"), Script: []*string{ to.Ptr("Write-Host Hello World!")}, }, nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) } res, err := poller.PollUntilDone(ctx, nil) if err != nil { log.Fatalf("failed to pull the result: %v", err) } // TODO: use response item _ = res }
{ "content_hash": "275226fc0d9eddbc910e2018caef4b19", "timestamp": "", "source": "github", "line_count": 1032, "max_line_length": 295, "avg_line_length": 47.998062015503876, "alnum_prop": 0.7164977591149514, "repo_name": "Azure/azure-sdk-for-go", "id": "4d0f58e10fa6fdaacd78ce0070ca4083358a9e4e", "size": "49873", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "sdk/resourcemanager/compute/armcompute/virtualmachinescalesetvms_client_example_test.go", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1629" }, { "name": "Bicep", "bytes": "8394" }, { "name": "CSS", "bytes": "6089" }, { "name": "Dockerfile", "bytes": "1435" }, { "name": "Go", "bytes": "5463500" }, { "name": "HTML", "bytes": "8933" }, { "name": "JavaScript", "bytes": "8137" }, { "name": "PowerShell", "bytes": "504494" }, { "name": "Shell", "bytes": "3893" }, { "name": "Smarty", "bytes": "1723" } ], "symlink_target": "" }
define(function(require, exports, module){ var StatusBar = brackets.getModule('widgets/StatusBar'), MainViewManager = brackets.getModule('view/MainViewManager'), Dialogs = brackets.getModule('widgets/Dialogs'), ExtensionUtils = brackets.getModule('utils/ExtensionUtils'), ThemeManager = brackets.getModule('view/ThemeManager'), indicatorId = 'indicator-dnbard-raml', dialogId = 'dialog-dnbard-raml', modulePath = ExtensionUtils.getModulePath(module), indicatorDOM = $('<div id="' + indicatorId + '">View RAML</div>'), ramlRegex = /\.raml$/i, currentFile = null; ExtensionUtils.loadStyleSheet(module, 'styles.css'); StatusBar.addIndicator(indicatorId, indicatorDOM, true); indicatorDOM.click(function(){ if (currentFile === null){ return console.error('File entity are null'); } if (ThemeManager.getCurrentTheme().dark){ Dialogs.showModalDialog(dialogId, 'RAML', '<iframe src="' + modulePath + 'api-console/index-dark.html"></iframe>', "", [], true); } else { Dialogs.showModalDialog(dialogId, 'RAML', '<iframe src="' + modulePath + 'api-console/index.html"></iframe>', "", [], true); } window.addEventListener("message", function(event){ if (event.data === "RAMLReady"){ var ramlIframe = $('.dialog-dnbard-raml iframe')[0].contentWindow; currentFile.read(function(err, fileData){ ramlIframe.postMessage(fileData, '*'); }); } }); }); function toggleIndicator(isVisibleState){ StatusBar.updateIndicator(indicatorId, isVisibleState); } MainViewManager.on('currentFileChange', function(event, file){ toggleIndicator(!!ramlRegex.test(file._path)); currentFile = file; }); });
{ "content_hash": "b4e5107320460d920926f9a5a725a7a0", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 141, "avg_line_length": 40.46808510638298, "alnum_prop": 0.6114616193480547, "repo_name": "dnbard/brackets-raml", "id": "b88c0d5d78734baaf8bd5708d4e1036c3774935f", "size": "1902", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "main.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "233728" }, { "name": "HTML", "bytes": "3233" }, { "name": "JavaScript", "bytes": "3304980" } ], "symlink_target": "" }
from .sub_resource import SubResource class Probe(SubResource): """A load balancer probe. All required parameters must be populated in order to send to Azure. :param id: Resource Identifier. :type id: str :param load_balancing_rules: The load balancer rules that use this probe. :type load_balancing_rules: list[~azure.mgmt.network.v2015_06_15.models.SubResource] :param protocol: Required. The protocol of the end point. Possible values are: 'Http' or 'Tcp'. If 'Tcp' is specified, a received ACK is required for the probe to be successful. If 'Http' is specified, a 200 OK response from the specifies URI is required for the probe to be successful. Possible values include: 'Http', 'Tcp' :type protocol: str or ~azure.mgmt.network.v2015_06_15.models.ProbeProtocol :param port: Required. The port for communicating the probe. Possible values range from 1 to 65535, inclusive. :type port: int :param interval_in_seconds: The interval, in seconds, for how frequently to probe the endpoint for health status. Typically, the interval is slightly less than half the allocated timeout period (in seconds) which allows two full probes before taking the instance out of rotation. The default value is 15, the minimum value is 5. :type interval_in_seconds: int :param number_of_probes: The number of probes where if no response, will result in stopping further traffic from being delivered to the endpoint. This values allows endpoints to be taken out of rotation faster or slower than the typical times used in Azure. :type number_of_probes: int :param request_path: The URI used for requesting health status from the VM. Path is required if a protocol is set to http. Otherwise, it is not allowed. There is no default value. :type request_path: str :param provisioning_state: Gets the provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str :param name: Gets name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str """ _validation = { 'protocol': {'required': True}, 'port': {'required': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'load_balancing_rules': {'key': 'properties.loadBalancingRules', 'type': '[SubResource]'}, 'protocol': {'key': 'properties.protocol', 'type': 'str'}, 'port': {'key': 'properties.port', 'type': 'int'}, 'interval_in_seconds': {'key': 'properties.intervalInSeconds', 'type': 'int'}, 'number_of_probes': {'key': 'properties.numberOfProbes', 'type': 'int'}, 'request_path': {'key': 'properties.requestPath', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(Probe, self).__init__(**kwargs) self.load_balancing_rules = kwargs.get('load_balancing_rules', None) self.protocol = kwargs.get('protocol', None) self.port = kwargs.get('port', None) self.interval_in_seconds = kwargs.get('interval_in_seconds', None) self.number_of_probes = kwargs.get('number_of_probes', None) self.request_path = kwargs.get('request_path', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.name = kwargs.get('name', None) self.etag = kwargs.get('etag', None)
{ "content_hash": "84d6a125e2d8932d3b49c3c99b8da77d", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 98, "avg_line_length": 48.743589743589745, "alnum_prop": 0.6614939505523408, "repo_name": "lmazuel/azure-sdk-for-python", "id": "d59bc78e4c896b2ab3803838f0e6bf024e56b176", "size": "4276", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "azure-mgmt-network/azure/mgmt/network/v2015_06_15/models/probe.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "42572767" } ], "symlink_target": "" }
package natlab.tame.builtin.isComplexInfoProp.ast; import java.util.List; import natlab.tame.builtin.isComplexInfoProp.ArgICType; import natlab.tame.builtin.isComplexInfoProp.isComplexInfoPropMatch; import natlab.tame.valueanalysis.value.Value; public class ICTypeA extends ICType{ public ICTypeA() { } public String toString() { return "ANY"; } @Override public isComplexInfoPropMatch match(boolean isPatternSide, isComplexInfoPropMatch previousMatchResult, List<? extends Value<?>> argValues) { if(true==isPatternSide)//on the symbol on the LHS { /* * If the argument is any ( we do not know for sure if it is real or complex then increment * any but do not increment R or X. Consume the argument. save the complexity info and all other * info to previousmatch and return */ isComplexInfoPropMatch match = new isComplexInfoPropMatch(previousMatchResult); //if(null != argValues.get(previousMatchResult.getNumMatched())) if(argValues.size() > previousMatchResult.getNumMatched()) { Value<?> argument = argValues.get(previousMatchResult.getNumMatched());// get the value of argument // ArgICType isArgComplex = new ArgICType(argument); //returns -1=complex, 0=any, 1= real int isArgComplex = (new ArgICType()).getArgICType(argument); //int isArgComplex =0; //TODO - implement this method if (0 == isArgComplex || 1 == isArgComplex || -1 == isArgComplex) //i.e it is any { //mATCHED // set the attributes of match object //set values here and add to the match.consumeArg(); match.setLastMatchSucceed(true); match.setLastMatchICType("ANY"); match.incNumAargs(1); if(1 == isArgComplex) match.incNumRargs(1); if(-1 == isArgComplex) match.incNumXargs(1); // System.out.println("matched argument to ANY\n"); } else { match.setLastMatchSucceed(false); } } else { match.setError(true); } if (null == match.getLastMatchICType()) { match.setLastMatchSucceed(false); } return match; } else { //RHS isComplexInfoPropMatch match = new isComplexInfoPropMatch(previousMatchResult); if (match.getNumMatched() == argValues.size()) { //LHS matched match.loadOutput("ANY"); // System.out.println("ANY."); return match; } else { //match fail somewhere on LHS match.setError(true); return match; } } } }
{ "content_hash": "fb63cc2e02034ce2279e9133ddb0456a", "timestamp": "", "source": "github", "line_count": 99, "max_line_length": 103, "avg_line_length": 25.13131313131313, "alnum_prop": 0.667604501607717, "repo_name": "Sable/mclab-core", "id": "5de3097cf9d13fa0834851b9920ba937af5a98e9", "size": "2488", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "languages/Natlab/src/natlab/tame/builtin/isComplexInfoProp/ast/ICTypeA.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ActionScript", "bytes": "387" }, { "name": "Batchfile", "bytes": "559" }, { "name": "C", "bytes": "466526" }, { "name": "C++", "bytes": "19994" }, { "name": "CSS", "bytes": "3032" }, { "name": "Emacs Lisp", "bytes": "2535" }, { "name": "GAP", "bytes": "320936" }, { "name": "HTML", "bytes": "359828" }, { "name": "Java", "bytes": "5242198" }, { "name": "Lex", "bytes": "114133" }, { "name": "M4", "bytes": "3863" }, { "name": "Makefile", "bytes": "5969" }, { "name": "Matlab", "bytes": "1207" }, { "name": "OCaml", "bytes": "6276" }, { "name": "Objective-C", "bytes": "723006" }, { "name": "Python", "bytes": "569613" }, { "name": "Ruby", "bytes": "21165" }, { "name": "Shell", "bytes": "3574" }, { "name": "Smalltalk", "bytes": "417" }, { "name": "VimL", "bytes": "5978" }, { "name": "Yacc", "bytes": "3743" } ], "symlink_target": "" }
/*Please dont change it */ /*Common*/ .animation_results, .animation_results .x-panel-body { background-color: #dfe8f7; } .tryit_results, .tryit_results .x-panel-body { background-color: #dfe8f7; overflow: auto; } .center-exp { margin-left: auto; margin-right: auto; display: table; } /* Animation */ .animation-content { background-color: #dfe8f7; color: #696969; font-family: Verdana, Arial, helvetica, sans-serif;; font-size: 15px; width: 100%; } .animation-content .call, .animation-content .answer, .animation-content .output { font-weight: bold; padding: 10px; border: 2px dotted #a9a9a9; margin: 10px; color: black; text-align: center; letter-spacing: 1px; word-break: break-word; white-space: pre-wrap; } .animation-content .error { color: #de0202; border-color: #de0202; } .animation-content .explanation { font-family: Roboto, serif !important; font-size: 16px; font-weight: bold; text-align: center; padding: 5px; color: #294270; } .animation-content .explanation table { border-collapse: collapse; margin: 10px; } .animation-content .explanation table th, .animation-content .explanation table td{ font-family: Roboto, serif; color: #294270; padding: 2px; border: solid #294270 1px; text-align: center; font-size: 12px; font-weight: normal; } .animation-success { background: #EBEDED; } .animation-success div.result { background-repeat: no-repeat; height: 200px; width: 400px; margin: auto; } .animation-success div.result.norm-sign { background-image: url("http://checkio.s3.amazonaws.com/files/tasks/sucess_slide_norm.png"); } .animation-success div.result.win-sign { background-image: url("http://checkio.s3.amazonaws.com/files/tasks/sucess_slide_win.png"); } .animation-success div.result div { position: relative; font-size: 25px; color: #ffffff; } .animation-success div.result.norm-sign div { top: 55px; left: 25px; } .animation-success div.result.win-sign div { top: 30px; left: 25px; width: 200px; font-size: 25px; } .animation-success div.result.norm-sign .numbers { position: relative; top: 80px; left: 0; color: #55bbee; } .animation-success div.result.win-sign .numbers { position: relative; top: 53px; left: 17px; color: #55bbee; } .animation-success div.result .numbers th { width: 80px; text-align: center; font-size: 25px; } .animation-success div.result .numbers td { font-size: 10px; text-align: center; color: #003b70; } .animation-success div.result .numbers tr th span.ends { font-size: 15px; } .animation-success div.result * { font-family: Roboto, Arial, 'Open Sans', sans-serif; } .tryit-content { background-color: #dfe8f7; font-family: Verdana, Arial, helvetica, sans-serif; } .tryit-content .tool td { text-align: center; vertical-align: top; padding: 3px; } /*it for firefox*/ .tryit-content .tool tr:first-child td:last-child { height: 20%; } .tryit-content .checkio-result { font-size: 16px; text-align: center; color: #294270; width: 160px; } .tryit-content .btn { padding: 4px 6px; font-size: 14px; font-family: Verdana, Arial, helvetica, sans-serif;; font-weight: 500; line-height: 1.428571429; text-align: center; white-space: nowrap; vertical-align: middle; cursor: pointer; border: 1px solid transparent; border-radius: 4px; background-color: #8FC7ED; } .tryit-content .btn:focus { outline: thin dotted #333; outline: 5px auto -webkit-focus-ring-color; outline-offset: -2px; } .tryit-content .btn:hover, .tryit-content .btn:focus { text-decoration: none; background-color: #65A1CF; } .tryit-content .btn:active, .tryit-content .btn.active { outline: 0; -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.5); box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.5); } .tryit-content .btn.disabled, .tryit-content .btn[disabled], fieldset[disabled] .btn { pointer-events: none; cursor: default; opacity: 0.65; filter: alpha(opacity=65); -webkit-box-shadow: none; box-shadow: none; } .tryit-content input[type="text"], .tryit-content input[type="number"] { display: inline-block; padding: 4px 6px; font-size: 14px; line-height: 1.428571429; font-family: inherit; color: #294270; vertical-align: middle; background-color: #ffffff; border: 1px solid #cccccc; border-radius: 4px; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); -webkit-transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s; transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s; } .tryit-content input[type="text"]:focus, .tryit-content input[type="number"]:focus { border-color: rgba(82, 168, 236, 0.8); outline: 0; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6); } .tryit-content input[type="text"][disabled], .tryit-content input[type="number"][readonly] { cursor: not-allowed; background-color: #eeeeee; } /* Your CSS */ /* */
{ "content_hash": "d0c75878929d91ab9b51b040aa4b23fb", "timestamp": "", "source": "github", "line_count": 255, "max_line_length": 95, "avg_line_length": 21.215686274509803, "alnum_prop": 0.6497227356746765, "repo_name": "Bryukh-Checkio-Tasks/checkio-mission-pep8-break", "id": "8aeac5def54fa77678dae65c18ead662c27e1875", "size": "5410", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "editor/animation/init.css", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5410" }, { "name": "HTML", "bytes": "16806" }, { "name": "JavaScript", "bytes": "7444" }, { "name": "Python", "bytes": "82229" } ], "symlink_target": "" }
title: "Zero downtime deployments with Go and Kubernetes" date: 2018-08-06T19:40:55+01:00 url: "graceful-shutdown" pinned: true --- If you’re writing Go then you’re probably aware that graceful shutdown was added to the http package in 1.8. > The HTTP server also adds support for [graceful shutdown](https://golang.org/doc/go1.8#http_shutdown), allowing servers to minimize downtime by shutting down only after serving all requests that are in flight. — [Go 1.8 is released](https://blog.golang.org/go1.8) Similarly, If you’re using Kubernetes then I’m sure you’re aware of, and hopefully using rolling updates for your deployments. > Rolling updates incrementally replace your resource’s Pods with new ones, which are then scheduled on nodes with available resources. Rolling updates are designed to update your workloads without downtime. — [Performing Rolling Updates](https://cloud.google.com/kubernetes-engine/docs/how-to/updating-apps) However, you might not be sure how the two work together to ensure truly zero downtime deployments — I wasn’t! This is a quick guide to writing readiness and liveness probes in Go and how to configure them with a Kubernetes rolling update deployment. ## Getting started Let’s get started with a basic health check, to begin we’ll use it for both the readiness and liveness probes in Kubernetes. This was how I started writing services, and until you hit a significant amount of traffic, it’s probably fine. Here’s a sample Go app, using a [Chi router and middleware](https://github.com/go-chi/chi) as well as the deployment probe configuration. ```go package main import ( "net/http" "github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5/middleware" ) func main() { r := chi.NewRouter() r.Use(middleware.Heartbeat("/health")) r.Get("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Hello, World!")) }) http.ListenAndServe(":3000", r) } ``` ```yaml livenessProbe: httpGet: path: /health port: 80 readinessProbe: httpGet: path: /health port: 80 ``` This will work fine, but when performing a rolling update Kubernetes will send a `SIGTERM` signal to the process and the server will die. Any open connections will fail resulting in a bad experience for users ## Graceful shutdown There is fantastic documentation and example code for the `server.Shutdown` method on [godoc.org](https://golang.org/pkg/net/http/#Server.Shutdown). One thing to note here is that the example uses `os.Interrupt` as the shutdown signal. That’ll work when you run a server locally and hit `ctrl-C` to close it, but not on Kubernetes. Kubernetes sends a `SIGTERM` signal which is different. ```go package main import ( "context" "log" "net/http" "os" "os/signal" "syscall" ) func main() { var srv http.Server idleConnsClosed := make(chan struct{}) go func() { sigint := make(chan os.Signal, 1) // interrupt signal sent from terminal signal.Notify(sigint, os.Interrupt) // sigterm signal sent from kubernetes signal.Notify(sigint, syscall.SIGTERM) <-sigint // We received an interrupt signal, shut down. if err := srv.Shutdown(context.Background()); err != nil { // Error from closing listeners, or context timeout: log.Printf("HTTP server Shutdown: %v", err) } close(idleConnsClosed) }() if err := srv.ListenAndServe(); err != http.ErrServerClosed { // Error starting or closing listener: log.Printf("HTTP server ListenAndServe: %v", err) } <-idleConnsClosed } ``` Now, let’s look at how we integrate graceful shutdown with the two different Kubernetes probes. --- A quick primer on probes in Kubernetes: _Liveness_ indicates that the pod is running, if the liveness probe fails the pod will be restarted. _Readiness_ indicates that the pod is ready to receive traffic, when a pod is ready the load balancer will start sending traffic to it. --- Let’s go through the steps we want to happen during a rolling update. 1. Running pods are told to shut down via a SIGTERM signal 2. The readiness probes on those running pods should start failing as they are not accepting new traffic, but only closing any open connections 3. During this time new pods have started up and will be ready to receive traffic 4. Once all connections to old pods have been closed, the liveness probes should fail 5. The old pods are now completely shut down and assuming the rollout went well, all traffic should be going to new pods We’ll need to use two different types of probes to achieve this, an `httpGet` probe for readiness and a `command` for liveness. Think about it, once a Go application receives the `SIGTERM` signal it will no longer serve new traffic so any http health checks will fail, this is why the liveness check needs to be independent of the http server. The most common way to do this is by creating a file on disk when the process starts, and remove it when ending. The liveness check is then a simple `cat` command to check that the file exists. Here’s an example of how we would create the probe file before running the application, and remove it once it has completed. ```go package probe import "os" const liveFile = "/tmp/live" // Create will create a file for the liveness check. func Create() error { _, err := os.Create(liveFile) return err } // Remove will remove the file create for the liveness probe. func Remove() error { return os.Remove(liveFile) } // Exists checks if the file created for the liveness probe exists. func Exists() bool { if _, err := os.Stat(liveFile); err == nil { return true } return false } ``` ```go // Command defines the command-line interface for starting our aplication HTTP server. var Command = &cobra.Command{ Use: "app", Short: "Run the application", RunE: func(cmd *cobra.Command, args []string) error { var s app.Specification envconfig.MustProcess("", &s) if err := probe.Create(); err != nil { return fmt.Errorf("create probe: %w", err) } app.Run(s) if err := probe.Remove(); err != nil { return fmt.Errorf("remove probe: %w", err) } return nil }, } ``` I’ve hardcoded the location of the probe file here to simplify the example code, but don’t overlook this. You’ll need to make sure that you mount a [persistent volume](https://kubernetes.io/docs/concepts/storage/persistent-volumes/) to write to. I’d also suggest using the [`ioutil.TempFile`](https://golang.org/pkg/io/ioutil/#TempFile) method available in the Go standard library. Now… we need to update the deployment configuration to check for the existence of `/tmp/live`. ```yaml livenessProbe: exec: command: - cat - /tmp/live readinessProbe: httpGet: path: /health port: 80 ``` That _should_ be all you need, but I did run into an interesting problem. ## Debugging You might run into issues, like I did, where the pod got stuck in a restart loop. Once you’ve found the pod name, you can use the describe command to see what’s going on: ```sh kubectl describe pod my-application-789757d855-ptccl ``` In my case, I ran into a rather interesting error: ```sh Warning Unhealthy 16s (x7 over 1m) kubelet, gke-dev-cluster-2-dev-pool-2-b6567556-l83v Liveness probe failed: rpc error: code = 2 desc = oci runtime error: exec failed: container_linux.go:247: starting container process caused "exec: \"cat\": executable file not found in $PATH" ``` _That’s right, the container I was using didn’t have `cat` installed._ I’ve been using the [distroless container from Google](https://github.com/GoogleContainerTools/distroless) as a base image for my application containers. It has everything I need to run a Go binary and nothing else. This is fantastic because the containers I ship are tiny… build times are faster, deployments are faster and it reduces security risk. It’s great that I can ship 15mb containers, but… not so great when I can’t use basic utilities like `cat`. Rather than poking around in the container to see what else I could use, or use a different base image, I wrote a small sub-command in my Go application to handle this. You’ll notice a `probe.Exists` method in the `probe` package above, here’s what the liveness sub-command looks like: ```go package live import ( "os" "github.com/overhq/over-stories-api/pkg/probe" "github.com/spf13/cobra" ) // Command defines the command-line interface for our liveness probe. var Command = &cobra.Command{ Use: "live", Short: "Check if application is live", RunE: func(cmd *cobra.Command, args []string) error { if probe.Exists() { return nil } return fmt.Errof("probe does not exist") }, } ``` Calling the liveness check as a sub-command instead of using `cat` directly sorted out my problems, hopefully that helps if you run into a similar issue. --- I hope this post has provided some insight into how the graceful shutdown and rolling updates can work together to achieve truly zero downtime deployments. If you have any questions, thoughts or suggestions then I’d love to hear from you! _Further reading_ - [Kubernetes Container probes documentation](https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#container-probes) - [Go `server.Shutdown` documentation](https://golang.org/pkg/net/http/#Server.Shutdown) - [Performing Rolling Updates](https://cloud.google.com/kubernetes-engine/docs/how-to/updating-apps)
{ "content_hash": "f3b8a751b01857002d8501732dd0a98c", "timestamp": "", "source": "github", "line_count": 259, "max_line_length": 392, "avg_line_length": 36.196911196911195, "alnum_prop": 0.7410133333333333, "repo_name": "wayneashleyberry/wayne.cloud", "id": "71077b4fbd6af1082fac6b2cdca5a9128c0ee992", "size": "9451", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "content/posts/graceful-shutdown.md", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "5475" } ], "symlink_target": "" }
package http.client.response import play.api.libs.json.JsValue trait HttpResponse { val status: Int val headers: Seq[HttpHeader] val statusText: String val body: String val bodyAsBytes: Array[Byte] def json: JsValue }
{ "content_hash": "91ee7e883e5e32454e74ca6b5baa297a", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 33, "avg_line_length": 19.333333333333332, "alnum_prop": 0.75, "repo_name": "SocialOrra/social4s", "id": "408d8ff647dda584abf46a4387ac37f68a96186c", "size": "232", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "http-client/src/main/scala/http/client/response/HttpResponse.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Scala", "bytes": "109536" }, { "name": "Shell", "bytes": "16299" } ], "symlink_target": "" }
var Lab = require('lab'); var Hapi = require('hapi'); var cheerio = require('cheerio'); var Path = require('path'); var Inert = require('inert'); var Vision = require('vision'); // Declare internals var internals = { bootstrapServer: function (server, plugins, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } server.register([Inert, Vision].concat(plugins), options, function (err) { if (err) { return callback(err); } server.initialize(callback); }); } }; // Test shortcuts var lab = exports.lab = Lab.script(); var before = lab.before; var describe = lab.experiment; var it = lab.test; var expect = require('code').expect; describe('Registration', function() { it('should register', function(done) { var server = new Hapi.Server(); server.connection({ host: 'test' }); internals.bootstrapServer(server, require('../'), function() { var routes = server.table(); expect(routes).to.have.length(1); expect(routes[0].table).to.have.length(2); done(); }); }); it('should register with options', function(done) { var server = new Hapi.Server(); server.connection({ host: 'test' }); internals.bootstrapServer(server, { register: require('../'), options: { helpersPath: '.', cssPath: null, endpoint: '/' } }, function(err) { expect(err).to.not.exist(); var routes = server.table(); expect(routes[0].table).to.have.length(1); done(); }); }); it('should fail to register with bad options', function (done) { var server = new Hapi.Server(); server.connection({ host: 'test' }); internals.bootstrapServer(server, { register: require('../'), options: { foo: 'bar' } }, function(err) { expect(err).to.exist(); expect(err.message).to.equal('"foo" is not allowed'); done(); }); }); it('should register with malformed endpoint', function(done) { var server = new Hapi.Server(); server.connection({ host: 'test' }); internals.bootstrapServer(server, { register: require('../'), options: { endpoint: 'api/' } }, function(err) { expect(err).to.not.exist(); var routes = server.table(); var endpoints = routes[0].table; expect(endpoints).to.have.length(2); expect(endpoints).to.part.deep.include([{ path: '/api' }, { path: '/api/css/{path*}' }]); done(); }); }); }); describe('Lout', function() { var server = null; before(function(done) { server = new Hapi.Server(); server.connection({ host: 'test' }); server.route(require('./routes/default')); internals.bootstrapServer(server, require('../'), function() { done(); }); }); it('shows template when correct path is provided', function(done) { server.inject('/docs?server=http://test&path=/test', function(res) { var $ = cheerio.load(res.result); expect($('.anchor-link').length).to.equal(5); expect($('.anchor').length).to.equal(5); var matches = ['GET/test', 'POST/test', 'PUT/test', 'PATCH/test', 'DELETE/test']; var methodHeadings = $('.panel-heading .method-title'); expect(methodHeadings.length).to.equal(5); methodHeadings.each(function() { expect($(this).text().replace(/\n|\s+/g, '')).to.contain(matches.shift()); }); expect($('.badge').length).to.equal(2); expect($('h3.cors').length).to.equal(0); expect($('title').text()).to.include('/test'); done(); }); }); it('shows array objects', function(done) { server.inject('/docs?server=http://test&path=/rootarray', function(res) { var $ = cheerio.load(res.result); expect($('dt h6').length).to.equal(5); done(); }); }); it('shows alternatives', function(done) { server.inject('/docs?server=http://test&path=/alternatives', function(res) { expect(res.result).to.contain('Alternatives'); expect(res.result).to.contain('number'); expect(res.result).to.contain('string'); expect(res.result).to.contain('first'); expect(res.result).to.contain('last'); done(); }); }); it('returns a Not Found response when wrong path is provided', function(done) { server.inject('/docs?server=http://test&path=blah', function(res) { expect(res.result.error).to.equal('Not Found'); done(); }); }); it('displays the index if no path is provided', function(done) { server.inject('/docs', function(res) { server.table()[0].table.forEach(function(route) { if ((route.settings.plugins && route.settings.plugins.lout === false) || route.path === '/docs' || route.method === 'options') { expect(res.result).to.not.contain('?server=http://test&path=' + route.path); } else { expect(res.result).to.contain('?server=http://test&path=' + route.path); } }); done(); }); }); it('index doesn\'t have the docs endpoint listed', function(done) { server.inject('/docs', function(res) { expect(res.result).to.not.contain('?server=http://test&path=/docs'); done(); }); }); it('index doesn\'t include routes that are configured with docs disabled', function(done) { server.inject('/docs', function(res) { expect(res.result).to.not.contain('/notincluded'); done(); }); }); it('displays nested rules', function(done) { server.inject('/docs?server=http://test&path=/nested', function(res) { expect(res.result).to.contain('param1'); expect(res.result).to.contain('nestedparam1'); expect(res.result).to.contain('icon-star'); done(); }); }); it('displays path parameters', function(done) { server.inject('/docs?server=http://test&path=/path/{pparam}/test', function(res) { expect(res.result).to.contain('Path Parameters'); expect(res.result).to.contain('pparam'); expect(res.result).to.contain('icon-star'); done(); }); }); it('should not show properties on empty objects', function(done) { server.inject('/docs?server=http://test&path=/emptyobject', function(res) { expect(res.result).to.contain('param1'); expect(res.result.match(/Properties/g)).to.have.length(1); done(); }); }); it('should show routes without any validation', function(done) { server.inject('/docs?path=/novalidation', function(res) { expect(res.result).to.not.contain('Parameters'); done(); }); }); it('should handle invalid array of rules', function(done) { server.inject('/docs?server=http://test&path=/withnestedrulesarray', function(res) { expect(res.result).to.contain('Request Parameters'); done(); }); }); it('should show html notes', function(done) { server.inject('/docs?server=http://test&path=/withhtmlnote', function(res) { var $ = cheerio.load(res.result); expect($('.htmlroutenote').length).to.equal(1); expect($('.htmltypenote').length).to.equal(1); done(); }); }); it('should show example', function(done) { server.inject('/docs?server=http://test&path=/withexample', function(res) { var $ = cheerio.load(res.result); expect($('.example').length).to.equal(1); done(); }); }); it('should support multiple nested examples', function(done) { server.inject('/docs?server=http://test&path=/withnestedexamples', function(res) { var $ = cheerio.load(res.result); expect($('.example').length).to.equal(3); done(); }); }); it('should support "false" as validation rule', function(done) { server.inject('/docs?server=http://test&path=/denybody', function(res) { expect(res.result).to.contain('Denied'); done(); }); }); it('should not detect "false" on an empty object', function(done) { server.inject('/docs?server=http://test&path=/rootemptyobject', function(res) { expect(res.result).to.not.contain('Denied'); done(); }); }); it('should show meta informations', function(done) { server.inject('/docs?server=http://test&path=/withmeta', function(res) { var $ = cheerio.load(res.result); expect($('.meta pre code').length).to.equal(1); done(); }); }); it('should show units', function(done) { server.inject('/docs?server=http://test&path=/withunit', function(res) { expect(res.result).to.contain('Unit'); expect(res.result).to.contain('ms'); done(); }); }); it('should show default values', function(done) { server.inject('/docs?server=http://test&path=/withdefaultvalue', function(res) { var $ = cheerio.load(res.result); expect($('dt.default-value').text()).to.equal('Default value'); expect($('dd.default-value').text()).to.contain('42'); done(); }); }); it('should show binary types encoding', function(done) { server.inject('/docs?server=http://test&path=/withbinaryencoding', function(res) { var $ = cheerio.load(res.result); expect($('dt.encoding').text()).to.equal('Encoding'); expect($('dd.encoding').text()).to.equal('base64'); expect($('dt.rules-Min').text()).to.equal('Min'); expect($('dd.rules-Min').text()).to.contain('42'); expect($('dt.rules-Max').text()).to.equal('Max'); expect($('dd.rules-Max').text()).to.contain('128'); expect($('dt.rules-Length').text()).to.equal('Length'); expect($('dd.rules-Length').text()).to.contain('64'); done(); }); }); it('should show dates with min and max', function(done) { server.inject('/docs?server=http://test&path=/withdate', function(res) { // The tests results will depend on the timezone it is executed on, so I'll only test for the presence // of something. var $ = cheerio.load(res.result); expect($('dt.rules-Min').text()).to.equal('Min'); expect($('dd.rules-Min').text().replace(/\n|\s+/g, '')).to.not.be.empty(); expect($('dt.rules-Max').text()).to.equal('Max'); expect($('dd.rules-Max').text().replace(/\n|\s+/g, '')).to.not.be.empty(); done(); }); }); it('should show peer dependencies', function(done) { server.inject('/docs?server=http://test&path=/withpeersconditions', function(res) { expect(res.result).to.contain('Requires a and b and c.'); expect(res.result).to.contain('Requires a or b or c.'); expect(res.result).to.contain('Requires a xor b xor c.'); expect(res.result).to.contain('Requires b, c to be present when a is.'); expect(res.result).to.contain('Requires b, c to not be present when a is.'); done(); }); }); it('should show pattern on objects', function(done) { server.inject('/docs?server=http://test&path=/withpattern', function(res) { expect(res.result).to.contain('Patterns'); expect(res.result).to.contain('/\\w\\d/'); expect(res.result).to.contain('boolean'); done(); }); }); it('should show peer dependencies', function(done) { server.inject('/docs?server=http://test&path=/withallowunknown', function(res) { var $ = cheerio.load(res.result); expect($('dd.allow-unknown').text()).to.equal('truefalse'); done(); }); }); it('should show case insensitive string', function(done) { server.inject('/docs?server=http://test&path=/test', function(res) { var $ = cheerio.load(res.result); expect($('dd.case-insensitive').length).to.equal(1); done(); }); }); it('should support string specifics', function(done) { server.inject('/docs?server=http://test&path=/withstringspecifics', function(res) { var $ = cheerio.load(res.result); var ddRules = 'dt.rules-'; var rulesSelector = ddRules + ['Alphanum', 'Regex', 'Token', 'Email', 'Guid', 'IsoDate', 'Hostname', 'Lowercase', 'Uppercase', 'Trim' ].join(',' + ddRules); expect($('dd.rules-Regex').text()).to.contain('/\\d{3}.*/'); expect($(rulesSelector).length).to.equal(10); done(); }); }); it('should support conditional alternatives', function(done) { server.inject('/docs?server=http://test&path=/withconditionalalternatives', function(res) { var $ = cheerio.load(res.result); expect($('.condition-text').text().replace(/\n|\s+/g, '')) .to.contain('Ifbmatchesthefollowingmodel') .to.contain('Ifamatchesthefollowingmodel'); expect($('.condition-model').length).to.equal(2); expect($('.consequence-model').length).to.equal(4); expect($('.type > dd').text()) .to.contain('string') .to.contain('number') .to.contain('boolean') .to.contain('date'); done(); }); }); it('should support references', function(done) { server.inject('/docs?server=http://test&path=/withreferences', function(res) { var $ = cheerio.load(res.result); expect($('dd.ref-target').text()) .to.contain('a.b') .to.contain('$x'); done(); }); }); it('should support assertions', function(done) { server.inject('/docs?server=http://test&path=/withassert', function(res) { var $ = cheerio.load(res.result); expect($('.assertion-text').text().replace(/\n|\s+/g, '')) .to.contain('Assertsthatd.ematchesthefollowingmodel') .to.contain('Assertsthat$xmatchesthefollowingmodel'); expect($('dd.ref-target').text()) .to.contain('a.c') .to.contain('b.e'); done(); }); }); it('should show properties of the route', function(done) { server.inject('/docs?server=http://test&path=/withproperties', function(res) { var $ = cheerio.load(res.result); expect($('p.vhost').text()).to.equal('john.doe'); expect($('dd.cors-maxAge').text()).to.equal('12345'); expect($('p.jsonp').text()).to.equal('callback'); done(); }); }); it('should handle cors: true', function (done) { server.inject('/docs?server=http://test&path=/withcorstrue', function(res) { var $ = cheerio.load(res.result); expect($('h3.cors').text()).to.equal('CORS'); expect($('dd.cors-isOriginExposed').text()).to.equal('true'); done(); }); }); it('should support references in rules', function(done) { server.inject('/docs?server=http://test&path=/withrulereference', function(res) { var $ = cheerio.load(res.result); expect($('.rules-Min .reference').text()).to.equal('param2'); done(); }); }); it('should remove stripped fields', function(done) { server.inject('/docs?server=http://test&path=/withstrip', function(res) { var $ = cheerio.load(res.result); expect($('.glyphicon-trash')).to.have.length(1); done(); }); }); describe('Authentication', function() { var server; before(function(done) { server = new Hapi.Server(); server.connection({ host: 'test' }); server.auth.scheme('testScheme', function() { return { authenticate: function() {}, payload: function() {}, response: function() {} }; }); server.auth.strategy('testStrategy', 'testScheme'); server.route(require('./routes/withauth')); internals.bootstrapServer(server, require('../'), function() { done(); }); }); it('should display authentication information', function(done) { server.inject('/docs?server=http://test&path=/withauth', function(res) { expect(res).to.exist(); expect(res.result).to.contain('Strategies'); done(); }); }); it('should display authentication information with an object', function(done) { server.inject('/docs?server=http://test&path=/withauthasobject', function(res) { var $ = cheerio.load(res.result); expect($('p.auth-strategies').text()).to.equal('testStrategy'); expect($('p.auth-mode').text()).to.equal('try'); expect($('p.auth-payload').text()).to.equal('optional'); expect($('p.auth-scope').text()).to.equal('test'); expect($('p.auth-entity').text()).to.equal('user'); done(); }); }); }); describe('Index', function() { it('doesn\'t throw an error when requesting the index when there are no POST routes', function(done) { var server = new Hapi.Server(); server.connection(); server.route(require('./routes/withoutpost')); internals.bootstrapServer(server, require('../'), function() { server.inject('/docs', function(res) { expect(res).to.exist(); expect(res.result).to.contain('/test'); done(); }); }); }); }); }); describe('Customized Lout', function() { it('should succeed with a basePath without helpers', function(done) { var server = new Hapi.Server(); server.connection(); internals.bootstrapServer(server, { register: require('../'), options: { basePath: Path.join(__dirname, './custom-test-files') } }, function() { done(); }); }); it('should succeed with a correct configuration', function(done) { var server = new Hapi.Server(); server.connection(); internals.bootstrapServer(server, { register: require('../'), options: { basePath: Path.join(__dirname, './custom-test-files'), helpersPath: '.', cssPath: null } }, function() { done(); }); }); it('should succeed with a custom engine', function(done) { var server = new Hapi.Server(); server.connection(); var options = { engines: { custom: { module: { compile: function() {} } } } }; internals.bootstrapServer(server, { register: require('../'), options: options }, function(err) { expect(err).to.not.exist(); done(); }); }); it('should serve a custom css', function(done) { var server = new Hapi.Server(); server.connection(); internals.bootstrapServer(server, { register: require('../'), options: { cssPath: Path.join(__dirname, './custom-test-files/css') } }, function() { server.inject('/docs/css/style.css', function(res) { expect(res).to.exist(); expect(res.result).to.contain('.cssTest'); done(); }); }); }); it('ignores methods', function(done) { var server = new Hapi.Server(); server.connection(); server.route(require('./routes/default')); internals.bootstrapServer(server, { register: require('../'), options: { filterRoutes: function (route) { return route.method !== 'delete' && route.path !== '/test'; } } }, function() { server.inject('/docs', function(res) { expect(res.result).to.not.contain('?server=http://test&path=/test'); expect(res.result).to.not.contain('#DELETE'); done(); }); }); }); }); describe('Multiple connections', function() { var server = null; before(function (done) { server = new Hapi.Server(); server.connection({ host: 'test', port: 1, labels: 'c1' }); server.connection({ host: 'test', port: 2, labels: 'c2' }); server.route(require('./routes/default')); internals.bootstrapServer(server, require('../'), function() { done(); }); }); it('should load all the servers routes', function (done) { server.inject('/docs', function(res) { var tables = server.table(); expect(tables).to.have.length(2); tables.forEach(function (connection) { expect(res.result).to.contain(connection.info.uri); connection.table.forEach(function(route) { if ((route.settings.plugins && route.settings.plugins.lout === false) || route.path === '/docs' || route.method === 'options') { expect(res.result).to.not.contain('?server=' + connection.info.uri + '&path=' + route.path); } else { expect(res.result).to.contain('?server=' + connection.info.uri + '&path=' + route.path); } }); }); done(); }); }); it('should only show one server if parameter is there', function (done) { server.inject('/docs?server=http://test:1', function(res) { var table = server.table(); expect(table).to.have.length(2); var table1, table2; table.forEach(function (connection) { var uri = connection.info.uri; if (uri === 'http://test:1') { table1 = connection.table; } else if (uri === 'http://test:2') { table2 = connection.table; } }); expect(res.result).to.contain('http://test:1'); table1.forEach(function(route) { if ((route.settings.plugins && route.settings.plugins.lout === false) || route.path === '/docs' || route.method === 'options') { expect(res.result).to.not.contain('?server=http://test:1&path=' + route.path); } else { expect(res.result).to.contain('?server=http://test:1&path=' + route.path); } }); expect(res.result).to.not.contain('http://test:2'); table2.forEach(function(route) { expect(res.result).to.not.contain('?server=http://test:2&path=' + route.path); }); done(); }); }); }); describe('Select connections', function() { var server = null; var selected = ['c2']; var unselected = ['c1']; before(function (done) { server = new Hapi.Server(); server.connection({ host: 'test', port: 1, labels: 'c1' }); server.connection({ host: 'test', port: 2, labels: 'c2' }); server.route(require('./routes/default')); internals.bootstrapServer(server, require('../'), { select: 'c2' }, done); }); it('should load all the selected servers routes', function (done) { server.select(selected).inject('/docs', function(res) { var selectedTables = server.select(selected).table(); var unselectedTables = server.select(unselected).table(); expect(selectedTables).to.have.length(1); expect(unselectedTables).to.have.length(1); selectedTables.forEach(function (connection) { expect(res.result).to.contain(connection.info.uri); connection.table.forEach(function(route) { if ((route.settings.plugins && route.settings.plugins.lout === false) || route.path === '/docs' || route.method === 'options') { expect(res.result).to.not.contain('?server=' + connection.info.uri + '&path=' + route.path); } else { expect(res.result).to.contain('?server=' + connection.info.uri + '&path=' + route.path); } }); }); unselectedTables.forEach(function (connection) { expect(res.result).to.not.contain(connection.info.uri); }); done(); }); }); }); describe('Multiple paths', function () { it('should show separate paths', function (done) { var server = new Hapi.Server(); server.connection({ host: 'test' }); server.route({ method: 'GET', path: '/v1/test', handler: function() {} }); server.route({ method: 'GET', path: '/v2/test', handler: function() {} }); server.route({ method: 'GET', path: '/another', handler: function() {} }); internals.bootstrapServer(server, [{ register: require('../'), options: { endpoint: '/docs/v1', filterRoutes: function (route) { return /^\/v1/.test(route.path); } } }, { register: require('../'), options: { endpoint: '/docs/v2', filterRoutes: function (route) { return /^\/v2/.test(route.path); } } }], function(err) { expect(err).to.not.exist(); var routes = server.table(); expect(routes[0].table).to.have.length(7); // 3 routes, 2 docs routes, 2 css routes server.inject('/docs/v1', function (res) { var $ = cheerio.load(res.result); expect($('.route-index > a').length).to.equal(1); expect($('.route-index > a').attr('href')).to.equal('?server=http://test&path=/v1/test#GET'); server.inject('/docs/v2', function (res) { var $ = cheerio.load(res.result); expect($('.route-index > a').length).to.equal(1); expect($('.route-index > a').attr('href')).to.equal('?server=http://test&path=/v2/test#GET'); server.inject('/docs', function (res) { expect(res.statusCode).to.equal(404); done(); }); }); }); }); }); });
{ "content_hash": "8fa1f120871848621cfb2c3eea188894", "timestamp": "", "source": "github", "line_count": 926, "max_line_length": 116, "avg_line_length": 30.711663066954642, "alnum_prop": 0.5040613242378424, "repo_name": "evdevgit/lout", "id": "3283dd70b4b8701143603c42a41a2084459cfdd8", "size": "28456", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/index.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "2639" }, { "name": "HTML", "bytes": "17777" }, { "name": "JavaScript", "bytes": "52833" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html lang="en-GB" xml:lang="en-GB" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <title>advmod:neg</title> <link rel="root" href=""/> <!-- for JS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"> <link rel="stylesheet" type="text/css" href="../../css/jquery-ui-redmond.css"/> <link rel="stylesheet" type="text/css" href="../../css/style.css"/> <link rel="stylesheet" type="text/css" href="../../css/style-vis.css"/> <link rel="stylesheet" type="text/css" href="../../css/hint.css"/> <script type="text/javascript" src="../../lib/ext/head.load.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/anchor-js/3.2.2/anchor.min.js"></script> <script>document.addEventListener("DOMContentLoaded", function(event) {anchors.add();});</script> <!-- Set up this custom Google search at https://cse.google.com/cse/business/settings?cx=001145188882102106025:dl1mehhcgbo --> <!-- DZ 2021-01-22: I am temporarily hiding the search field to find out whether it slows down loading of the title page. <script> (function() { var cx = '001145188882102106025:dl1mehhcgbo'; var gcse = document.createElement('script'); gcse.type = 'text/javascript'; gcse.async = true; gcse.src = 'https://cse.google.com/cse.js?cx=' + cx; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gcse, s); })(); </script> --> <!-- <link rel="shortcut icon" href="favicon.ico"/> --> </head> <body> <div id="main" class="center"> <div id="hp-header"> <table width="100%"><tr><td width="50%"> <span class="header-text"><a href="http://universaldependencies.org/#language-la">home</a></span> <span class="header-text"><a href="https://github.com/universaldependencies/docs/edit/pages-source/_la/dep/advmod-neg.md" target="#">edit page</a></span> <span class="header-text"><a href="https://github.com/universaldependencies/docs/issues">issue tracker</a></span> </td><td> <gcse:search></gcse:search> </td></tr></table> </div> <hr/> <div class="v2complete"> This page pertains to UD version 2. </div> <div id="content"> <noscript> <div id="noscript"> It appears that you have Javascript disabled. Please consider enabling Javascript for this page to see the visualizations. </div> </noscript> <!-- The content may include scripts and styles, hence we must load the shared libraries before the content. --> <script type="text/javascript"> console.time('loading libraries'); var root = '../../'; // filled in by jekyll head.js( // External libraries // DZ: Copied from embedding.html. I don't know which one is needed for what, so I'm currently keeping them all. root + 'lib/ext/jquery.min.js', root + 'lib/ext/jquery.svg.min.js', root + 'lib/ext/jquery.svgdom.min.js', root + 'lib/ext/jquery.timeago.js', root + 'lib/ext/jquery-ui.min.js', root + 'lib/ext/waypoints.min.js', root + 'lib/ext/jquery.address.min.js' ); </script> <h2><code>advmod:neg</code>: negating particle</h2> <p>This relation is used exclusively and always in combination with <a href="la-feat/Polarity">negative</a> <a href="la-pos/PART">particles</a>.</p> <p>In Latin, the chief negative particle is <em>non</em>, but also <em>ne</em>/<em>ni</em> and <em>haud</em> are attested as such. They are used mainly to negate predicates, but can confer negative polarity to any other element. They do not really act as <a href="la-pos/ADV">other adverbial</a> elements, in that they are merely functional, clitic-like elements and as such more similar to <a href="la-pos/aux">auxiliaries</a> than to adverbs: hence the basic relation <code class="language-plaintext highlighter-rouge">advmod</code> has best to be augmented with this subtype in the case of negative particles.</p> <pre><code class="language-sdparse">« Non loquor his , ymmo studio callentibus » , inquis . \n « Not I-speak to-these , rather in-study hardening » , you-say . advmod:neg(loquor, non) advmod:neg(I-speak, not) </code></pre> <p>‘«Not to such I speak but rather to those skilled in study,» thou sayst.’ (<em>Eclogues</em> I, UDante)</p> <pre><code class="language-sdparse">Quod patet non solum ex hoc quod est operatio subsistens : sed quia una operatione deus seipsum ita perfecte intelligit sicut est , et omnia alia , quae sunt et quae non sunt , bona et mala . \n What appears not only out-of this what is operation subsistent : but because one with-operation himself so perfectly understands like is , and all other , which they-are and which not they-are , good and bad . advmod:neg(solum, non-3) advmod:emph(hoc,solum) advmod:neg(only, not-40) advmod:emph(this,only) </code></pre> <p>‘This is evident not only because it is a subsistent operation but also because by one operation God knows Himself as perfectly as He is perfect, as well as all other things, those that are and those that are not, the good and the evil.’ (<em>Summa contra Gentiles</em>, ITTB) <!-- Interlanguage links updated Po lis 14 15:35:07 CET 2022 --></p> <!-- "in other languages" links --> <hr/> advmod:neg in other languages: [<a href="../../akk/dep/advmod-neg.html">akk</a>] [<a href="../../apu/dep/advmod-neg.html">apu</a>] [<a href="../../bxr/dep/advmod-neg.html">bxr</a>] [<a href="../../kmr/dep/advmod-neg.html">kmr</a>] [<a href="../../la/dep/advmod-neg.html">la</a>] [<a href="../../mt/dep/advmod-neg.html">mt</a>] [<a href="../../nhi/dep/advmod-neg.html">nhi</a>] [<a href="../../pl/dep/advmod-neg.html">pl</a>] [<a href="../../quc/dep/advmod-neg.html">quc</a>] [<a href="../../sms/dep/advmod-neg.html">sms</a>] [<a href="../../vi/dep/advmod-neg.html">vi</a>] </div> <!-- support for embedded visualizations --> <script type="text/javascript"> var root = '../../'; // filled in by jekyll head.js( // We assume that external libraries such as jquery.min.js have already been loaded outside! // (See _layouts/base.html.) // brat helper modules root + 'lib/brat/configuration.js', root + 'lib/brat/util.js', root + 'lib/brat/annotation_log.js', root + 'lib/ext/webfont.js', // brat modules root + 'lib/brat/dispatcher.js', root + 'lib/brat/url_monitor.js', root + 'lib/brat/visualizer.js', // embedding configuration root + 'lib/local/config.js', // project-specific collection data root + 'lib/local/collections.js', // Annodoc root + 'lib/annodoc/annodoc.js', // NOTE: non-local libraries 'https://spyysalo.github.io/conllu.js/conllu.js' ); var webFontURLs = [ // root + 'static/fonts/Astloch-Bold.ttf', root + 'static/fonts/PT_Sans-Caption-Web-Regular.ttf', root + 'static/fonts/Liberation_Sans-Regular.ttf' ]; var setupTimeago = function() { jQuery("time.timeago").timeago(); }; head.ready(function() { setupTimeago(); // mark current collection (filled in by Jekyll) Collections.listing['_current'] = 'la'; // perform all embedding and support functions Annodoc.activate(Config.bratCollData, Collections.listing); }); </script> <!-- google analytics --> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-55233688-1', 'auto'); ga('send', 'pageview'); </script> <div id="footer"> <p class="footer-text">&copy; 2014–2021 <a href="http://universaldependencies.org/introduction.html#contributors" style="color:gray">Universal Dependencies contributors</a>. Site powered by <a href="http://spyysalo.github.io/annodoc" style="color:gray">Annodoc</a> and <a href="http://brat.nlplab.org/" style="color:gray">brat</a></p>. </div> </div> </body> </html>
{ "content_hash": "7bbacc9e98803e422ca9aa35dcc87b95", "timestamp": "", "source": "github", "line_count": 205, "max_line_length": 616, "avg_line_length": 42.55609756097561, "alnum_prop": 0.6282668500687758, "repo_name": "UniversalDependencies/universaldependencies.github.io", "id": "dff66f22be806615daec596088a194323aeef0ab", "size": "8740", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "la/dep/advmod-neg.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "64420" }, { "name": "HTML", "bytes": "383191916" }, { "name": "JavaScript", "bytes": "687350" }, { "name": "Perl", "bytes": "7788" }, { "name": "Python", "bytes": "21203" }, { "name": "Shell", "bytes": "7253" } ], "symlink_target": "" }
var Themis = require('../src/themis'); var util = require('util'); describe('The pre validation data transformers', function() { before(function () { Themis.registerTransformer('pad', 'pre', function(data, transformer) { if (transformer === true) { return " " + data + " "; } else { return data; } }); Themis.registerTransformer('trim', 'pre', function(data, transformer) { if (transformer === true) { return data.trim(); } else { return data; } }); }); it('can transform "properties" of objects', function() { var schema = { type: 'object', properties: { first_name: { type: 'string', trim: true }, last_name: { type: 'string', pad: true } } }; var data = { first_name: ' Johny ', middle_name: ' Java ', last_name: 'Jose' }; var report = Themis.validator(schema)(data, '0'); data.should.deep.equal({ first_name: 'Johny', middle_name: ' Java ', last_name: ' Jose ' }); }); it('can transform "additionalProperties" of objects', function() { var schema = { type: 'object', additionalProperties: { type: 'string', trim: true } }; var data = { first_name: ' Johny ', middle_name: ' Java ', last_name: ' Jose ' }; var report = Themis.validator(schema)(data, '0') data.should.deep.equal({ first_name: 'Johny', middle_name: 'Java', last_name: 'Jose' }); }); it('can transform "items" of arrays', function() { var schema = { type: 'array', items: [ { type: 'string', trim: true }, { type: 'string', pad: true } ] }; var data = [' Johny ', 'Java', 'Jose ', ' ! ' ]; var report = Themis.validator(schema)(data, '0') data.should.deep.equal(['Johny', ' Java ', 'Jose ', ' ! ']); schema = { type: 'array', items: { type: 'string', pad: true } }; data = [' Johny ', 'Java', 'Jose ', ' ! ' ]; report = Themis.validator(schema)(data, '0') data.should.deep.equal([' Johny ', ' Java ', ' Jose ', ' ! ']); }); it('can transform "additionalItems" of arrays', function() { var schema = { type: 'array', items: [ { type: 'string' } ], additionalItems: { type: 'string', pad: true } }; var data = ['Johny', 'Java', 'Jose'] var report = Themis.validator(schema)(data, '0') data.should.deep.equal(['Johny', ' Java ', ' Jose ']); }); })
{ "content_hash": "26d3fe833b9f959d8ecea57abb247d32", "timestamp": "", "source": "github", "line_count": 128, "max_line_length": 75, "avg_line_length": 21.4609375, "alnum_prop": 0.4757917728431016, "repo_name": "playlyfe/themis", "id": "f15b05b98af9bbe7af07276908ef1b553ac22757", "size": "2747", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/transformers.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "285004" }, { "name": "JavaScript", "bytes": "165935" } ], "symlink_target": "" }
<?php namespace Light\ObjectService\Resource\Operation; use Light\ObjectAccess\Resource\ResolvedResource; /** * An operation encapsulates the parameters and the logic of an action to be performed on a resource. * */ abstract class Operation { /** * Executes the operation. * @param ResolvedResource $resource * @param ExecutionParameters $parameters */ abstract public function execute(ResolvedResource $resource, ExecutionParameters $parameters); }
{ "content_hash": "dbe1f2bfadf356fbfb771496096476f0", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 101, "avg_line_length": 26, "alnum_prop": 0.7670940170940171, "repo_name": "szymanp/light-objectservice", "id": "3540b322f7cce684acaf00bc7536062863b66fc9", "size": "468", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/ObjectService/Resource/Operation/Operation.php", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "197" }, { "name": "PHP", "bytes": "162359" } ], "symlink_target": "" }
// AUTOGENERATED FILE - DO NOT MODIFY! // This file generated by Djinni from ripple_like_wallet.djinni #include "RippleConfigurationDefaults.hpp" // my header #include "Marshal.hpp" namespace djinni_generated { RippleConfigurationDefaults::RippleConfigurationDefaults() : ::djinni::JniInterface<::ledger::core::api::RippleConfigurationDefaults, RippleConfigurationDefaults>("co/ledger/core/RippleConfigurationDefaults$CppProxy") {} RippleConfigurationDefaults::~RippleConfigurationDefaults() = default; CJNIEXPORT void JNICALL Java_co_ledger_core_RippleConfigurationDefaults_00024CppProxy_nativeDestroy(JNIEnv* jniEnv, jobject /*this*/, jlong nativeRef) { try { DJINNI_FUNCTION_PROLOGUE1(jniEnv, nativeRef); delete reinterpret_cast<::djinni::CppProxyHandle<::ledger::core::api::RippleConfigurationDefaults>*>(nativeRef); } JNI_TRANSLATE_EXCEPTIONS_RETURN(jniEnv, ) } } // namespace djinni_generated
{ "content_hash": "d330601703fed6fe34dce67d6332d91f", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 220, "avg_line_length": 42.36363636363637, "alnum_prop": 0.7811158798283262, "repo_name": "LedgerHQ/lib-ledger-core", "id": "90adaf71a92a202dc49b6444098f138691449c65", "size": "932", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "core/src/jni/jni/RippleConfigurationDefaults.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Ada", "bytes": "87492" }, { "name": "Assembly", "bytes": "95273" }, { "name": "Batchfile", "bytes": "49710" }, { "name": "C", "bytes": "17901111" }, { "name": "C++", "bytes": "136103115" }, { "name": "CMake", "bytes": "1117135" }, { "name": "CSS", "bytes": "2536" }, { "name": "DIGITAL Command Language", "bytes": "312789" }, { "name": "Dockerfile", "bytes": "1746" }, { "name": "Emacs Lisp", "bytes": "5297" }, { "name": "HTML", "bytes": "474505" }, { "name": "JavaScript", "bytes": "15286" }, { "name": "M4", "bytes": "58734" }, { "name": "Makefile", "bytes": "243" }, { "name": "Nix", "bytes": "6555" }, { "name": "Perl", "bytes": "2222280" }, { "name": "Prolog", "bytes": "29177" }, { "name": "Python", "bytes": "26175" }, { "name": "Raku", "bytes": "34072" }, { "name": "Roff", "bytes": "5" }, { "name": "Scala", "bytes": "1392" }, { "name": "Scheme", "bytes": "4249" }, { "name": "Shell", "bytes": "186270" }, { "name": "XS", "bytes": "4319" }, { "name": "eC", "bytes": "5127" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <locationmap xmlns="http://apache.org/forrest/locationmap/1.0"> <components> <matchers default="lm"> <matcher name="lm" src="org.apache.forrest.locationmap.WildcardLocationMapHintMatcher"/> </matchers> <selectors default="exists"> <selector name="exists" logger="sitemap.selector.exists" src="org.apache.forrest.sourceexists.SourceExistsSelector" /> </selectors> </components> <locator> <!-- Utility patterns --> <match pattern="doac.categoryDefinitions"> <location src="{properties:content}doac/categoryDefinitions.xml" /> </match> <match pattern="doac.skillDefinitions"> <location src="{properties:content}doac/skillDefinitions.xml" /> </match> <!-- FOAF descriptors with DOAC information --> <match pattern="doac.descriptor.ramon"> <location src="{properties:content}xdocs/samples/ramon_foaf.rdf" /> </match> <match pattern="doac.transform.*.*"> <select> <location src="resources/stylesheets/{1}-to-{2}.xsl"/> <location src="{forrest:forrest.plugins}/org.apache.forrest.plugin.input.doac/resources/stylesheets/{1}-to-{2}.xsl"/> </select> </match> </locator> </locationmap>
{ "content_hash": "4583ec23257fb02d491c1c665c0669f1", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 125, "avg_line_length": 40.01923076923077, "alnum_prop": 0.691494473810668, "repo_name": "apache/forrest", "id": "c37bf2867dc0f58f41c08ab279e81b2f94e2a424", "size": "2081", "binary": false, "copies": "2", "ref": "refs/heads/trunk", "path": "whiteboard/plugins/org.apache.forrest.plugin.input.doac/locationmap.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "62060" }, { "name": "CSS", "bytes": "234824" }, { "name": "Clean", "bytes": "7189" }, { "name": "HTML", "bytes": "197618" }, { "name": "Java", "bytes": "1155856" }, { "name": "JavaScript", "bytes": "64397" }, { "name": "Perl", "bytes": "23794" }, { "name": "Python", "bytes": "6570" }, { "name": "Scala", "bytes": "33856" }, { "name": "Shell", "bytes": "35462" }, { "name": "XSLT", "bytes": "2100713" } ], "symlink_target": "" }
<?php namespace Lib\Radius\Mapper; use Zend\Db\TableGateway\TableGateway; use Lib\Model\AbstractMapper; use Lib\Model\AbstractEntity; use Lib\Model\Exception as Exception; class UserGroupMapper extends AbstractMapper { /** * Overwrite MapperAbstract primaryKey * The db primary key's column name */ protected $primaryKeys = array('username', 'groupname'); /** * Find row by user * * @return Zend\Db\ResultSet\ResultSet */ public function findByUser($username) { $rowset = $this->tableGateway->select(array('username' => $username)); if ($rowset->count() <=0) { throw new Exception\ObjectNotFoundException(__CLASS__." Could not find row: [$username]"); } return $rowset; } /** * Find row by group * * @return Zend\Db\ResultSet\ResultSet */ public function findByGroup($groupname) { $rowset = $this->tableGateway->select(array('groupname' => $groupname)); if ($rowset->count() <=0) { throw new Exception\ObjectNotFoundException(__CLASS__." Could not find row: [$groupname]"); } return $rowset; } /** * Update group by array objects * It chcek and delete user from the group if group does not exist in the array objects * It check and add user to the group if user not already belong to the group * * @param array of Usergroupentity */ public function updateByArrayObjs(array $objs, $username = null){ // if array not exist, delete // findByUser and delete group not exist in pass in $objs try{ $groups = $this->findByUser($username); }catch(Exception\ObjectNotFoundException $e){ $groups = null; } $createObjs = $objs; // UserGroupEntity array objs $deleteObjs = array(); // Usergroupentity array objs $updateObjs = array(); // Usergroupentity array objs // Construct update, create, delete obj lists if(!empty($groups)){ foreach($groups as $gIndex => $group){ $isDelete = true; // Remove exist group obj from create list foreach($objs as $oIndex => $obj){ if($obj->getGroupname() == $group->getGroupname()){ // Create List unset($createObjs[$oIndex]); $isDelete = false; break; } } if($isDelete){ // Delete list $deleteObjs[] = $group; }else{ // Update list $updateObjs[] = $group; } } } // Process all obj list $objList = array('create' => $createObjs, 'delete' => $deleteObjs, 'update' => $updateObjs); foreach($objList as $action => $objs){ if(!empty($objs)){ foreach($objs as $obj){ if(empty($obj->getGroupname()) || empty($obj->getUsername())){ continue; } if($action == 'create' || $action == 'update'){ $this->save($obj); }elseif($action == 'delete'){ $this->delete($obj); } } } } /* // Debug message echo "delete object"; print_r($deleteObjs); echo "create object"; print_r($createObjs); echo "Update object"; print_r($updateObjs);*/ } }
{ "content_hash": "081680a1c2debd2be81964f16833e00d", "timestamp": "", "source": "github", "line_count": 115, "max_line_length": 103, "avg_line_length": 31.965217391304346, "alnum_prop": 0.5057127312295974, "repo_name": "kanalfred/apigility", "id": "934e22625a8c15b55408b969b3255b7a33eecec2", "size": "3676", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "module/Lib/src/Radius/Mapper/UserGroupMapper.php", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "711" }, { "name": "HTML", "bytes": "19434" }, { "name": "PHP", "bytes": "80909" }, { "name": "Pascal", "bytes": "5173" }, { "name": "Perl", "bytes": "41847" }, { "name": "Puppet", "bytes": "369302" }, { "name": "Ruby", "bytes": "307839" }, { "name": "Shell", "bytes": "82848" } ], "symlink_target": "" }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Android.App; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("BI_Gyroscope.Droid")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("BI_Gyroscope.Droid")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] // Add some common permissions, these can be removed if not needed [assembly: UsesPermission(Android.Manifest.Permission.Internet)] [assembly: UsesPermission(Android.Manifest.Permission.WriteExternalStorage)]
{ "content_hash": "dd740eeaf86f3f776133e72848f7a432", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 84, "avg_line_length": 37.73529411764706, "alnum_prop": 0.7552611067809821, "repo_name": "ytabuchi/BuildInsider_DeviceMotion", "id": "e8d6d968f7d51d6f96cb2266e3a1df6e158d67ed", "size": "1286", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "BI_Gyroscope/BI_Gyroscope/BI_Gyroscope.Droid/Properties/AssemblyInfo.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "104570" } ], "symlink_target": "" }
package org.deeplearning4j.graph.models.embeddings; import lombok.AllArgsConstructor; import lombok.NoArgsConstructor; import org.deeplearning4j.graph.api.IGraph; import org.deeplearning4j.graph.api.Vertex; import org.deeplearning4j.graph.models.GraphVectors; import org.nd4j.linalg.api.blas.Level1; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.factory.Nd4j; import org.nd4j.linalg.ops.transforms.Transforms; import org.nd4j.linalg.primitives.Pair; import java.util.Comparator; import java.util.PriorityQueue; /** Base implementation for GraphVectors. Used in DeepWalk, and also when loading * graph vectors from file. */ @AllArgsConstructor @NoArgsConstructor public class GraphVectorsImpl<V, E> implements GraphVectors<V, E> { protected IGraph<V, E> graph; protected GraphVectorLookupTable lookupTable; @Override public IGraph<V, E> getGraph() { return graph; } @Override public int numVertices() { return lookupTable.getNumVertices(); } @Override public int getVectorSize() { return lookupTable.vectorSize(); } @Override public INDArray getVertexVector(Vertex<V> vertex) { return lookupTable.getVector(vertex.vertexID()); } @Override public INDArray getVertexVector(int vertexIdx) { return lookupTable.getVector(vertexIdx); } @Override public int[] verticesNearest(int vertexIdx, int top) { INDArray vec = lookupTable.getVector(vertexIdx).dup(); double norm2 = vec.norm2Number().doubleValue(); PriorityQueue<Pair<Double, Integer>> pq = new PriorityQueue<>(lookupTable.getNumVertices(), new PairComparator()); Level1 l1 = Nd4j.getBlasWrapper().level1(); for (int i = 0; i < numVertices(); i++) { if (i == vertexIdx) continue; INDArray other = lookupTable.getVector(i); double cosineSim = l1.dot(vec.length(), 1.0, vec, other) / (norm2 * other.norm2Number().doubleValue()); pq.add(new Pair<>(cosineSim, i)); } int[] out = new int[top]; for (int i = 0; i < top; i++) { out[i] = pq.remove().getSecond(); } return out; } private static class PairComparator implements Comparator<Pair<Double, Integer>> { @Override public int compare(Pair<Double, Integer> o1, Pair<Double, Integer> o2) { return -Double.compare(o1.getFirst(), o2.getFirst()); } } /**Returns the cosine similarity of the vector representations of two vertices in the graph * @return Cosine similarity of two vertices */ @Override public double similarity(Vertex<V> vertex1, Vertex<V> vertex2) { return similarity(vertex1.vertexID(), vertex2.vertexID()); } /**Returns the cosine similarity of the vector representations of two vertices in the graph, * given the indices of these verticies * @return Cosine similarity of two vertices */ @Override public double similarity(int vertexIdx1, int vertexIdx2) { if (vertexIdx1 == vertexIdx2) return 1.0; INDArray vector = Transforms.unitVec(getVertexVector(vertexIdx1)); INDArray vector2 = Transforms.unitVec(getVertexVector(vertexIdx2)); return Nd4j.getBlasWrapper().dot(vector, vector2); } }
{ "content_hash": "222505e8213decf34668a14f155aa859", "timestamp": "", "source": "github", "line_count": 112, "max_line_length": 115, "avg_line_length": 30.366071428571427, "alnum_prop": 0.6639223757718318, "repo_name": "RobAltena/deeplearning4j", "id": "0fc0e5a6065025fa7e0298e4fec50b5d18d9e45d", "size": "4162", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "deeplearning4j/deeplearning4j-graph/src/main/java/org/deeplearning4j/graph/models/embeddings/GraphVectorsImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2469" }, { "name": "C", "bytes": "144275" }, { "name": "C#", "bytes": "138404" }, { "name": "C++", "bytes": "16954560" }, { "name": "CMake", "bytes": "77377" }, { "name": "CSS", "bytes": "10363" }, { "name": "Cuda", "bytes": "2324886" }, { "name": "Dockerfile", "bytes": "1329" }, { "name": "FreeMarker", "bytes": "77045" }, { "name": "HTML", "bytes": "38914" }, { "name": "Java", "bytes": "36293636" }, { "name": "JavaScript", "bytes": "436278" }, { "name": "PureBasic", "bytes": "12256" }, { "name": "Python", "bytes": "325018" }, { "name": "Ruby", "bytes": "4558" }, { "name": "Scala", "bytes": "355054" }, { "name": "Shell", "bytes": "80490" }, { "name": "Smarty", "bytes": "900" }, { "name": "Starlark", "bytes": "931" }, { "name": "TypeScript", "bytes": "80252" } ], "symlink_target": "" }
<?php namespace App\Http\Controllers; use App\Http\Requests\CreateActivityRequest; use App\Http\Requests\UpdateActivityRequest; use App\Repositories\ActivityRepository; use App\Http\Controllers\AppBaseController; use Illuminate\Http\Request; use Flash; use Prettus\Repository\Criteria\RequestCriteria; use Response; class ActivityController extends AppBaseController { /** @var ActivityRepository */ private $activityRepository; public function __construct(ActivityRepository $activityRepo) { $this->activityRepository = $activityRepo; } /** * Display a listing of the Activity. * * @param Request $request * @return Response */ public function index(Request $request) { $this->activityRepository->pushCriteria(new RequestCriteria($request)); $activities = $this->activityRepository->all(); return view('activities.index') ->with('activities', $activities); } /** * Show the form for creating a new Activity. * * @return Response */ public function create() { return view('activities.create'); } /** * Store a newly created Activity in storage. * * @param CreateActivityRequest $request * * @return Response */ public function store(CreateActivityRequest $request) { $input = $request->all(); $activity = $this->activityRepository->create($input); Flash::success('Activity saved successfully.'); return redirect(route('activities.index')); } /** * Display the specified Activity. * * @param int $id * * @return Response */ public function show($id) { $activity = $this->activityRepository->findWithoutFail($id); if (empty($activity)) { Flash::error('Activity not found'); return redirect(route('activities.index')); } return view('activities.show')->with('activity', $activity); } /** * Show the form for editing the specified Activity. * * @param int $id * * @return Response */ public function edit($id) { $activity = $this->activityRepository->findWithoutFail($id); if (empty($activity)) { Flash::error('Activity not found'); return redirect(route('activities.index')); } return view('activities.edit')->with('activity', $activity); } /** * Update the specified Activity in storage. * * @param int $id * @param UpdateActivityRequest $request * * @return Response */ public function update($id, UpdateActivityRequest $request) { $activity = $this->activityRepository->findWithoutFail($id); if (empty($activity)) { Flash::error('Activity not found'); return redirect(route('activities.index')); } $activity = $this->activityRepository->update($request->all(), $id); Flash::success('Activity updated successfully.'); return redirect(route('activities.index')); } /** * Remove the specified Activity from storage. * * @param int $id * * @return Response */ public function destroy($id) { $activity = $this->activityRepository->findWithoutFail($id); if (empty($activity)) { Flash::error('Activity not found'); return redirect(route('activities.index')); } $this->activityRepository->delete($id); Flash::success('Activity deleted successfully.'); return redirect(route('activities.index')); } }
{ "content_hash": "fd2810689637d40f51c76ec1fc13d569", "timestamp": "", "source": "github", "line_count": 155, "max_line_length": 79, "avg_line_length": 23.954838709677418, "alnum_prop": 0.5970913008349044, "repo_name": "chelopezlo/backend-congreso", "id": "3b86edc2e870f4867cdd9d69c54b7c8acd669227", "size": "3713", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/Http/Controllers/ActivityController.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "553" }, { "name": "CSS", "bytes": "72" }, { "name": "HTML", "bytes": "110188" }, { "name": "JavaScript", "bytes": "503" }, { "name": "PHP", "bytes": "467517" } ], "symlink_target": "" }
require 'rgeo' # RGeo is a spatial data library for Ruby, provided by the "rgeo" gem. # # The optional RGeo::GeoJSON module provides a set of tools for GeoJSON # encoding and decoding. module RGeo # This is a namespace for a set of tools that provide GeoJSON encoding. # See http://geojson.org/ for more information about this specification. module GeoJSON end end # Implementation files require 'rgeo/geo_json/version' require 'rgeo/geo_json/entities' require 'rgeo/geo_json/coder' require 'rgeo/geo_json/interface'
{ "content_hash": "973b04940ce50ef35e3a047d12d1c8e3", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 74, "avg_line_length": 20.576923076923077, "alnum_prop": 0.7495327102803738, "repo_name": "ynelin/rgeo-geojson", "id": "98dcc2bd05bc1c0b03dee17406bad707eebb1b5e", "size": "535", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/rgeo/geo_json.rb", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Ruby", "bytes": "36035" } ], "symlink_target": "" }
import * as React from "react"; import { FBSelect, DropDownItem } from "../../ui/index"; import { updateMCU } from "../../devices/actions"; import { isNumber } from "lodash"; import { t } from "../../i18next_wrapper"; import { pinDropdowns, celery2DropDown, PinGroupName, PERIPHERAL_HEADING, } from "../../sequences/step_tiles/pin_support"; import { selectAllPeripherals, selectAllSavedPeripherals, } from "../../resources/selectors"; import { Dictionary, NamedPin, McuParamName } from "farmbot"; import { ResourceIndex } from "../../resources/interfaces"; import { NumberConfigKey } from "farmbot/dist/resources/configs/firmware"; import { SourceFwConfig } from "../../devices/interfaces"; interface PinNumberDropdownProps { sourceFwConfig: SourceFwConfig; dispatch: Function; pinNumKey: McuParamName; resources: ResourceIndex; disabled: boolean; } /** * Dropdown of pin numbers values. Includes peripheral pin numbers. * Will show the peripheral name of a pin if the pin number value matches. */ export const PinNumberDropdown = (props: PinNumberDropdownProps) => { const { pinNumKey, resources, dispatch } = props; const pinNumberValue = props.sourceFwConfig(pinNumKey).value || 0; const peripheralIds = peripheralDictionary(resources); const pinNumberNode = pinNumOrNamedPin(pinNumberValue, peripheralIds); const classes = [ props.sourceFwConfig(pinNumKey).consistent ? "" : "dim", props.disabled ? "disabled" : "", ]; return <FBSelect extraClass={classes.join(" ")} selectedItem={pinNumberValue ? celery2DropDown(pinNumberNode, resources) : undefined} customNullLabel={t("Select a pin")} onChange={onChange({ dispatch, oldValue: pinNumberValue, pinNumKey })} list={listItems(resources)} />; }; const peripheralDictionary = (resources: ResourceIndex): Dictionary<number> => { const peripheralIds: Dictionary<number> = {}; selectAllPeripherals(resources).map(p => (p.body.pin && p.body.id) && (peripheralIds[p.body.pin] = p.body.id)); return peripheralIds; }; const pinNumOrNamedPin = (pin: number, lookup: Dictionary<number>): NamedPin | number => lookup[pin] ? { kind: "named_pin", args: { pin_type: "Peripheral", pin_id: lookup[pin] } } : pin; const DISABLE_DDI = (): DropDownItem => ({ label: t("None"), value: 0 }); const listItems = (resources: ResourceIndex): DropDownItem[] => [DISABLE_DDI(), ...peripheralItems(resources), ...pinDropdowns(n => n)]; const peripheralItems = (resources: ResourceIndex): DropDownItem[] => { const list = selectAllSavedPeripherals(resources) .filter(peripheral => isNumber(peripheral.body.pin)) .map(peripheral => ({ label: peripheral.body.label, value: "" + peripheral.body.pin, headingId: PinGroupName.Peripheral })); return list.length ? [PERIPHERAL_HEADING(), ...list] : []; }; interface OnChangeProps { dispatch: Function; oldValue: number; pinNumKey: NumberConfigKey; } const onChange = (props: OnChangeProps) => (ddi: DropDownItem) => { const { oldValue, pinNumKey } = props; const newValue = parseInt("" + ddi.value); (isFinite(newValue) && (newValue !== oldValue)) && props.dispatch(updateMCU(pinNumKey, "" + newValue)); };
{ "content_hash": "ec29bbf3f03fbaedace9f3bfa2be28e5", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 80, "avg_line_length": 35.03225806451613, "alnum_prop": 0.6899938612645795, "repo_name": "gabrielburnworth/Farmbot-Web-App", "id": "164036a2495d3bd336c43f475726320107092fb8", "size": "3258", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "frontend/settings/hardware_settings/pin_number_dropdown.tsx", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "92635" }, { "name": "Dockerfile", "bytes": "966" }, { "name": "HTML", "bytes": "96279" }, { "name": "JavaScript", "bytes": "14963" }, { "name": "Ruby", "bytes": "743494" }, { "name": "Shell", "bytes": "4027" }, { "name": "TypeScript", "bytes": "2370182" } ], "symlink_target": "" }
package Paws::Route53::CreateHostedZoneResponse; use Moose; has ChangeInfo => (is => 'ro', isa => 'Paws::Route53::ChangeInfo', required => 1); has DelegationSet => (is => 'ro', isa => 'Paws::Route53::DelegationSet', required => 1); has HostedZone => (is => 'ro', isa => 'Paws::Route53::HostedZone', required => 1); has Location => (is => 'ro', isa => 'Str', traits => ['ParamInHeader'], header_name => 'Location', required => 1); has VPC => (is => 'ro', isa => 'Paws::Route53::VPC'); has _request_id => (is => 'ro', isa => 'Str'); 1; ### main pod documentation begin ### =head1 NAME Paws::Route53::CreateHostedZoneResponse =head1 ATTRIBUTES =head2 B<REQUIRED> ChangeInfo => L<Paws::Route53::ChangeInfo> A complex type that contains information about the C<CreateHostedZone> request. =head2 B<REQUIRED> DelegationSet => L<Paws::Route53::DelegationSet> A complex type that describes the name servers for this hosted zone. =head2 B<REQUIRED> HostedZone => L<Paws::Route53::HostedZone> A complex type that contains general information about the hosted zone. =head2 B<REQUIRED> Location => Str The unique URL representing the new hosted zone. =head2 VPC => L<Paws::Route53::VPC> A complex type that contains information about an Amazon VPC that you associated with this hosted zone. =cut
{ "content_hash": "7498c54b2cb3178c2e5776bc593c9498", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 116, "avg_line_length": 24.10909090909091, "alnum_prop": 0.6870286576168929, "repo_name": "ioanrogers/aws-sdk-perl", "id": "0ee93ffc324edd9011e092d99b927dc4a8851445", "size": "1327", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "auto-lib/Paws/Route53/CreateHostedZoneResponse.pm", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Makefile", "bytes": "1292" }, { "name": "Perl", "bytes": "20360380" }, { "name": "Perl 6", "bytes": "99393" }, { "name": "Shell", "bytes": "445" } ], "symlink_target": "" }
import { Glue42Core } from "../../../../glue"; import { SubscriptionInner } from "../../types"; import ClientRepository from "../../client/repository"; export class UserSubscription implements Glue42Core.Interop.Subscription { public get requestArguments() { return this.subscriptionData.params.arguments || {}; } public get servers(): Glue42Core.Interop.Instance[] { return this.subscriptionData.trackedServers .filter((pair) => pair.subscriptionId) .map((pair) => this.repository.getServerById(pair.serverId).instance); } public get serverInstance(): Glue42Core.Interop.Instance { return this.servers[0]; } public get stream(): Glue42Core.Interop.MethodDefinition { return this.subscriptionData.method; } constructor(private repository: ClientRepository, private subscriptionData: SubscriptionInner) { } public onData(dataCallback: (data: Glue42Core.Interop.StreamData) => void): void { if (typeof dataCallback !== "function") { throw new TypeError("The data callback must be a function."); } this.subscriptionData.handlers.onData.push(dataCallback); if (this.subscriptionData.handlers.onData.length === 1 && this.subscriptionData.queued.data.length > 0) { this.subscriptionData.queued.data.forEach((dataItem) => { dataCallback(dataItem); }); } } public onClosed(closedCallback: (info: Glue42Core.Interop.OnClosedInfo) => void): void { if (typeof closedCallback !== "function") { throw new TypeError("The callback must be a function."); } this.subscriptionData.handlers.onClosed.push(closedCallback); } public onFailed(callback: (err: any) => void): void { // DO NOTHING } public onConnected(callback: (server: Glue42Core.Interop.Instance, reconnect: boolean) => void): void { if (typeof callback !== "function") { throw new TypeError("The callback must be a function."); } this.subscriptionData.handlers.onConnected.push(callback); } public close(): void { this.subscriptionData.close(); } public setNewSubscription(newSub: SubscriptionInner) { this.subscriptionData = newSub; } }
{ "content_hash": "caedd24d3ab9b0cf058793664e2c73e1", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 113, "avg_line_length": 35.815384615384616, "alnum_prop": 0.647766323024055, "repo_name": "StBozov/Core", "id": "6b3c63b13035144306c5e25a1038e266c0358736", "size": "2328", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/core/src/interop/protocols/gw3/subscription.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "31193" } ], "symlink_target": "" }
package com.amazonaws.services.opsworks.model; import java.io.Serializable; import com.amazonaws.AmazonWebServiceRequest; /** * */ public class RebootInstanceRequest extends AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The instance ID. * </p> */ private String instanceId; /** * <p> * The instance ID. * </p> * * @param instanceId * The instance ID. */ public void setInstanceId(String instanceId) { this.instanceId = instanceId; } /** * <p> * The instance ID. * </p> * * @return The instance ID. */ public String getInstanceId() { return this.instanceId; } /** * <p> * The instance ID. * </p> * * @param instanceId * The instance ID. * @return Returns a reference to this object so that method calls can be * chained together. */ public RebootInstanceRequest withInstanceId(String instanceId) { setInstanceId(instanceId); return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getInstanceId() != null) sb.append("InstanceId: " + getInstanceId()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof RebootInstanceRequest == false) return false; RebootInstanceRequest other = (RebootInstanceRequest) obj; if (other.getInstanceId() == null ^ this.getInstanceId() == null) return false; if (other.getInstanceId() != null && other.getInstanceId().equals(this.getInstanceId()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getInstanceId() == null) ? 0 : getInstanceId().hashCode()); return hashCode; } @Override public RebootInstanceRequest clone() { return (RebootInstanceRequest) super.clone(); } }
{ "content_hash": "0b8ac25111a5aaff911a5948e20e27ad", "timestamp": "", "source": "github", "line_count": 112, "max_line_length": 79, "avg_line_length": 22.875, "alnum_prop": 0.5565964090554254, "repo_name": "mhurne/aws-sdk-java", "id": "4c1c282dec9b4da5f8a8cb7008408554b1fc9b07", "size": "3149", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "aws-java-sdk-opsworks/src/main/java/com/amazonaws/services/opsworks/model/RebootInstanceRequest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "FreeMarker", "bytes": "123790" }, { "name": "Java", "bytes": "110875821" }, { "name": "Scilab", "bytes": "3561" } ], "symlink_target": "" }
var _ = require('underscore'); var TaskList = require('./taskList'); var TaskForm = require('./taskForm'); var TaskBox = React.createClass({ displayName: 'TaskBox', loadTasksFromServer: function() { $.ajax({ url: this.props.tasksUrl + '/tasks.json', dataType: 'json', success: function(data) { this.setState({allTodos: data}); }.bind(this), error: function(xhr, status, err) { console.error(this.props.url, status, err.toString()); }.bind(this) }); }, handleTaskSubmit: function(newTask) { $.ajax({ url: this.props.tasksUrl + '/tasks', dataType: 'json', type: 'POST', data: JSON.stringify(newTask), success: function() { this.loadTasksFromServer(); }.bind(this), error: function(xhr, status, err) { console.error(this.props.url, status, err.toString()); }.bind(this) }); }, updateTaskCompletion: function(task) { var patchData = [ { "op": "replace", "path": "/" + task.taskId + "/isCompleted", "value": task.isCompleted } ]; $.ajax({ url: this.props.tasksUrl + '/tasks', dataType: 'text', type: 'PATCH', data: JSON.stringify(patchData), success: function() { this.loadTasksFromServer(); }.bind(this), error: function(xhr, status, err) { console.error(this.props.url, status, err.toString()); }.bind(this) }); }, getInitialState: function() { return { allTodos: this.loadTasksFromServer() }; }, render: function() { var completedTasks = _.values(this.state.allTodos).filter( function(task) {return task.isCompleted;}); return ( React.createElement('div', {class: 'tasksBox'}, React.createElement('h1', {}, "Tasks"), React.createElement('span', {}, "Completed Tasks: " + completedTasks.length), React.createElement(TaskList, { allTodos: this.state.allTodos, toggleTaskCompletion: this.updateTaskCompletion }), React.createElement(TaskForm, { onTaskSubmit: this.handleTaskSubmit }) ) ); } }); module.exports = TaskBox;
{ "content_hash": "40d3eba474c72bc86c43d1159bc52316", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 122, "avg_line_length": 27.628205128205128, "alnum_prop": 0.5930394431554524, "repo_name": "yongpeishi/todolist-app", "id": "6fdedace95fcda5237a0f7b0068e2650ed5da41a", "size": "2155", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/scripts/components/taskBox.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "286" }, { "name": "JavaScript", "bytes": "4254" }, { "name": "Ruby", "bytes": "1582" } ], "symlink_target": "" }
require 'spec_helper' RSpec.describe NotifySubjectSelectorOfSeenWorker do let(:worker) { described_class.new } let(:workflow) { create(:workflow) } let(:subject_id) { 2 } let(:user_id) { 1 } it "should be retryable 3 times" do retry_count = worker.class.get_sidekiq_options['retry'] expect(retry_count).to eq(3) end describe "#perform" do it "should gracefully handle a missing workflow lookup" do expect{ worker.perform(-1, user_id, subject_id) }.not_to raise_error end context "when cellect is off" do it "should not call cellect" do expect(CellectClient).not_to receive(:add_seen) worker.perform(workflow.id, user_id, subject_id) end end context "when cellect is on" do before do allow(Panoptes.flipper).to receive(:enabled?).with("cellect").and_return(true) end it "should not call to cellect if the workflow is not set to use it" do expect(CellectClient).not_to receive(:add_seen) worker.perform(workflow.id, user_id, subject_id) end context "when the workflow is using cellect" do before do allow_any_instance_of(Workflow) .to receive(:using_cellect?).and_return(true) end it "should not call to cellect if the user is nil" do expect(CellectClient).not_to receive(:add_seen) worker.perform(workflow.id, nil, subject_id) end it "should request that cellect add the seen for the subject" do expect(CellectClient) .to receive(:add_seen) .with(workflow.id, user_id, subject_id) worker.perform(workflow.id, user_id, subject_id) end end end end end
{ "content_hash": "7917590a0e7633ffb80efca6898f6ea1", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 86, "avg_line_length": 30.103448275862068, "alnum_prop": 0.631729667812142, "repo_name": "srallen/Panoptes", "id": "8c054ab18f98e5e9f65ee5cb98f997fee9a2342b", "size": "1746", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "spec/workers/notify_subject_selector_of_seen_worker_spec.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "API Blueprint", "bytes": "178762" }, { "name": "CSS", "bytes": "6213" }, { "name": "HTML", "bytes": "55779" }, { "name": "JavaScript", "bytes": "641" }, { "name": "Ruby", "bytes": "1305898" }, { "name": "Shell", "bytes": "1226" } ], "symlink_target": "" }
namespace pw::analog { class GmockMicrovoltInput : public MicrovoltInput { public: MOCK_METHOD(pw::Result<int32_t>, TryReadUntil, (pw::chrono::SystemClock::time_point deadline), (override)); MOCK_METHOD(Limits, GetLimits, (), (const, override)); MOCK_METHOD(References, GetReferences, (), (const, override)); }; } // namespace pw::analog
{ "content_hash": "d55f509d0bac08c3469655dc1b593c95", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 64, "avg_line_length": 26.133333333333333, "alnum_prop": 0.6326530612244898, "repo_name": "google/pigweed", "id": "a6ce9227eddee9adfe3bf3d5fd565c19f666b1e4", "size": "1068", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "pw_analog/public/pw_analog/microvolt_input_gmock.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "8654" }, { "name": "C", "bytes": "487991" }, { "name": "C++", "bytes": "6119052" }, { "name": "CMake", "bytes": "288698" }, { "name": "CSS", "bytes": "4820" }, { "name": "Go", "bytes": "18932" }, { "name": "HTML", "bytes": "1194" }, { "name": "Java", "bytes": "327548" }, { "name": "JavaScript", "bytes": "12482" }, { "name": "Jinja", "bytes": "2467" }, { "name": "Python", "bytes": "3578966" }, { "name": "Rust", "bytes": "645" }, { "name": "SCSS", "bytes": "1382" }, { "name": "Shell", "bytes": "22974" }, { "name": "Smarty", "bytes": "692" }, { "name": "Starlark", "bytes": "489444" }, { "name": "TypeScript", "bytes": "235169" } ], "symlink_target": "" }
"use strict"; /** * Hackathon @ J On The Beach 2017 * VOS (Value ObjectS) file * Path: valo/src/visualizations_js/src/vo/map_point.js * @license MIT * @author Danilo Rossi <drossi@itrsgroup.com> * @author Andres Ramirez <aramirez@itrsgroup.com> * @author Zuri Pabón <zpabon@itrsgroup.com> */ import { runSingleQuery } from '../../../lib_js/valo_sdk_js'; import { isFunction } from 'lodash'; import { HOST, TENANT, REPLAY, REPLAY_INTERVAL } from '../settings' import Rx from 'rx-lite'; /** * It creates new observable which emits events every REPLAY_INTERVAL milliseconds * * @param {RxJS.Observable} observable an RxJS observable * @return RxJS.Observable */ function replayObservabable(observable){ const Identity = i => i; return observable.zip( Rx.Observable.interval(REPLAY_INTERVAL), Identity // Identity function ); } /** * It creates a new Valo session and runs a query in that session * Once query is created on Valo it is started and a new SSE connection is opened * That connection is wrapped around an RxJS observable object so it is just * needed to subscribe to the observable to process the payloads coming from Valo * * @param {Function<ErrorObject, PayloadObject>} callback? If provided, * the observable is not returned. This callback will be called every time a new * event comes or if an error happends. If no callback is provided, the observable * is returned instead. * @return RxJS.Observable? */ export async function readEvents(query, callback){ const { observable } = await runSingleQuery(HOST, TENANT, query); if(!callback || !isFunction(callback)) return observable; const _observable = REPLAY ? replayObservabable(observable) : observable; _observable.subscribe( payload => payload && callback(null, payload), error => callback(error), completed => callback(null, null)); }
{ "content_hash": "a1cd83bec26574a6a47e80835d178ca0", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 82, "avg_line_length": 30.26984126984127, "alnum_prop": 0.708442579968537, "repo_name": "ITRS-Group/hackathon2017", "id": "89f4c6609fa2a45718aad4a117a060d559273b5b", "size": "1908", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "base/src/visualizations_js/src/dao/common.js", "mode": "33188", "license": "mit", "language": [ { "name": "Arduino", "bytes": "27373" }, { "name": "C++", "bytes": "8753" }, { "name": "CSS", "bytes": "10186" }, { "name": "HTML", "bytes": "27515" }, { "name": "JavaScript", "bytes": "217808" }, { "name": "Shell", "bytes": "8119" }, { "name": "TypeScript", "bytes": "19089" } ], "symlink_target": "" }
import PropTypes from 'prop-types'; import React from 'react'; import {sortByString} from '../helpers/SortHelpers'; // This is a sorted table, pass in a list of objects as `rows`, // and then `columns` to describe how to sort and label columns. class FlexibleRoster extends React.Component { constructor(props) { super(props); this.state = { sortByIndex: this.props.initialSortIndex, sortDesc: true }; this.onClickHeader = this.onClickHeader.bind(this); } orderedRows() { const sortedRows = this.sortedRows(); if (!this.state.sortDesc) return sortedRows.reverse(); return sortedRows; } sortedRows() { const rows = this.props.rows; const columns = this.props.columns; const sortByIndex = this.state.sortByIndex; const key = columns[sortByIndex].key; if ('sortFunc' in columns[sortByIndex]) { return rows.sort((a,b) => columns[sortByIndex].sortFunc(a,b,key)); } else { return rows.sort((a, b) => sortByString(a, b, key)); } } headerClassName (sortByIndex) { // Using tablesort classes here for the cute CSS carets, // not for the acutal table sorting JS (that logic is handled by this class). if (sortByIndex !== this.state.sortByIndex) return 'sort-header'; if (this.state.sortDesc) return 'sort-header sort-down'; return 'sort-header sort-up'; } onClickHeader(sortByIndex) { if (sortByIndex === this.state.sortByIndex) { this.setState({ sortDesc: !this.state.sortDesc }); } else { this.setState({ sortByIndex: sortByIndex}); } } render() { return ( <div className='FlexibleRoster'> <table id='roster-table' className='roster-table' style={{ width: '100%' }}> <thead> {this.renderSuperHeaders()} {this.renderHeaders()} </thead> {this.renderBody()} </table> </div> ); } renderSuperHeaders() { const columns = this.props.columns; let superHeaders = []; let currentCount = 0; for (let i=0; i<columns.length; i++) { // group for the current column let itemGroup = columns[i].group; // group for the next column for comparison // set to null if this is the last column let nextItemGroup = columns.length > i+1 ? columns[i+1].group : null; // count of items with the same group // increment in the beginning since colSpan starts at 1 currentCount++; // if the current item doesn't equal the next // push the super header with a length of currentCount // and reset currentCount for a new column group if(itemGroup != nextItemGroup) { superHeaders.push({label: itemGroup, span: currentCount}); currentCount = 0; } } return ( <tr className='column-groups'> {superHeaders.map((superHeader, index) => { return ( <th key={index} className={superHeader.label == null ? '' : 'column-group'} colSpan={superHeader.span}> {superHeader.label} </th> ); })} </tr> ); } renderHeaders() { return ( <tr id='roster-header'> {this.props.columns.map((column, index) => { return ( <th key={column.key} onClick={this.onClickHeader.bind(null, index)} className={this.headerClassName(index)}> {column.label} </th> ); })} </tr> ); } renderBodyValue(item, column) { if ('cell' in column) { return column.cell(item,column); } else { return item[column.key]; } } renderBody() { return ( <tbody id='roster-data'> {this.orderedRows().map((row, index) => { const style = (index % 2 === 0) ? { backgroundColor: '#FFFFFF' } : { backgroundColor: '#F7F7F7' }; return ( <tr key={row.id} style={style}> {this.props.columns.map(column => { return ( <td key={row.id + column.key}> {this.renderBodyValue(row, column)} </td> ); })} </tr> ); })} </tbody> ); } } FlexibleRoster.propTypes = { rows: PropTypes.arrayOf(PropTypes.object).isRequired, columns: PropTypes.arrayOf(PropTypes.object).isRequired, initialSortIndex: PropTypes.number }; export default FlexibleRoster;
{ "content_hash": "a718ab08bbe1ef02c369bc1c7889dfad", "timestamp": "", "source": "github", "line_count": 167, "max_line_length": 115, "avg_line_length": 26.98802395209581, "alnum_prop": 0.5726647437319725, "repo_name": "studentinsights/studentinsights", "id": "d9c3441483ae4f77b754a0c6029378f0c6c9ba84", "size": "4507", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/assets/javascripts/components/FlexibleRoster.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "8550" }, { "name": "HTML", "bytes": "67602" }, { "name": "JavaScript", "bytes": "2068243" }, { "name": "Procfile", "bytes": "173" }, { "name": "Ruby", "bytes": "1879416" }, { "name": "SCSS", "bytes": "16368" }, { "name": "Shell", "bytes": "30425" } ], "symlink_target": "" }
/* fficonfig.h. Generated from fficonfig.h.in by configure. */ /* fficonfig.h.in. Generated from configure.ac by autoheader. */ /* Define if building universal (internal helper macro) */ /* #undef AC_APPLE_UNIVERSAL_BUILD */ /* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP systems. This function is required for `alloca.c' support on those systems. */ /* #undef CRAY_STACKSEG_END */ /* Define to 1 if using `alloca.c'. */ /* #undef C_ALLOCA */ /* Define to the flags needed for the .section .eh_frame directive. */ /* #undef EH_FRAME_FLAGS */ /* Define this if you want extra debugging. */ /* #undef FFI_DEBUG */ /* Cannot use PROT_EXEC on this target, so, we revert to alternative means */ /* #undef FFI_EXEC_TRAMPOLINE_TABLE */ /* Define this if you want to enable pax emulated trampolines */ /* #undef FFI_MMAP_EXEC_EMUTRAMP_PAX */ /* Cannot use malloc on this target, so, we revert to alternative means */ /* #undef FFI_MMAP_EXEC_WRIT */ /* Define this if you do not want support for the raw API. */ /* #undef FFI_NO_RAW_API */ /* Define this if you do not want support for aggregate types. */ /* #undef FFI_NO_STRUCTS */ /* Define to 1 if you have `alloca', as a function or macro. */ #define HAVE_ALLOCA 1 /* Define to 1 if you have <alloca.h> and it should be used (not on Ultrix). */ /* #undef HAVE_ALLOCA_H */ /* Define if your assembler supports .ascii. */ /* #undef HAVE_AS_ASCII_PSEUDO_OP */ /* Define if your assembler supports .cfi_* directives. */ /* #undef HAVE_AS_CFI_PSEUDO_OP */ /* Define if your assembler supports .register. */ /* #undef HAVE_AS_REGISTER_PSEUDO_OP */ /* Define if your assembler and linker support unaligned PC relative relocs. */ /* #undef HAVE_AS_SPARC_UA_PCREL */ /* Define if your assembler supports .string. */ /* #undef HAVE_AS_STRING_PSEUDO_OP */ /* Define if your assembler supports unwind section type. */ /* #undef HAVE_AS_X86_64_UNWIND_SECTION_TYPE */ /* Define if your assembler supports PC relative relocs. */ #define HAVE_AS_X86_PCREL 1 /* Define to 1 if you have the <dlfcn.h> header file. */ /* #undef HAVE_DLFCN_H */ /* Define if __attribute__((visibility("hidden"))) is supported. */ /* #undef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE */ /* Define to 1 if you have the <inttypes.h> header file. */ /* #undef HAVE_INTTYPES_H */ /* Define if you have the long double type and it is bigger than a double */ /* #undef HAVE_LONG_DOUBLE */ /* Define if you support more than one size of the long double type */ /* #undef HAVE_LONG_DOUBLE_VARIANT */ /* Define to 1 if you have the `memcpy' function. */ #define HAVE_MEMCPY 1 /* Define to 1 if you have the <memory.h> header file. */ #define HAVE_MEMORY_H 1 /* Define to 1 if you have the `mkostemp' function. */ /* #undef HAVE_MKOSTEMP */ /* Define to 1 if you have the `mmap' function. */ /* #undef HAVE_MMAP */ /* Define if mmap with MAP_ANON(YMOUS) works. */ /* #undef HAVE_MMAP_ANON */ /* Define if mmap of /dev/zero works. */ /* #undef HAVE_MMAP_DEV_ZERO */ /* Define if read-only mmap of a plain file works. */ /* #undef HAVE_MMAP_FILE */ /* Define if .eh_frame sections should be read-only. */ /* #undef HAVE_RO_EH_FRAME */ /* Define to 1 if you have the <stdint.h> header file. */ #define HAVE_STDINT_H 1 /* Define to 1 if you have the <stdlib.h> header file. */ #define HAVE_STDLIB_H 1 /* Define to 1 if you have the <strings.h> header file. */ /* #undef HAVE_STRINGS_H */ /* Define to 1 if you have the <string.h> header file. */ #define HAVE_STRING_H 1 /* Define to 1 if you have the <sys/mman.h> header file. */ /* #undef HAVE_SYS_MMAN_H */ /* Define to 1 if you have the <sys/stat.h> header file. */ #define HAVE_SYS_STAT_H 1 /* Define to 1 if you have the <sys/types.h> header file. */ #define HAVE_SYS_TYPES_H 1 /* Define to 1 if you have the <unistd.h> header file. */ /* #undef HAVE_UNISTD_H */ /* Define to the sub-directory in which libtool stores uninstalled libraries. */ #define LT_OBJDIR ".libs/" /* Define to 1 if your C compiler doesn't accept -c and -o together. */ /* #undef NO_MINUS_C_MINUS_O */ /* Name of package */ #define PACKAGE "libffi" /* Define to the address where bug reports for this package should be sent. */ #define PACKAGE_BUGREPORT "http://sourceware.org/libffi.html" /* Define to the full name of this package. */ #define PACKAGE_NAME "libffi" /* Define to the full name and version of this package. */ #define PACKAGE_STRING "libffi 3.0.10" /* Define to the one symbol short name of this package. */ #define PACKAGE_TARNAME "libffi" /* Define to the home page for this package. */ #define PACKAGE_URL "" /* Define to the version of this package. */ #define PACKAGE_VERSION "3.0.10" /* The size of `double', as computed by sizeof. */ #define SIZEOF_DOUBLE 8 /* The size of `long double', as computed by sizeof. */ #define SIZEOF_LONG_DOUBLE 8 /* The size of `size_t', as computed by sizeof. */ #ifdef _WIN64 #define SIZEOF_SIZE_T 8 #else #define SIZEOF_SIZE_T 4 #endif /* If using the C implementation of alloca, define if you know the direction of stack growth for your system; otherwise it will be automatically deduced at runtime. STACK_DIRECTION > 0 => grows toward higher addresses STACK_DIRECTION < 0 => grows toward lower addresses STACK_DIRECTION = 0 => direction of growth unknown */ /* #undef STACK_DIRECTION */ /* Define to 1 if you have the ANSI C header files. */ #define STDC_HEADERS 1 /* Define if symbols are underscored. */ #define SYMBOL_UNDERSCORE 1 /* Define this if you are using Purify and want to suppress spurious messages. */ /* #undef USING_PURIFY */ /* Version number of package */ #define VERSION "3.0.10" /* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most significant byte first (like Motorola and SPARC, unlike Intel). */ #if defined AC_APPLE_UNIVERSAL_BUILD # if defined __BIG_ENDIAN__ # define WORDS_BIGENDIAN 1 # endif #else # ifndef WORDS_BIGENDIAN /* # undef WORDS_BIGENDIAN */ # endif #endif /* Define to `unsigned int' if <sys/types.h> does not define. */ /* #undef size_t */ #ifdef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE #ifdef LIBFFI_ASM #define FFI_HIDDEN(name) .hidden name #else #define FFI_HIDDEN __attribute__ ((visibility ("hidden"))) #endif #else #ifdef LIBFFI_ASM #define FFI_HIDDEN(name) #else #define FFI_HIDDEN #endif #endif
{ "content_hash": "632e1dd7b19f2dfaae231ae8387a47fc", "timestamp": "", "source": "github", "line_count": 219, "max_line_length": 78, "avg_line_length": 29.01826484018265, "alnum_prop": 0.6887490165224233, "repo_name": "coapp-packages/libffi", "id": "75cac14146cd50bda5510bea6715d95240f08c1f", "size": "6355", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "COPKG/libffi/libffi/fficonfig.h", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "543907" }, { "name": "Batchfile", "bytes": "1178" }, { "name": "C", "bytes": "1108971" }, { "name": "C++", "bytes": "9082" }, { "name": "Groff", "bytes": "210525" }, { "name": "Python", "bytes": "6613" }, { "name": "Shell", "bytes": "355360" }, { "name": "TeX", "bytes": "323102" } ], "symlink_target": "" }
""" version.py module The version set here will be automatically incorporated into setup.py and also set as the __version__ attribute for the package. "dev", "rc", and other verison tags should be added using the ``setup.py egg_info`` command when creating distributions. """ from __future__ import ( absolute_import, division, print_function, unicode_literals ) __version_info__ = (0, 2, 0) __version__ = '.'.join([str(ver) for ver in __version_info__])
{ "content_hash": "0f541f9c07acf943693733155e182400", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 69, "avg_line_length": 30.8, "alnum_prop": 0.7034632034632035, "repo_name": "ihiji/falcon-marshmallow", "id": "dda59551f5dccbca68b366245f42d63417348889", "size": "486", "binary": false, "copies": "1", "ref": "refs/heads/development", "path": "falcon_marshmallow/_version.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "48145" } ], "symlink_target": "" }
describe User do before do @user = User.new(name: "example", password: "foobar", password_confirmation: "foobar") end subject { @user } it { should respond_to(:name) } it { should respond_to(:password_digest) } it { should respond_to(:password) } it { should respond_to(:password_confirmation) } it { should respond_to(:authenticate) } it { should respond_to(:remember_token) } it { should be_valid } describe "accessible attributes" do it "should not allow access to user_id" do expect do User.new(admin: true) end.to raise_error(ActiveModel::MassAssignmentSecurity::Error) end end describe "when name is not present" do before { @user.name = " " } it { should_not be_valid } end describe "when name is too long" do before { @user.name = "a" * 21 } it { should_not be_valid } end describe "when name is already taken" do before do user_with_same_name = @user.dup user_with_same_name.save end it { should_not be_valid } end describe "when password is not present" do before { @user.password = @user.password_confirmation = " "} it { should_not be_valid } end describe "when password doesn't match confirmation" do before { @user.password_confirmation = "mismatch" } it { should_not be_valid } end describe "when password confirmation is nil" do before { @user.password_confirmation = nil } it { should_not be_valid } end describe "return value of authenticate method" do before { @user.save } let(:found_user) { User.find_by_name(@user.name) } describe "with valid password" do it { should == found_user.authenticate(@user.password) } end describe "with invalid password" do let(:user_for_invalid_password) { found_user.authenticate("invalid") } it { should_not == user_for_invalid_password } specify { user_for_invalid_password.should be_false } end end describe "with password that's too short" do before { @user.password = @user.password_confirmation = "a" * 5 } it { should be_invalid } end describe "remember token" do before { @user.save } its(:remember_token) { should_not be_blank } end end
{ "content_hash": "14d58149776bb92749dce452ed6ce181", "timestamp": "", "source": "github", "line_count": 86, "max_line_length": 90, "avg_line_length": 26.023255813953487, "alnum_prop": 0.6519213583556747, "repo_name": "cristianjd/contextbeats", "id": "91f9f239fe4974835957f3f03726e9ec70c503e0", "size": "2238", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/models/user_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "6492" }, { "name": "JavaScript", "bytes": "6018" }, { "name": "Ruby", "bytes": "40640" } ], "symlink_target": "" }
package com.github.dstapen.sshmavenplugin; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.File; import java.util.concurrent.TimeUnit; @RunWith(Parameterized.class) public class DownloadFileMojoTest extends ParametrizedTransferTest { @Test public void testDownloadFileMojo() throws Exception { TimeUnit.SECONDS.sleep(1L); UploadFileMojo arrangement = new UploadFileMojo("localhost", SSH_HOST_PORT, SSH_USERNAME, true, SSH_PASSWORD, 1_000, local, remote, false); arrangement.execute(); File tempFile = File.createTempFile("downloaded_little", ".tmp"); tempFile.deleteOnExit(); DownloadFileMojo sut = new DownloadFileMojo("localhost", SSH_HOST_PORT, SSH_USERNAME, true, SSH_PASSWORD, 1000, remote, tempFile.getAbsolutePath(), false); sut.execute(); } }
{ "content_hash": "8966ec83ccfb3784fc51f10ad74d66cc", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 103, "avg_line_length": 31.733333333333334, "alnum_prop": 0.6817226890756303, "repo_name": "dstapen/ssh-maven-plugin", "id": "a51c0b8d890354f3c4ea3be000f164d9e623555b", "size": "952", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/com/github/dstapen/sshmavenplugin/DownloadFileMojoTest.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "24817" } ], "symlink_target": "" }
package in.ceeq.help; import in.ceeq.R; import java.util.ArrayList; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.os.Build; import android.os.Bundle; import android.support.v4.app.NavUtils; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; import android.widget.ExpandableListAdapter; import android.widget.ExpandableListView; import android.widget.TextView; import com.bugsense.trace.BugSenseHandler; public class HelpActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_help); setupActionbar(); setupBugsense(); createHelpQuestions(); createHelpAnswers(); setupHelplist(); getActionBar().setBackgroundDrawable(getResources().getDrawable(R.color.blue)); } private ExpandableListView helpList; private ExpandableListAdapter helpListAdapter; public void setupHelplist() { helpList = (ExpandableListView) findViewById(R.id.helpList); helpListAdapter = new ListAdapter(this, help_list, text_list); helpList.setAdapter(helpListAdapter); } public void setupBugsense() { BugSenseHandler.initAndStartSession(HelpActivity.this, "5996b3d9"); } ArrayList<String> help_list, text_list; public void createHelpQuestions() { help_list = new ArrayList<String>(); help_list.add("What is Ceeq ?"); help_list.add("Why enable GPS ?"); help_list.add("Why enable Device Administrator ?"); help_list.add("What are Remote Commands ?"); help_list.add("Why so many permissions ?"); help_list.add("What is Protect Me ?"); help_list.add("What is Online Sync ?"); help_list.add("What is One Click Backup"); help_list.add("What is Stealth Mode"); help_list.add("What about my privacy & data ?"); help_list.add("Contact the developer"); } public void createHelpAnswers() { text_list = new ArrayList<String>(); text_list.add(getString(R.string.help_note_7)); text_list.add(getString(R.string.help_note_8)); text_list.add(getString(R.string.help_note_9)); text_list.add(getString(R.string.help_note_10)); text_list.add(getString(R.string.help_note_11)); text_list.add(getString(R.string.help_note_12)); text_list.add(getString(R.string.help_note_13)); text_list.add(getString(R.string.help_note_14)); text_list.add(getString(R.string.help_note_15)); text_list.add(getString(R.string.help_note_16)); text_list.add(getString(R.string.help_note_17)); } public class ListAdapter extends BaseExpandableListAdapter { public ArrayList<String> h_list, i_list = new ArrayList<String>(); public LayoutInflater inflater; public Context context; public ListAdapter(Context context, ArrayList<String> h_list, ArrayList<String> i_list) { this.context = context; this.h_list = h_list; this.i_list = i_list; this.inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public Object getChild(int groupPosition, int childPosition) { return null; } @Override public long getChildId(int groupPosition, int childPosition) { return 0; } @Override public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { TextView text = null; if (convertView == null) { convertView = inflater.inflate(R.layout.list_help_inner, null); } text = (TextView) convertView.findViewById(R.id.n_text); text.setText(text_list.get(groupPosition)); return convertView; } @Override public int getChildrenCount(int groupPosition) { return 1; } @Override public Object getGroup(int groupPosition) { return null; } @Override public int getGroupCount() { return h_list.size(); } @Override public void onGroupCollapsed(int groupPosition) { super.onGroupCollapsed(groupPosition); } @Override public void onGroupExpanded(int groupPosition) { super.onGroupExpanded(groupPosition); } @Override public long getGroupId(int groupPosition) { return 0; } @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { if (convertView == null) { convertView = inflater.inflate(R.layout.list_help_outer, null); } TextView header = (TextView) convertView .findViewById(R.id.n_header); header.setText(h_list.get(groupPosition)); return convertView; } @Override public boolean hasStableIds() { return false; } @Override public boolean isChildSelectable(int groupPosition, int childPosition) { return false; } } @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void setupActionbar() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setDisplayShowHomeEnabled(false); } } public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: NavUtils.navigateUpFromSameTask(this); return true; } return super.onOptionsItemSelected(item); } }
{ "content_hash": "19c2bb13b2d678f7d2cd1663d1c776f3", "timestamp": "", "source": "github", "line_count": 196, "max_line_length": 81, "avg_line_length": 26.79591836734694, "alnum_prop": 0.734958111195735, "repo_name": "ceeq/project-ceeq", "id": "dcb803566b49b2bd1617849c9f1e801586fd0fae", "size": "5363", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/in/ceeq/help/HelpActivity.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "365398" } ], "symlink_target": "" }
<?php namespace iio\phplibphone\Library; use iio\phplibphone\Exception; use SimpleXMLElement; use iio\phplibphone\CarrierLookupInterface; /** * Fetch carrier information for swedish phone numbers from api.pts.se * * @author Hannes Forsgård <hannes.forsgard@gmail.com> * @package phplibphone */ class CarriersSe implements CarrierLookupInterface { /** * Get country code this library handles * * @return int */ public function getCountryCode() { return 46; } /** * Fetch carrier information from api.pts.se * * @param string $ndc National destination code * @param string $sn Subscriber number * @return string Carrier description * @throws Exception if unable to reach api.pts.se, or XML is broken */ public function lookup($ndc, $sn) { $url = "http://api.pts.se/ptsnumber/ptsnumber.asmx/SearchByNumber"; $query = sprintf('?Ndc=%s&Number=%s', urlencode($ndc), urlencode($sn)); $page = @file_get_contents($url . $query); if (!$page) { throw new Exception("Unable to fetch carrier from '$url'"); } libxml_use_internal_errors(true); $xml = new SimpleXMLElement($page); if (!$xml instanceof SimpleXMLElement) { throw new Exception("Invalid XML returned from '$url'"); } foreach ($xml->children() as $node) { if ($node->getName() == 'Operator') { return (string)$node; } } throw new Exception("Operator node missing from '$url'"); } }
{ "content_hash": "8fca19d067add61238763538f90b8c9a", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 79, "avg_line_length": 26.016129032258064, "alnum_prop": 0.6007439553626782, "repo_name": "hanneskod/phplibphone", "id": "ce97a9e74a366cc0ee5a7f5e03e338732bd3114f", "size": "1841", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/iio/phplibphone/Library/CarriersSe.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "41366" } ], "symlink_target": "" }
require "benchmark" require "abstract_controller/logger" module ActionController # Adds instrumentation to several ends in ActionController::Base. It also provides # some hooks related with process_action. This allows an ORM like Active Record # and/or DataMapper to plug in ActionController and show related information. # # Check ActiveRecord::Railties::ControllerRuntime for an example. module Instrumentation extend ActiveSupport::Concern include AbstractController::Logger attr_internal :view_runtime def process_action(*) raw_payload = { controller: self.class.name, action: action_name, request: request, params: request.filtered_parameters, headers: request.headers, format: request.format.ref, method: request.request_method, path: request.fullpath } ActiveSupport::Notifications.instrument("start_processing.action_controller", raw_payload) ActiveSupport::Notifications.instrument("process_action.action_controller", raw_payload) do |payload| result = super payload[:response] = response payload[:status] = response.status result rescue => error payload[:status] = ActionDispatch::ExceptionWrapper.status_code_for_exception(error.class.name) raise ensure append_info_to_payload(payload) end end def render(*) render_output = nil self.view_runtime = cleanup_view_runtime do Benchmark.ms { render_output = super } end render_output end def send_file(path, options = {}) ActiveSupport::Notifications.instrument("send_file.action_controller", options.merge(path: path)) do super end end def send_data(data, options = {}) ActiveSupport::Notifications.instrument("send_data.action_controller", options) do super end end def redirect_to(*) ActiveSupport::Notifications.instrument("redirect_to.action_controller", request: request) do |payload| result = super payload[:status] = response.status payload[:location] = response.filtered_location result end end private # A hook invoked every time a before callback is halted. def halted_callback_hook(filter, _) ActiveSupport::Notifications.instrument("halted_callback.action_controller", filter: filter) end # A hook which allows you to clean up any time, wrongly taken into account in # views, like database querying time. # # def cleanup_view_runtime # super - time_taken_in_something_expensive # end def cleanup_view_runtime # :doc: yield end # Every time after an action is processed, this method is invoked # with the payload, so you can add more information. def append_info_to_payload(payload) # :doc: payload[:view_runtime] = view_runtime end module ClassMethods # A hook which allows other frameworks to log what happened during # controller process action. This method should return an array # with the messages to be added. def log_process_action(payload) #:nodoc: messages, view_runtime = [], payload[:view_runtime] messages << ("Views: %.1fms" % view_runtime.to_f) if view_runtime messages end end end end
{ "content_hash": "fae6c592c1cf030910096d8574d2c24f", "timestamp": "", "source": "github", "line_count": 107, "max_line_length": 109, "avg_line_length": 31.672897196261683, "alnum_prop": 0.6674535261138979, "repo_name": "bogdanvlviv/rails", "id": "62e0c351fce39fdc07b538e78dde0064c30d8ad8", "size": "3420", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "actionpack/lib/action_controller/metal/instrumentation.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "44762" }, { "name": "CoffeeScript", "bytes": "24543" }, { "name": "HTML", "bytes": "476880" }, { "name": "JavaScript", "bytes": "131711" }, { "name": "Ruby", "bytes": "13717764" }, { "name": "SCSS", "bytes": "979" }, { "name": "Shell", "bytes": "4531" }, { "name": "Yacc", "bytes": "1003" } ], "symlink_target": "" }
Browser base64 Session Description<br /> <textarea id="localSessionDescription" readonly="true"></textarea> <br /> <button onclick="window.copySDP()"> Copy browser SDP to clipboard </button> <br /> <br /> Golang base64 Session Description<br /> <textarea id="remoteSessionDescription"></textarea> <br/> <button onclick="window.startSession()"> Start Session </button><br /> <br /> Video<br /> <video id="video1" width="160" height="120" autoplay muted></video> <br /> Logs<br /> <div id="logs"></div>
{ "content_hash": "7ef1c6bd76dfec6cb9da186e73ac8798", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 74, "avg_line_length": 26.63157894736842, "alnum_prop": 0.6976284584980237, "repo_name": "pion/webrtc", "id": "363b3fb2d2a85479cf3205523d1678020cbf128d", "size": "506", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "examples/rtp-forwarder/jsfiddle/demo.html", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "236" }, { "name": "Go", "bytes": "979460" }, { "name": "HTML", "bytes": "1061" }, { "name": "JavaScript", "bytes": "270" }, { "name": "Shell", "bytes": "859" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_79) on Thu Sep 17 01:49:46 IST 2015 --> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>org.apache.solr.morphlines.cell (Solr 5.3.1 API)</title> <meta name="date" content="2015-09-17"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <h1 class="bar"><a href="../../../../../org/apache/solr/morphlines/cell/package-summary.html" target="classFrame">org.apache.solr.morphlines.cell</a></h1> <div class="indexContainer"> <h2 title="Classes">Classes</h2> <ul title="Classes"> <li><a href="SolrCellBuilder.html" title="class in org.apache.solr.morphlines.cell" target="classFrame">SolrCellBuilder</a></li> <li><a href="StripNonCharSolrContentHandlerFactory.html" title="class in org.apache.solr.morphlines.cell" target="classFrame">StripNonCharSolrContentHandlerFactory</a></li> <li><a href="TrimSolrContentHandlerFactory.html" title="class in org.apache.solr.morphlines.cell" target="classFrame">TrimSolrContentHandlerFactory</a></li> </ul> </div> </body> </html>
{ "content_hash": "9ea2a0742c5918cad0d3c7b32326c8dd", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 172, "avg_line_length": 55.86363636363637, "alnum_prop": 0.7152156224572823, "repo_name": "TitasNandi/Summer_Project", "id": "ebedf4dbbca37adbfdb81f7226a00ed0689b142c", "size": "1229", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "solr-5.3.1/docs/solr-morphlines-cell/org/apache/solr/morphlines/cell/package-frame.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AMPL", "bytes": "291" }, { "name": "Batchfile", "bytes": "119331" }, { "name": "C", "bytes": "620" }, { "name": "CSS", "bytes": "746530" }, { "name": "Groff", "bytes": "8389332" }, { "name": "Groovy", "bytes": "887" }, { "name": "HTML", "bytes": "84461564" }, { "name": "Java", "bytes": "22523686" }, { "name": "JavaScript", "bytes": "1254038" }, { "name": "Jupyter Notebook", "bytes": "413571" }, { "name": "Makefile", "bytes": "4287" }, { "name": "Perl", "bytes": "15597" }, { "name": "Python", "bytes": "1888984" }, { "name": "Shell", "bytes": "177570" }, { "name": "XQuery", "bytes": "11244" }, { "name": "XSLT", "bytes": "390648" } ], "symlink_target": "" }
package com.github.kelebra.security.identifier.factory; import com.github.kelebra.security.identifier.exceptions.UnknownSecurityIdentifierType; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.Arrays; import java.util.Collection; import static org.assertj.core.api.Assertions.assertThat; @RunWith(Parameterized.class) public class SecurityIdentifierFactoryTest { private final String securityIdentifier; private final SecurityIdentifierType securityIdentifierType; public SecurityIdentifierFactoryTest(String securityIdentifier, SecurityIdentifierType securityIdentifierType) { this.securityIdentifier = securityIdentifier; this.securityIdentifierType = securityIdentifierType; } @Parameterized.Parameters(name = "{1} - {0}") public static Collection primeNumbers() { return Arrays.asList(new Object[][]{ {"037833100", SecurityIdentifierType.CUSIP}, {"US0378331005", SecurityIdentifierType.ISIN}, {"0263494", SecurityIdentifierType.SEDOL} }); } @Test public void factoryShouldDetermineCusipType() throws UnknownSecurityIdentifierType { assertThat(SecurityIdentifierFactory.getType(securityIdentifier)).isEqualTo(securityIdentifierType); } }
{ "content_hash": "895d33b2dd512d907f7559ea92ee534c", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 116, "avg_line_length": 36.24324324324324, "alnum_prop": 0.7576435495898584, "repo_name": "kelebra/security-identifier", "id": "123268f95896015f8f55332785479f99fcc45d33", "size": "1341", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/com/github/kelebra/security/identifier/factory/SecurityIdentifierFactoryTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "24397" } ], "symlink_target": "" }