code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
/* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "flag" "fmt" "io/ioutil" "os" "strings" ) var ( yamlPaths = flag.String("yaml", "", "comma-separated list of input YAML files") printText = flag.Bool("print-text", false, "print generated proto in text format to stdout") outputPath = flag.String("output", "", "output path to save generated protobuf data") ) func errExit(format string, a ...interface{}) { fmt.Fprintf(os.Stderr, format, a...) os.Exit(1) } func main() { flag.Parse() yamlFiles := strings.Split(*yamlPaths, ",") if len(yamlFiles) == 0 || yamlFiles[0] == "" { errExit("Must specify one or more YAML files with --yaml\n") } if !*printText && *outputPath == "" { errExit("Must set --print-text or --output\n") } if *printText && *outputPath != "" { errExit("Cannot set both --print-text and --output\n") } var c Config for _, file := range yamlFiles { b, err := ioutil.ReadFile(file) if err != nil { errExit("IO Error : Cannot Read File %s : %v\n", file, err) } if err = c.Update(b); err != nil { errExit("Error parsing file %s : %v\n", file, err) } } if *printText { if err := c.MarshalText(os.Stdout); err != nil { errExit("err printing proto: %v", err) } } else { b, err := c.MarshalBytes() if err != nil { errExit("err encoding proto: %v", err) } if err = ioutil.WriteFile(*outputPath, b, 0644); err != nil { errExit("IO Error : Cannot Write File %v\n", outputPath) } } }
krousey/test-infra
testgrid/cmd/config/main.go
GO
apache-2.0
2,010
package org.galaxy.myhttp; import org.junit.Test; import static org.junit.Assert.*; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
galaxy-captain/MyHttp
app/src/test/java/org/galaxy/myhttp/ExampleUnitTest.java
Java
apache-2.0
310
--- layout: post title: 'Ubuntu 下的录屏软件 kazam' date: '2017-05-07' header-img: "img/post-bg-unix.jpg" tags: - Ubuntu author: 'Bro Qiang' --- # Ubuntu 下的录屏软件 软件有很多,不过个人觉得 kazam 用起来最顺手 ## 软件安装 ```shell sudo apt-get install kazam ``` ## 使用 快捷键 `Alt+F2` 输入 `kazam` 即可打开软件 ## 快捷键 -- 开始录 - `Win+R` -- 暂停 - `Win+P` -- 结束保存 - `Win+F` ## 麦克风杂音很大处理 使用 alsamixer 工具 ```shell $ sudo alsamixer ``` 将里面的配置,红色的全都改成绿色即可,不过我的改完之后麦克声音特别小,不清楚是Ubuntu支持的不好,还是麦克太差了……
BroQiang/broqiang.github.io
_posts/2017-05-07-Ubuntu-ScreenCaptureSoftware.md
Markdown
apache-2.0
714
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class Scanning_keluar_Edit Inherits System.Windows.Forms.Form 'Form overrides dispose to clean up the component list. <System.Diagnostics.DebuggerNonUserCode()> _ Protected Overrides Sub Dispose(ByVal disposing As Boolean) Try If disposing AndAlso components IsNot Nothing Then components.Dispose() End If Finally MyBase.Dispose(disposing) End Try End Sub 'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. <System.Diagnostics.DebuggerStepThrough()> _ Private Sub InitializeComponent() Me.components = New System.ComponentModel.Container Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(Scanning_keluar_Edit)) Me.LBLNama = New System.Windows.Forms.Label Me.ListView1 = New System.Windows.Forms.ListView Me.FileName = New System.Windows.Forms.ColumnHeader Me.Lokasi = New System.Windows.Forms.ColumnHeader Me.BTNScan = New System.Windows.Forms.Button Me.GroupBox1 = New System.Windows.Forms.GroupBox Me.BTNHapus = New System.Windows.Forms.Button Me.BTNSImpan = New System.Windows.Forms.Button Me.Label1 = New System.Windows.Forms.Label Me._twain32 = New Saraff.Twain.Twain32(Me.components) Me.Label12 = New System.Windows.Forms.Label Me.Label23 = New System.Windows.Forms.Label Me.GroupBox3 = New System.Windows.Forms.GroupBox Me.BTNTutup = New System.Windows.Forms.Button Me.picboxDeleteAll = New System.Windows.Forms.PictureBox Me.picboxDelete = New System.Windows.Forms.PictureBox Me.PictureBox1 = New System.Windows.Forms.PictureBox Me.ToolTip1 = New System.Windows.Forms.ToolTip(Me.components) Me.GroupBox1.SuspendLayout() Me.GroupBox3.SuspendLayout() CType(Me.picboxDeleteAll, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.picboxDelete, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.PictureBox1, System.ComponentModel.ISupportInitialize).BeginInit() Me.SuspendLayout() ' 'LBLNama ' Me.LBLNama.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle Me.LBLNama.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.LBLNama.Location = New System.Drawing.Point(94, 34) Me.LBLNama.Name = "LBLNama" Me.LBLNama.Size = New System.Drawing.Size(133, 23) Me.LBLNama.TabIndex = 5 Me.ToolTip1.SetToolTip(Me.LBLNama, "Nama File") ' 'ListView1 ' Me.ListView1.Columns.AddRange(New System.Windows.Forms.ColumnHeader() {Me.FileName, Me.Lokasi}) Me.ListView1.Dock = System.Windows.Forms.DockStyle.Bottom Me.ListView1.Location = New System.Drawing.Point(3, 19) Me.ListView1.Name = "ListView1" Me.ListView1.Size = New System.Drawing.Size(230, 151) Me.ListView1.TabIndex = 0 Me.ListView1.UseCompatibleStateImageBehavior = False Me.ListView1.View = System.Windows.Forms.View.Details ' 'FileName ' Me.FileName.Text = "Nama File" ' 'Lokasi ' Me.Lokasi.Text = "Lokasi" ' 'BTNScan ' Me.BTNScan.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.BTNScan.Location = New System.Drawing.Point(65, 74) Me.BTNScan.Name = "BTNScan" Me.BTNScan.Size = New System.Drawing.Size(122, 43) Me.BTNScan.TabIndex = 6 Me.BTNScan.Text = "Scan" Me.ToolTip1.SetToolTip(Me.BTNScan, "Scan") Me.BTNScan.UseVisualStyleBackColor = True ' 'GroupBox1 ' Me.GroupBox1.Controls.Add(Me.BTNScan) Me.GroupBox1.Controls.Add(Me.BTNHapus) Me.GroupBox1.Controls.Add(Me.LBLNama) Me.GroupBox1.Controls.Add(Me.BTNSImpan) Me.GroupBox1.Controls.Add(Me.Label1) Me.GroupBox1.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.GroupBox1.Location = New System.Drawing.Point(347, 11) Me.GroupBox1.Name = "GroupBox1" Me.GroupBox1.Size = New System.Drawing.Size(236, 184) Me.GroupBox1.TabIndex = 169 Me.GroupBox1.TabStop = False Me.GroupBox1.Text = "Scanning" ' 'BTNHapus ' Me.BTNHapus.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.BTNHapus.Location = New System.Drawing.Point(128, 136) Me.BTNHapus.Name = "BTNHapus" Me.BTNHapus.Size = New System.Drawing.Size(99, 31) Me.BTNHapus.TabIndex = 7 Me.BTNHapus.Text = "Hapus" Me.ToolTip1.SetToolTip(Me.BTNHapus, "Hapus Hasil Scan") Me.BTNHapus.UseVisualStyleBackColor = True ' 'BTNSImpan ' Me.BTNSImpan.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.BTNSImpan.Location = New System.Drawing.Point(21, 136) Me.BTNSImpan.Name = "BTNSImpan" Me.BTNSImpan.Size = New System.Drawing.Size(93, 31) Me.BTNSImpan.TabIndex = 6 Me.BTNSImpan.Text = "Simpan" Me.ToolTip1.SetToolTip(Me.BTNSImpan, "Simpan Hasil Scan") Me.BTNSImpan.UseVisualStyleBackColor = True ' 'Label1 ' Me.Label1.AutoSize = True Me.Label1.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.Label1.Location = New System.Drawing.Point(18, 38) Me.Label1.Name = "Label1" Me.Label1.Size = New System.Drawing.Size(70, 16) Me.Label1.TabIndex = 4 Me.Label1.Text = "Nama File" ' '_twain32 ' Me._twain32.AppProductName = "Saraff.Twain" Me._twain32.Parent = Nothing ' 'Label12 ' Me.Label12.AutoSize = True Me.Label12.BackColor = System.Drawing.Color.WhiteSmoke Me.Label12.Font = New System.Drawing.Font("Segoe UI", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.Label12.Location = New System.Drawing.Point(363, 387) Me.Label12.Margin = New System.Windows.Forms.Padding(4, 0, 4, 0) Me.Label12.Name = "Label12" Me.Label12.Size = New System.Drawing.Size(106, 15) Me.Label12.TabIndex = 171 Me.Label12.Text = "Delete && Delete All" ' 'Label23 ' Me.Label23.AutoSize = True Me.Label23.Location = New System.Drawing.Point(472, 198) Me.Label23.Name = "Label23" Me.Label23.Size = New System.Drawing.Size(45, 13) Me.Label23.TabIndex = 174 Me.Label23.Text = "Label23" Me.Label23.Visible = False ' 'GroupBox3 ' Me.GroupBox3.Controls.Add(Me.ListView1) Me.GroupBox3.Location = New System.Drawing.Point(347, 211) Me.GroupBox3.Name = "GroupBox3" Me.GroupBox3.Size = New System.Drawing.Size(236, 173) Me.GroupBox3.TabIndex = 170 Me.GroupBox3.TabStop = False Me.GroupBox3.Text = "Daftar Gambar" ' 'BTNTutup ' Me.BTNTutup.DialogResult = System.Windows.Forms.DialogResult.Cancel Me.BTNTutup.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.BTNTutup.Location = New System.Drawing.Point(489, 405) Me.BTNTutup.Name = "BTNTutup" Me.BTNTutup.Size = New System.Drawing.Size(91, 34) Me.BTNTutup.TabIndex = 168 Me.BTNTutup.Text = "Selesai" Me.ToolTip1.SetToolTip(Me.BTNTutup, "Selesai") Me.BTNTutup.UseVisualStyleBackColor = True ' 'picboxDeleteAll ' Me.picboxDeleteAll.Image = Global.SIMARSIP.My.Resources.Resources.picboxDeleteAll_Leave Me.picboxDeleteAll.Location = New System.Drawing.Point(412, 405) Me.picboxDeleteAll.Name = "picboxDeleteAll" Me.picboxDeleteAll.Size = New System.Drawing.Size(61, 36) Me.picboxDeleteAll.TabIndex = 173 Me.picboxDeleteAll.TabStop = False Me.picboxDeleteAll.Tag = "Delete All" Me.ToolTip1.SetToolTip(Me.picboxDeleteAll, "Hapus Semua") ' 'picboxDelete ' Me.picboxDelete.Image = Global.SIMARSIP.My.Resources.Resources.picboxDelete_Leave Me.picboxDelete.Location = New System.Drawing.Point(353, 405) Me.picboxDelete.Name = "picboxDelete" Me.picboxDelete.Size = New System.Drawing.Size(60, 36) Me.picboxDelete.TabIndex = 172 Me.picboxDelete.TabStop = False Me.picboxDelete.Tag = "Delete Current Image" Me.ToolTip1.SetToolTip(Me.picboxDelete, "Hapus") ' 'PictureBox1 ' Me.PictureBox1.BackColor = System.Drawing.SystemColors.ControlDark Me.PictureBox1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle Me.PictureBox1.ImageLocation = "" Me.PictureBox1.Location = New System.Drawing.Point(13, 13) Me.PictureBox1.Name = "PictureBox1" Me.PictureBox1.Size = New System.Drawing.Size(316, 429) Me.PictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom Me.PictureBox1.TabIndex = 167 Me.PictureBox1.TabStop = False ' 'Scanning_keluar_Edit ' Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink Me.CancelButton = Me.BTNTutup Me.ClientSize = New System.Drawing.Size(596, 452) Me.ControlBox = False Me.Controls.Add(Me.picboxDeleteAll) Me.Controls.Add(Me.picboxDelete) Me.Controls.Add(Me.PictureBox1) Me.Controls.Add(Me.GroupBox1) Me.Controls.Add(Me.Label12) Me.Controls.Add(Me.Label23) Me.Controls.Add(Me.GroupBox3) Me.Controls.Add(Me.BTNTutup) Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon) Me.Name = "Scanning_keluar_Edit" Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen Me.Text = "Scanning" Me.GroupBox1.ResumeLayout(False) Me.GroupBox1.PerformLayout() Me.GroupBox3.ResumeLayout(False) CType(Me.picboxDeleteAll, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.picboxDelete, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.PictureBox1, System.ComponentModel.ISupportInitialize).EndInit() Me.ResumeLayout(False) Me.PerformLayout() End Sub Friend WithEvents LBLNama As System.Windows.Forms.Label Private WithEvents picboxDeleteAll As System.Windows.Forms.PictureBox Private WithEvents picboxDelete As System.Windows.Forms.PictureBox Friend WithEvents PictureBox1 As System.Windows.Forms.PictureBox Friend WithEvents ListView1 As System.Windows.Forms.ListView Friend WithEvents FileName As System.Windows.Forms.ColumnHeader Friend WithEvents Lokasi As System.Windows.Forms.ColumnHeader Friend WithEvents BTNScan As System.Windows.Forms.Button Friend WithEvents GroupBox1 As System.Windows.Forms.GroupBox Friend WithEvents BTNHapus As System.Windows.Forms.Button Friend WithEvents BTNSImpan As System.Windows.Forms.Button Friend WithEvents Label1 As System.Windows.Forms.Label Friend WithEvents _twain32 As Saraff.Twain.Twain32 Private WithEvents Label12 As System.Windows.Forms.Label Friend WithEvents Label23 As System.Windows.Forms.Label Friend WithEvents GroupBox3 As System.Windows.Forms.GroupBox Friend WithEvents BTNTutup As System.Windows.Forms.Button Friend WithEvents ToolTip1 As System.Windows.Forms.ToolTip End Class
anakpantai/busus
SIMARSIP/Arsip Keluar/Scanning Keluar Edit.Designer.vb
Visual Basic
apache-2.0
12,990
require_relative '../netapp_cmode' Puppet::Type.type(:netapp_lun).provide(:cmode, :parent => Puppet::Provider::NetappCmode) do @doc = "Manage Netapp Lun creation, modification and deletion. [Family: vserver]" confine :feature => :posix defaultfor :feature => :posix netapp_commands :lunlist => {:api => 'lun-get-iter', :iter => true, :result_element => 'attributes-list'} netapp_commands :luncreate => 'lun-create-by-size' netapp_commands :lundestroy => 'lun-destroy' netapp_commands :lunresize => 'lun-resize' netapp_commands :lunonline => 'lun-online' netapp_commands :lunoffline => 'lun-offline' mk_resource_methods def self.instances Puppet.debug("Puppet::Provider::Netapp_lun.cmode: Got to self.instances.") luns = [] #Get a list of all Lun's results = lunlist() || [] # Itterate through the results results.each do |lun| lun_path = lun.child_get_string('path') Puppet.debug("Puppet::Provider::Netapp_lun.cmode: Processing lun #{lun_path}.") # Construct initial hash for lun lun_hash = { :name => lun_path, :ensure => :present } # Grab additional elements # Lun state - Need to map true/false to online/offline lun_state = lun.child_get_string('online') if lun_state == 'true' lun_hash[:state] = 'online' else lun_hash[:state] = 'offline' end # Get size lun_hash[:size] = lun.child_get_string('size') # Create the instance and add to luns array Puppet.debug("Puppet::Provider::Netapp_lun.cmode: Creating instance for #{lun_path}\n Contents = #{lun_hash.inspect}.") luns << new(lun_hash) end # Return the final luns array Puppet.debug("Puppet::Provider::Netapp_lun.cmode: Returning luns array.") luns end def self.prefetch(resources) Puppet.debug("Puppet::Provider::Netapp_lun.cmode: Got to self.prefetch.") # Itterate instances and match provider where relevant. instances.each do |prov| Puppet.debug("Prov.path = #{resources[prov.name]}. ") if resource = resources[prov.name] resource.provider = prov end end end def flush Puppet.debug("Puppet::Provider::Netapp_lun.cmode: flushing Netapp Lun #{@resource[:path]}.") # Are we updating or destroying? Puppet.debug("Puppet::Provider::Netapp_lun.cmode: required resource state = #{@property_hash[:ensure]}") if @property_hash[:ensure] == :absent Puppet.debug("Puppet::Provider::Netapp_lun.cmode: Ensure is absent. Destroying...") # Deleting the lun lundestroy('path', @resource[:path]) Puppet.debug("Puppet::Provider::Netapp_lun.cmode: Lun #{@resource[:path]} has been destroyed successfully. ") return true end end # Set lun size def size=(value) Puppet.debug("Puppet::Provider::Netapp_lun.cmode size=: Setting lun size for #{@resource[:path]} to #{@resource[:size]}.") force if @resource[:force] == nil force = false else force = @resource[:force] end # Resize the volume result = lunresize('force', force, 'path', @resource[:path], 'size', @resource[:size]) if result.results_status() != "failed" Puppet.debug("Puppet::Provider::Netapp_lun.cmode size=: Lun has been resized.") return true end end # Set lun state def state=(value) Puppet.debug("Puppet::Provider::Netapp_lun.cmode state=: Setting lun state for #{@resource[:path]} to #{@resource[:state]}.") case @resource[:state] when :online Puppet.debug("Puppet::Provider::Netapp_lun.cmode state=: Onlineing lun.") result = lunonline('path', @resource[:path]) Puppet.debug("Puppet::Provider::Netapp_lun.cmode state=: Lun has been onlined.") return true when :offline Puppet.debug("Puppet::Provider::Netapp_lun.cmode state=: Offlining lun.") result = lunoffline('path', @resource[:path]) Puppet.debug("Puppet::Provider::Netapp_lun.cmode state=: Lun has been offlined.") return true end end def create Puppet.debug("Puppet::Provider::Netapp_lun.cmode: creating Netapp Lun #{@resource[:path]}.") # Lun create args luncreate_args = [] luncreate_args << 'path' << @resource[:path] luncreate_args << 'size' << @resource[:size] luncreate_args << 'class' << @resource[:lunclass] luncreate_args << 'ostype' << @resource[:ostype] luncreate_args << 'space-reservation-enabled' << @resource[:spaceresenabled] # Optional fields luncreate_args << 'prefix-size' << @resource[:prefixsize] unless @resource[:prefixsize].nil? luncreate_args << 'qos-policy-group' << @resource[:qospolicygroup] unless @resource[:qospolicygroup].nil? # Create the lun result = luncreate(*luncreate_args) # Lun created successfully Puppet.debug("Puppet::Provider::Netapp_lun.cmode: Lun #{@resource[:path]} created successfully.") return true end def destroy Puppet.debug("Puppet::Provider::Netapp_lun.cmode: destroying Netapp Lun #{@resource[:path]}.") @property_hash[:ensure] = :absent end def exists? Puppet.debug("Puppet::Provider::Netapp_lun.cmode: checking existance of Netapp Lun #{@resource[:path]}.") @property_hash[:ensure] == :present end end
puppetlabs/puppetlabs-netapp
lib/puppet/provider/netapp_lun/cmode.rb
Ruby
apache-2.0
5,287
package org.commcare; import org.commcare.models.database.UnencryptedHybridFileBackedSqlStorage; import org.commcare.models.database.UnencryptedHybridFileBackedSqlStorageMock; import org.javarosa.core.services.storage.Persistable; /** * Delegator around CommCareApp allowing the test suite to override logic. * * @author Phillip Mates ([email protected]). */ public class CommCareTestApp extends CommCareApp { private final CommCareApp app; public CommCareTestApp(CommCareApp app) { super(app.getAppRecord()); fileRoot = app.fileRoot; setAppResourceState(app.getAppResourceState()); this.app = app; } @Override public <T extends Persistable> UnencryptedHybridFileBackedSqlStorage<T> getFileBackedStorage(String name, Class<T> c) { return new UnencryptedHybridFileBackedSqlStorageMock<>(name, c, app.buildAndroidDbHelper(), app); } }
dimagi/commcare-android
app/unit-tests/src/org/commcare/CommCareTestApp.java
Java
apache-2.0
906
// Code generated by go-swagger; DO NOT EDIT. package models // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( strfmt "github.com/go-openapi/strfmt" "github.com/go-openapi/errors" "github.com/go-openapi/swag" "github.com/go-openapi/validate" ) // SendPhotoLinkBody send photo link body // swagger:model SendPhotoLinkBody type SendPhotoLinkBody struct { // caption Caption string `json:"caption,omitempty"` // chat id // Required: true ChatID interface{} `json:"chat_id"` // disable notification DisableNotification bool `json:"disable_notification,omitempty"` // photo // Required: true Photo *string `json:"photo"` // reply markup ReplyMarkup interface{} `json:"reply_markup,omitempty"` // reply to message id ReplyToMessageID int64 `json:"reply_to_message_id,omitempty"` } // Validate validates this send photo link body func (m *SendPhotoLinkBody) Validate(formats strfmt.Registry) error { var res []error if err := m.validateChatID(formats); err != nil { // prop res = append(res, err) } if err := m.validatePhoto(formats); err != nil { // prop res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (m *SendPhotoLinkBody) validateChatID(formats strfmt.Registry) error { return nil } func (m *SendPhotoLinkBody) validatePhoto(formats strfmt.Registry) error { if err := validate.Required("photo", "body", m.Photo); err != nil { return err } return nil } // MarshalBinary interface implementation func (m *SendPhotoLinkBody) MarshalBinary() ([]byte, error) { if m == nil { return nil, nil } return swag.WriteJSON(m) } // UnmarshalBinary interface implementation func (m *SendPhotoLinkBody) UnmarshalBinary(b []byte) error { var res SendPhotoLinkBody if err := swag.ReadJSON(b, &res); err != nil { return err } *m = res return nil }
olebedev/go-tgbot
models/send_photo_link_body.go
GO
apache-2.0
1,957
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="de"> <head> <!-- Generated by javadoc (version 1.7.0_17) on Tue May 14 03:45:04 CEST 2013 --> <title>Uses of Class com.badlogic.gdx.net.HttpStatus (libgdx API)</title> <meta name="date" content="2013-05-14"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class com.badlogic.gdx.net.HttpStatus (libgdx API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../com/badlogic/gdx/net/HttpStatus.html" title="class in com.badlogic.gdx.net">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em> libgdx API <style> body, td, th { font-family:Helvetica, Tahoma, Arial, sans-serif; font-size:10pt } pre, code, tt { font-size:9pt; font-family:Lucida Console, Courier New, sans-serif } h1, h2, h3, .FrameTitleFont, .FrameHeadingFont, .TableHeadingColor font { font-size:105%; font-weight:bold } .TableHeadingColor { background:#EEEEFF; } a { text-decoration:none } a:hover { text-decoration:underline } a:link, a:visited { color:blue } table { border:0px } .TableRowColor td:first-child { border-left:1px solid black } .TableRowColor td { border:0px; border-bottom:1px solid black; border-right:1px solid black } hr { border:0px; border-bottom:1px solid #333366; } </style> </em></div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/badlogic/gdx/net/class-use/HttpStatus.html" target="_top">Frames</a></li> <li><a href="HttpStatus.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class com.badlogic.gdx.net.HttpStatus" class="title">Uses of Class<br>com.badlogic.gdx.net.HttpStatus</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../com/badlogic/gdx/net/HttpStatus.html" title="class in com.badlogic.gdx.net">HttpStatus</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#com.badlogic.gdx">com.badlogic.gdx</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="com.badlogic.gdx"> <!-- --> </a> <h3>Uses of <a href="../../../../../com/badlogic/gdx/net/HttpStatus.html" title="class in com.badlogic.gdx.net">HttpStatus</a> in <a href="../../../../../com/badlogic/gdx/package-summary.html">com.badlogic.gdx</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../com/badlogic/gdx/package-summary.html">com.badlogic.gdx</a> that return <a href="../../../../../com/badlogic/gdx/net/HttpStatus.html" title="class in com.badlogic.gdx.net">HttpStatus</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../com/badlogic/gdx/net/HttpStatus.html" title="class in com.badlogic.gdx.net">HttpStatus</a></code></td> <td class="colLast"><span class="strong">Net.HttpResponse.</span><code><strong><a href="../../../../../com/badlogic/gdx/Net.HttpResponse.html#getStatus()">getStatus</a></strong>()</code> <div class="block">Returns the <a href="../../../../../com/badlogic/gdx/net/HttpStatus.html" title="class in com.badlogic.gdx.net"><code>HttpStatus</code></a> containing the statusCode of the HTTP response.</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../com/badlogic/gdx/net/HttpStatus.html" title="class in com.badlogic.gdx.net">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em>libgdx API</em></div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/badlogic/gdx/net/class-use/HttpStatus.html" target="_top">Frames</a></li> <li><a href="HttpStatus.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small> <div style="font-size:9pt"><i> Copyright &copy; 2010-2013 Mario Zechner ([email protected]), Nathan Sweet ([email protected]) </i></div> </small></p> </body> </html>
leszekuchacz/Leszek-Uchacz
docs/api/com/badlogic/gdx/net/class-use/HttpStatus.html
HTML
apache-2.0
7,238
/** * Copyright (C) 2014-2015 LinkedIn Corp. ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.linkedin.pinot.core.startree; import java.io.BufferedOutputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.tuple.Pair; import org.joda.time.DateTime; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Objects; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import com.linkedin.pinot.common.data.DimensionFieldSpec; import com.linkedin.pinot.common.data.MetricFieldSpec; import com.linkedin.pinot.common.data.FieldSpec.DataType; import com.linkedin.pinot.common.data.Schema; import com.linkedin.pinot.common.utils.Pairs.IntPair; import com.linkedin.pinot.core.data.GenericRow; import com.linkedin.pinot.core.segment.creator.impl.V1Constants; /** * Uses file to build the star tree. Each row is divided into dimension and metrics. Time is added to dimension list. * We use the split order to build the tree. In most cases, split order will be ranked depending on the cardinality (descending order). * Time column will be excluded or last entry in split order irrespective of its cardinality * This is a recursive algorithm where we branch on one dimension at every level. * * <b>Psuedo algo</b> * <code> * * build(){ * let table(1,N) consists of N input rows * table.sort(1,N) //sort the table on all dimensions, according to split order * constructTree(table, 0, N, 0); * } * constructTree(table,start,end, level){ * splitDimensionName = dimensionsSplitOrder[level] * groupByResult<dimName, length> = table.groupBy(dimensionsSplitOrder[level]); //returns the number of rows for each value in splitDimension * int rangeStart = 0; * for each ( entry<dimName,length> groupByResult){ * if(entry.length > minThreshold){ * constructTree(table, rangeStart, rangeStart + entry.length, level +1); * } * rangeStart = rangeStart + entry.length; * updateStarTree() //add new child * } * * //create a star tree node * * aggregatedRows = table.uniqueAfterRemovingAttributeAndAggregateMetrics(start,end, splitDimensionName); * for(each row in aggregatedRows_ * table.add(row); * if(aggregateRows.size > minThreshold) { * table.sort(end, end + aggregatedRows.size); * constructStarTree(table, end, end + aggregatedRows.size, level +1); * } * } * </code> */ public class OffHeapStarTreeBuilder implements StarTreeBuilder { private static final Logger LOG = LoggerFactory.getLogger(OffHeapStarTreeBuilder.class); File dataFile; private DataOutputStream dataBuffer; int rawRecordCount = 0; int aggRecordCount = 0; private List<String> dimensionsSplitOrder; private Set<String> skipStarNodeCreationForDimensions; private Set<String> skipMaterializationForDimensions; private int maxLeafRecords; private StarTree starTree; private StarTreeIndexNode starTreeRootIndexNode; private int numDimensions; private int numMetrics; private List<String> dimensionNames; private List<String> metricNames; private String timeColumnName; private List<DataType> dimensionTypes; private List<DataType> metricTypes; private Map<String, Object> dimensionNameToStarValueMap; private HashBiMap<String, Integer> dimensionNameToIndexMap; private Map<String, Integer> metricNameToIndexMap; private int dimensionSizeBytes; private int metricSizeBytes; private File outDir; private Map<String, HashBiMap<Object, Integer>> dictionaryMap; boolean debugMode = false; private int[] sortOrder; private int skipMaterializationCardinalityThreshold; public void init(StarTreeBuilderConfig builderConfig) throws Exception { Schema schema = builderConfig.schema; timeColumnName = schema.getTimeColumnName(); this.dimensionsSplitOrder = builderConfig.dimensionsSplitOrder; skipStarNodeCreationForDimensions = builderConfig.getSkipStarNodeCreationForDimensions(); skipMaterializationForDimensions = builderConfig.getSkipMaterializationForDimensions(); skipMaterializationCardinalityThreshold = builderConfig.getSkipMaterializationCardinalityThreshold(); this.maxLeafRecords = builderConfig.maxLeafRecords; this.outDir = builderConfig.getOutDir(); if (outDir == null) { outDir = new File(System.getProperty("java.io.tmpdir"), V1Constants.STAR_TREE_INDEX_DIR + "_" + DateTime.now()); } LOG.debug("Index output directory:{}", outDir); dimensionTypes = new ArrayList<>(); dimensionNames = new ArrayList<>(); dimensionNameToIndexMap = HashBiMap.create(); dimensionNameToStarValueMap = new HashMap<>(); dictionaryMap = new HashMap<>(); //READ DIMENSIONS COLUMNS List<DimensionFieldSpec> dimensionFieldSpecs = schema.getDimensionFieldSpecs(); for (int index = 0; index < dimensionFieldSpecs.size(); index++) { DimensionFieldSpec spec = dimensionFieldSpecs.get(index); String dimensionName = spec.getName(); dimensionNames.add(dimensionName); dimensionNameToIndexMap.put(dimensionName, index); Object starValue; starValue = getAllStarValue(spec); dimensionNameToStarValueMap.put(dimensionName, starValue); dimensionTypes.add(spec.getDataType()); HashBiMap<Object, Integer> dictionary = HashBiMap.create(); dictionaryMap.put(dimensionName, dictionary); } //treat time column as just another dimension, only difference is that we will never split on this dimension unless explicitly specified in split order if (timeColumnName != null) { dimensionNames.add(timeColumnName); dimensionTypes.add(schema.getTimeFieldSpec().getDataType()); int index = dimensionNameToIndexMap.size(); dimensionNameToIndexMap.put(timeColumnName, index); HashBiMap<Object, Integer> dictionary = HashBiMap.create(); dictionaryMap.put(schema.getTimeColumnName(), dictionary); } dimensionSizeBytes = dimensionNames.size() * Integer.SIZE / 8; this.numDimensions = dimensionNames.size(); //READ METRIC COLUMNS this.metricTypes = new ArrayList<>(); this.metricNames = new ArrayList<>(); this.metricNameToIndexMap = new HashMap<>(); this.metricSizeBytes = 0; List<MetricFieldSpec> metricFieldSpecs = schema.getMetricFieldSpecs(); for (int index = 0; index < metricFieldSpecs.size(); index++) { MetricFieldSpec spec = metricFieldSpecs.get(index); String metricName = spec.getName(); metricNames.add(metricName); metricNameToIndexMap.put(metricName, index); DataType dataType = spec.getDataType(); metricTypes.add(dataType); metricSizeBytes += dataType.size(); } this.numMetrics = metricNames.size(); builderConfig.getOutDir().mkdirs(); dataFile = new File(outDir, "star-tree.buf"); dataBuffer = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(dataFile))); //INITIALIZE THE ROOT NODE this.starTreeRootIndexNode = new StarTreeIndexNode(); this.starTreeRootIndexNode.setDimensionName(StarTreeIndexNode.all()); this.starTreeRootIndexNode.setDimensionValue(StarTreeIndexNode.all()); this.starTreeRootIndexNode.setLevel(0); LOG.debug("dimensionNames:{}", dimensionNames); LOG.debug("metricNames:{}", metricNames); } /** * Validate the split order by removing any dimensions that may be part of the skip materialization list. * @param dimensionsSplitOrder * @param skipMaterializationForDimensions * @return */ private List<String> sanitizeSplitOrder(List<String> dimensionsSplitOrder, Set<String> skipMaterializationForDimensions) { List<String> validatedSplitOrder = new ArrayList<String>(); for (String dimension : dimensionsSplitOrder) { if (skipMaterializationForDimensions == null || !skipMaterializationForDimensions.contains(dimension)) { LOG.info("Adding dimension {} to split order", dimension); validatedSplitOrder.add(dimension); } else { LOG.info( "Dimension {} cannot be part of 'dimensionSplitOrder' and 'skipMaterializationForDimensions', removing it from split order", dimension); } } return validatedSplitOrder; } private Object getAllStarValue(DimensionFieldSpec spec) throws Exception { switch (spec.getDataType()) { case STRING: return "ALL"; case BOOLEAN: case BYTE: case CHAR: case DOUBLE: case FLOAT: case INT: case LONG: return spec.getDefaultNullValue(); case OBJECT: case SHORT: case DOUBLE_ARRAY: case CHAR_ARRAY: case FLOAT_ARRAY: case INT_ARRAY: case LONG_ARRAY: case SHORT_ARRAY: case STRING_ARRAY: case BYTE_ARRAY: default: throw new Exception("Unsupported dimension data type" + spec); } } public GenericRow toGenericRow(DimensionBuffer dimensionKey, MetricBuffer metricsHolder) { GenericRow row = new GenericRow(); Map<String, Object> map = new HashMap<>(); for (int i = 0; i < dimensionNames.size(); i++) { String dimName = dimensionNames.get(i); BiMap<Integer, Object> inverseDictionary = dictionaryMap.get(dimName).inverse(); Object dimValue = inverseDictionary.get(dimensionKey.getDimension(i)); if (dimValue == null) { dimValue = dimensionNameToStarValueMap.get(dimName); } map.put(dimName, dimValue); } for (int i = 0; i < numMetrics; i++) { String metName = metricNames.get(i); map.put(metName, metricsHolder.get(i)); } row.init(map); return row; } public void append(GenericRow row) throws Exception { DimensionBuffer dimension = new DimensionBuffer(numDimensions); for (int i = 0; i < dimensionNames.size(); i++) { String dimName = dimensionNames.get(i); Map<Object, Integer> dictionary = dictionaryMap.get(dimName); Object dimValue = row.getValue(dimName); if (dimValue == null) { //TODO: Have another default value to represent STAR. Using default value to represent STAR as of now. //It does not matter during query execution, since we know that values is STAR from the star tree dimValue = dimensionNameToStarValueMap.get(dimName); } if (!dictionary.containsKey(dimValue)) { dictionary.put(dimValue, dictionary.size()); } dimension.setDimension(i, dictionary.get(dimValue)); } Number[] numbers = new Number[numMetrics]; for (int i = 0; i < numMetrics; i++) { String metName = metricNames.get(i); numbers[i] = (Number) row.getValue(metName); } MetricBuffer metrics = new MetricBuffer(numbers); append(dimension, metrics); } public void append(DimensionBuffer dimension, MetricBuffer metrics) throws Exception { appendToRawBuffer(dimension, metrics); } private void appendToRawBuffer(DimensionBuffer dimension, MetricBuffer metrics) throws IOException { appendToBuffer(dataBuffer, dimension, metrics); rawRecordCount++; } private void appendToAggBuffer(DimensionBuffer dimension, MetricBuffer metrics) throws IOException { appendToBuffer(dataBuffer, dimension, metrics); aggRecordCount++; } private void appendToBuffer(DataOutputStream dos, DimensionBuffer dimensions, MetricBuffer metricHolder) throws IOException { for (int i = 0; i < numDimensions; i++) { dos.writeInt(dimensions.getDimension(i)); } dos.write(metricHolder.toBytes(metricSizeBytes, metricTypes)); } public void build() throws Exception { if (skipMaterializationForDimensions == null || skipMaterializationForDimensions.isEmpty()) { skipMaterializationForDimensions = computeDefaultDimensionsToSkipMaterialization(); } if (dimensionsSplitOrder == null || dimensionsSplitOrder.isEmpty()) { dimensionsSplitOrder = computeDefaultSplitOrder(); } // Remove any dimensions from split order that would be not be materialized. dimensionsSplitOrder = sanitizeSplitOrder(dimensionsSplitOrder, skipMaterializationForDimensions); LOG.debug("Split order:{}", dimensionsSplitOrder); long start = System.currentTimeMillis(); dataBuffer.flush(); sort(dataFile, 0, rawRecordCount); constructStarTree(starTreeRootIndexNode, 0, rawRecordCount, 0, dataFile); long end = System.currentTimeMillis(); LOG.debug("Took {} ms to build star tree index. Original records:{} Materialized record:{}", (end - start), rawRecordCount, aggRecordCount); starTree = new StarTree(starTreeRootIndexNode, dimensionNameToIndexMap); File treeBinary = new File(outDir, "star-tree.bin"); LOG.debug("Saving tree binary at: {} ", treeBinary); starTree.writeTree(new BufferedOutputStream(new FileOutputStream(treeBinary))); printTree(starTreeRootIndexNode, 0); LOG.debug("Finished build tree. out dir: {} ", outDir); dataBuffer.close(); } private void printTree(StarTreeIndexNode node, int level) { for (int i = 0; i < level; i++) { LOG.debug(" "); } BiMap<Integer, String> inverse = dimensionNameToIndexMap.inverse(); String dimName = "ALL"; Object dimValue = "ALL"; if (node.getDimensionName() != StarTreeIndexNode.all()) { dimName = inverse.get(node.getDimensionName()); } if (node.getDimensionValue() != StarTreeIndexNode.all()) { dimValue = dictionaryMap.get(dimName).inverse().get(node.getDimensionValue()); } String formattedOutput = Objects.toStringHelper(node).add("nodeId", node.getNodeId()).add("level", level).add("dimensionName", dimName) .add("dimensionValue", dimValue).add("childDimensionName", inverse.get(node.getChildDimensionName())) .add("childCount", node.getChildren() == null ? 0 : node.getChildren().size()) .add("startDocumentId", node.getStartDocumentId()).add("endDocumentId", node.getEndDocumentId()) .add("documentCount", (node.getEndDocumentId() - node.getStartDocumentId())).toString(); LOG.debug(formattedOutput); if (!node.isLeaf()) { for (StarTreeIndexNode child : node.getChildren().values()) { printTree(child, level + 1); } } } private List<String> computeDefaultSplitOrder() { ArrayList<String> defaultSplitOrder = new ArrayList<>(); //include only the dimensions not time column. Also, assumes that skipMaterializationForDimensions is built. for (String dimensionName : dimensionNames) { if (skipMaterializationForDimensions != null && !skipMaterializationForDimensions.contains(dimensionName)) { defaultSplitOrder.add(dimensionName); } } if (timeColumnName != null) { defaultSplitOrder.remove(timeColumnName); } Collections.sort(defaultSplitOrder, new Comparator<String>() { @Override public int compare(String o1, String o2) { return dictionaryMap.get(o2).size() - dictionaryMap.get(o1).size(); //descending } }); return defaultSplitOrder; } private Set<String> computeDefaultDimensionsToSkipMaterialization() { Set<String> skipDimensions = new HashSet<String>(); for (String dimensionName : dimensionNames) { if (dictionaryMap.get(dimensionName).size() > skipMaterializationCardinalityThreshold) { skipDimensions.add(dimensionName); } } return skipDimensions; } /* * Sorts the file on all dimensions */ private void sort(File file, int startDocId, int endDocId) throws IOException { if (debugMode) { LOG.info("BEFORE SORTING"); printFile(file, startDocId, endDocId); } StarTreeDataTable dataSorter = new StarTreeDataTable(file, dimensionSizeBytes, metricSizeBytes, getSortOrder()); dataSorter.sort(startDocId, endDocId, 0, dimensionSizeBytes); if (debugMode) { LOG.info("AFTER SORTING"); printFile(file, startDocId, endDocId); } } private int[] getSortOrder() { if (sortOrder == null) { sortOrder = new int[dimensionNames.size()]; for (int i = 0; i < dimensionsSplitOrder.size(); i++) { sortOrder[i] = dimensionNameToIndexMap.get(dimensionsSplitOrder.get(i)); } //add remaining dimensions that were not part of dimensionsSplitOrder int counter = 0; for (String dimName : dimensionNames) { if (!dimensionsSplitOrder.contains(dimName)) { sortOrder[dimensionsSplitOrder.size() + counter] = dimensionNameToIndexMap.get(dimName); counter = counter + 1; } } } return sortOrder; } private void printFile(File file, int startDocId, int endDocId) throws IOException { LOG.info("Contents of file:{} from:{} to:{}", file.getName(), startDocId, endDocId); StarTreeDataTable dataSorter = new StarTreeDataTable(file, dimensionSizeBytes, metricSizeBytes, getSortOrder()); Iterator<Pair<byte[], byte[]>> iterator = dataSorter.iterator(startDocId, endDocId); int numRecordsToPrint = 100; int counter = 0; while (iterator.hasNext()) { Pair<byte[], byte[]> next = iterator.next(); LOG.info("{}, {}", DimensionBuffer.fromBytes(next.getLeft()), MetricBuffer.fromBytes(next.getRight(), metricTypes)); if (counter++ == numRecordsToPrint) { break; } } } private int constructStarTree(StarTreeIndexNode node, int startDocId, int endDocId, int level, File file) throws Exception { //node.setStartDocumentId(startDocId); int docsAdded = 0; if (level == dimensionsSplitOrder.size() - 1) { return 0; } String splitDimensionName = dimensionsSplitOrder.get(level); Integer splitDimensionId = dimensionNameToIndexMap.get(splitDimensionName); LOG.debug("Building tree at level:{} using file:{} from startDoc:{} endDocId:{} splitting on dimension:{}", level, file.getName(), startDocId, endDocId, splitDimensionName); Map<Integer, IntPair> sortGroupBy = groupBy(startDocId, endDocId, splitDimensionId, file); LOG.debug("Group stats:{}", sortGroupBy); node.setChildDimensionName(splitDimensionId); node.setChildren(new HashMap<Integer, StarTreeIndexNode>()); for (int childDimensionValue : sortGroupBy.keySet()) { StarTreeIndexNode child = new StarTreeIndexNode(); child.setDimensionName(splitDimensionId); child.setDimensionValue(childDimensionValue); child.setParent(node); child.setLevel(node.getLevel() + 1); // n.b. We will number the nodes later using BFS after fully split // Add child to parent node.getChildren().put(childDimensionValue, child); int childDocs = 0; IntPair range = sortGroupBy.get(childDimensionValue); if (range.getRight() - range.getLeft() > maxLeafRecords) { childDocs = constructStarTree(child, range.getLeft(), range.getRight(), level + 1, file); docsAdded += childDocs; } // Either range <= maxLeafRecords, or we did not split further (last level). if (childDocs == 0) { child.setStartDocumentId(range.getLeft()); child.setEndDocumentId(range.getRight()); } } // Return if star node does not need to be created. if (skipStarNodeCreationForDimensions != null && skipStarNodeCreationForDimensions.contains(splitDimensionName)) { return docsAdded; } //create star node StarTreeIndexNode starChild = new StarTreeIndexNode(); starChild.setDimensionName(splitDimensionId); starChild.setDimensionValue(StarTreeIndexNode.all()); starChild.setParent(node); starChild.setLevel(node.getLevel() + 1); // n.b. We will number the nodes later using BFS after fully split // Add child to parent node.getChildren().put(StarTreeIndexNode.all(), starChild); Iterator<Pair<DimensionBuffer, MetricBuffer>> iterator = uniqueCombinations(startDocId, endDocId, file, splitDimensionId); int rowsAdded = 0; int startOffset = rawRecordCount + aggRecordCount; while (iterator.hasNext()) { Pair<DimensionBuffer, MetricBuffer> next = iterator.next(); DimensionBuffer dimension = next.getLeft(); MetricBuffer metricsHolder = next.getRight(); LOG.debug("Adding row:{}", dimension); appendToAggBuffer(dimension, metricsHolder); rowsAdded++; } docsAdded += rowsAdded; LOG.debug("Added {} additional records at level {}", rowsAdded, level); //flush dataBuffer.flush(); int childDocs = 0; if (rowsAdded >= maxLeafRecords) { sort(dataFile, startOffset, startOffset + rowsAdded); childDocs = constructStarTree(starChild, startOffset, startOffset + rowsAdded, level + 1, dataFile); docsAdded += childDocs; } // Either rowsAdded < maxLeafRecords, or we did not split further (last level). if (childDocs == 0) { starChild.setStartDocumentId(startOffset); starChild.setEndDocumentId(startOffset + rowsAdded); } //node.setEndDocumentId(endDocId + docsAdded); return docsAdded; } /** * Assumes the file is already sorted, returns the unique combinations after removing a specified dimension. * Aggregates the metrics for each unique combination, currently only sum is supported by default * @param startDocId * @param endDocId * @param file * @param splitDimensionId * @return * @throws Exception */ private Iterator<Pair<DimensionBuffer, MetricBuffer>> uniqueCombinations(int startDocId, int endDocId, File file, int splitDimensionId) throws Exception { StarTreeDataTable dataSorter = new StarTreeDataTable(file, dimensionSizeBytes, metricSizeBytes, getSortOrder()); Iterator<Pair<byte[], byte[]>> iterator1 = dataSorter.iterator(startDocId, endDocId); File tempFile = new File(outDir, file.getName() + "_" + startDocId + "_" + endDocId + ".unique.tmp"); DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(tempFile))); while (iterator1.hasNext()) { Pair<byte[], byte[]> next = iterator1.next(); byte[] dimensionBuffer = next.getLeft(); byte[] metricBuffer = next.getRight(); DimensionBuffer dimensions = DimensionBuffer.fromBytes(dimensionBuffer); for (int i = 0; i < numDimensions; i++) { String dimensionName = dimensionNameToIndexMap.inverse().get(i); if (i == splitDimensionId || (skipMaterializationForDimensions != null && skipMaterializationForDimensions.contains(dimensionName))) { dos.writeInt(StarTreeIndexNode.all()); } else { dos.writeInt(dimensions.getDimension(i)); } } dos.write(metricBuffer); } dos.close(); dataSorter = new StarTreeDataTable(tempFile, dimensionSizeBytes, metricSizeBytes, getSortOrder()); dataSorter.sort(0, endDocId - startDocId); if (debugMode) { printFile(tempFile, 0, endDocId - startDocId); } final Iterator<Pair<byte[], byte[]>> iterator = dataSorter.iterator(0, endDocId - startDocId); return new Iterator<Pair<DimensionBuffer, MetricBuffer>>() { Pair<DimensionBuffer, MetricBuffer> prev = null; boolean done = false; @Override public void remove() { throw new UnsupportedOperationException(); } @Override public boolean hasNext() { return !done; } @Override public Pair<DimensionBuffer, MetricBuffer> next() { while (iterator.hasNext()) { Pair<byte[], byte[]> next = iterator.next(); byte[] dimBuffer = next.getLeft(); byte[] metricBuffer = next.getRight(); if (prev == null) { prev = Pair.of(DimensionBuffer.fromBytes(dimBuffer), MetricBuffer.fromBytes(metricBuffer, metricTypes)); } else { Pair<DimensionBuffer, MetricBuffer> current = Pair.of(DimensionBuffer.fromBytes(dimBuffer), MetricBuffer.fromBytes(metricBuffer, metricTypes)); if (!current.getLeft().equals(prev.getLeft())) { Pair<DimensionBuffer, MetricBuffer> ret = prev; prev = current; LOG.debug("Returning unique {}", prev.getLeft()); return ret; } else { prev.getRight().aggregate(current.getRight(), metricTypes); } } } done = true; LOG.debug("Returning unique {}", prev.getLeft()); return prev; } }; } /** * sorts the file from start to end on a dimension index * @param startDocId * @param endDocId * @param dimension * @param file * @return */ private Map<Integer, IntPair> groupBy(int startDocId, int endDocId, Integer dimension, File file) { StarTreeDataTable dataSorter = new StarTreeDataTable(file, dimensionSizeBytes, metricSizeBytes, getSortOrder()); return dataSorter.groupByIntColumnCount(startDocId, endDocId, dimension); } /** * Iterator to iterate over the records from startDocId to endDocId */ @Override public Iterator<GenericRow> iterator(final int startDocId, final int endDocId) throws Exception { StarTreeDataTable dataSorter = new StarTreeDataTable(dataFile, dimensionSizeBytes, metricSizeBytes, getSortOrder()); final Iterator<Pair<byte[], byte[]>> iterator = dataSorter.iterator(startDocId, endDocId); return new Iterator<GenericRow>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public void remove() { throw new UnsupportedOperationException(); } @Override public GenericRow next() { Pair<byte[], byte[]> pair = iterator.next(); DimensionBuffer dimensionKey = DimensionBuffer.fromBytes(pair.getLeft()); MetricBuffer metricsHolder = MetricBuffer.fromBytes(pair.getRight(), metricTypes); return toGenericRow(dimensionKey, metricsHolder); } }; } public JSONObject getStarTreeAsJSON() throws Exception { JSONObject json = new JSONObject(); toJson(json, starTreeRootIndexNode, dictionaryMap); return json; } private void toJson(JSONObject json, StarTreeIndexNode node, Map<String, HashBiMap<Object, Integer>> dictionaryMap) throws Exception { String dimName = "ALL"; Object dimValue = "ALL"; if (node.getDimensionName() != StarTreeIndexNode.all()) { dimName = dimensionNames.get(node.getDimensionName()); } if (node.getDimensionValue() != StarTreeIndexNode.all()) { dimValue = dictionaryMap.get(dimName).inverse().get(node.getDimensionValue()); } json.put("title", dimName + ":" + dimValue); if (node.getChildren() != null) { JSONObject[] childJsons = new JSONObject[node.getChildren().size()]; int index = 0; for (Integer child : node.getChildren().keySet()) { StarTreeIndexNode childNode = node.getChildren().get(child); JSONObject childJson = new JSONObject(); toJson(childJson, childNode, dictionaryMap); childJsons[index++] = childJson; } json.put("nodes", childJsons); } } @Override public void cleanup() { if (outDir != null) { FileUtils.deleteQuietly(outDir); } } @Override public StarTree getTree() { return starTree; } @Override public int getTotalRawDocumentCount() { return rawRecordCount; } @Override public int getTotalAggregateDocumentCount() { return aggRecordCount; } @Override public int getMaxLeafRecords() { return maxLeafRecords; } @Override public List<String> getDimensionsSplitOrder() { return dimensionsSplitOrder; } public Map<String, HashBiMap<Object, Integer>> getDictionaryMap() { return dictionaryMap; } public HashBiMap<String, Integer> getDimensionNameToIndexMap() { return dimensionNameToIndexMap; } @Override public Set<String> getSkipMaterializationForDimensions() { return skipMaterializationForDimensions; } }
tkao1000/pinot
pinot-core/src/main/java/com/linkedin/pinot/core/startree/OffHeapStarTreeBuilder.java
Java
apache-2.0
28,902
<!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 (1.8.0_112) on Fri Jun 16 09:55:12 MST 2017 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>org.wildfly.swarm.batch.jberet (Public javadocs 2017.6.1 API)</title> <meta name="date" content="2017-06-16"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> </head> <body> <h1 class="bar"><a href="../../../../../org/wildfly/swarm/batch/jberet/package-summary.html" target="classFrame">org.wildfly.swarm.batch.jberet</a></h1> <div class="indexContainer"> <h2 title="Classes">Classes</h2> <ul title="Classes"> <li><a href="BatchFraction.html" title="class in org.wildfly.swarm.batch.jberet" target="classFrame">BatchFraction</a></li> </ul> </div> </body> </html>
wildfly-swarm/wildfly-swarm-javadocs
2017.6.1/apidocs/org/wildfly/swarm/batch/jberet/package-frame.html
HTML
apache-2.0
970
<table class="table table-bordered" st-pipe="load" st-table="displayed"> <thead> <tr ng-if="globalFilter"> <th colspan="{{ columns.length + 1 }}"> <input st-search="" class="form-control" placeholder="global search ..." type="text"/> </th> </tr> <tr ng-if="columnFilter"> <th ng-repeat="col in columns"> <input st-search="{{col}}" class="form-control" placeholder="search by {{ col | translate }} ..." type="text"/> </th> <th></th> </tr> <tr> <th ng-repeat="col in columns" st-sort="{{col}}"> {{ col | translate }}</th> <th>Edit</th> </tr> </thead> <tbody ng-show="isLoading"> <tr> <td colspan="{{ columns.length + 1 }}" class="text-center">Loading ...</td> </tr> </tbody> <tbody ng-show="!isLoading"> <tr ng-repeat="row in displayed"> <td ng-repeat="col in columns">{{ row[col] }}</td> <td> <a ui-sref="{{edit}}"> {{ 'action.edit' | translate }} </a> </td> </tr> </tbody> <tfoot> <tr> <td colspan="{{ columns.length + 1 }}" class="text-center"> <div st-pagination="" st-items-by-page="itemsPerPage" st-displayed-pages="7"></div> </td> </tr> </tfoot> </table>
scvetkovski/web-programming-starter
src/main/webapp/app/directives/iv-simple-table.html
HTML
apache-2.0
1,267
/* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.plugins.signing; import com.google.common.base.Function; import groovy.lang.Closure; import org.gradle.api.artifacts.PublishArtifact; import org.gradle.api.file.FileCollection; import org.gradle.api.internal.file.collections.ImmutableFileCollection; import org.gradle.plugins.signing.signatory.Signatory; import org.gradle.plugins.signing.type.SignatureType; import org.gradle.util.ConfigureUtil; import java.io.File; import java.util.ArrayList; import java.util.List; /** * A sign operation creates digital signatures for one or more files or {@link PublishArtifact publish artifacts}. * * <p>The external representation of the signature is specified by the {@link #getSignatureType() signature type property}, while the {@link #signatory} property specifies who is to sign. <p> A sign * operation manages one or more {@link Signature} objects. The {@code sign} methods are used to register things to generate signatures for. The {@link #execute()} method generates the signatures for * all of the registered items at that time. */ abstract public class SignOperation implements SignatureSpec { /** * The file representation of the signature(s). */ private SignatureType signatureType; /** * The signatory to the generated digital signatures. */ private Signatory signatory; /** * Whether or not it is required that this signature be generated. */ private boolean required; private final List<Signature> signatures = new ArrayList<Signature>(); public String getDisplayName() { return "SignOperation"; } @Override public String toString() { return getDisplayName(); } @Override public void setSignatureType(SignatureType signatureType) { this.signatureType = signatureType; } @Override public SignatureType getSignatureType() { return signatureType; } @Override public void setSignatory(Signatory signatory) { this.signatory = signatory; } @Override public Signatory getSignatory() { return signatory; } @Override public void setRequired(boolean required) { this.required = required; } @Override public boolean isRequired() { return required; } /** * Registers signatures for the given artifacts. * * @return this * @see Signature#Signature(File, SignatureSpec, Object...) */ public SignOperation sign(PublishArtifact... artifacts) { for (PublishArtifact artifact : artifacts) { signatures.add(new Signature(artifact, this)); } return this; } /** * Registers signatures for the given files. * * @return this * @see Signature#Signature(File, SignatureSpec, Object...) */ public SignOperation sign(File... files) { for (File file : files) { signatures.add(new Signature(file, this)); } return this; } /** * Registers signatures (with the given classifier) for the given files * * @return this * @see Signature#Signature(PublishArtifact, SignatureSpec, Object...) */ public SignOperation sign(String classifier, File... files) { for (File file : files) { signatures.add(new Signature(file, classifier, this)); } return this; } /** * Change the signature type for signature generation. */ public SignOperation signatureType(SignatureType type) { this.signatureType = type; return this; } /** * Change the signatory for signature generation. */ public SignOperation signatory(Signatory signatory) { this.signatory = signatory; return this; } /** * Executes the given closure against this object. */ public SignOperation configure(Closure closure) { ConfigureUtil.configureSelf(closure, this); return this; } /** * Generates actual signature files for all of the registered signatures. * * <p>The signatures are generated with the configuration they have at this time, which includes the signature type and signatory of this operation at this time. <p> This method can be called * multiple times, with the signatures being generated with their current configuration each time. * * @return this * @see Signature#generate() */ public SignOperation execute() { for (Signature signature : signatures) { signature.generate(); } return this; } /** * The registered signatures. */ public List<Signature> getSignatures() { return new ArrayList<Signature>(signatures); } /** * Returns the single registered signature. * * @return The signature. * @throws IllegalStateException if there is not exactly one registered signature. */ public Signature getSingleSignature() { final int size = signatures.size(); switch (size) { case 1: return signatures.get(0); case 0: throw new IllegalStateException("Expected operation to contain exactly one signature, however, it contains no signatures."); default: throw new IllegalStateException("Expected operation to contain exactly one signature, however, it contains " + String.valueOf(size) + " signatures."); } } /** * All of the files that will be signed by this operation. */ public FileCollection getFilesToSign() { return newSignatureFileCollection(new Function<Signature, File>() { @Override public File apply(Signature input) { return input.getToSign(); } }); } /** * All of the signature files that will be generated by this operation. */ public FileCollection getSignatureFiles() { return newSignatureFileCollection(new Function<Signature, File>() { @Override public File apply(Signature input) { return input.getFile(); } }); } private FileCollection newSignatureFileCollection(Function<Signature, File> getFile) { return ImmutableFileCollection.of(collectSignatureFiles(getFile)); } private ArrayList<File> collectSignatureFiles(Function<Signature, File> getFile) { ArrayList<File> files = new ArrayList<File>(signatures.size()); for (Signature signature : signatures) { File file = getFile.apply(signature); if (file != null) { files.add(file); } } return files; } }
robinverduijn/gradle
subprojects/signing/src/main/java/org/gradle/plugins/signing/SignOperation.java
Java
apache-2.0
7,371
/* * Copyright 2013-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.cloudfoundry.client.v2.spaces; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import org.cloudfoundry.Nullable; import org.immutables.value.Value; import java.util.List; /** * The request payload for the Update a Space operation */ @JsonSerialize @Value.Immutable abstract class _UpdateSpaceRequest { /** * Allow SSH */ @JsonProperty("allow_ssh") @Nullable abstract Boolean getAllowSsh(); /** * The auditor ids */ @JsonProperty("auditor_guids") @Nullable abstract List<String> getAuditorIds(); /** * The developer ids */ @JsonProperty("developer_guids") @Nullable abstract List<String> getDeveloperIds(); /** * The domain ids */ @JsonProperty("domain_guids") @Nullable abstract List<String> getDomainIds(); /** * The manager ids */ @JsonProperty("manager_guids") @Nullable abstract List<String> getManagerIds(); /** * The name */ @JsonProperty("name") @Nullable abstract String getName(); /** * The organization id */ @JsonProperty("organization_guid") @Nullable abstract String getOrganizationId(); /** * The security group ids */ @JsonProperty("security_group_guids") @Nullable abstract List<String> getSecurityGroupIds(); /** * The space id */ @JsonIgnore abstract String getSpaceId(); }
cloudfoundry/cf-java-client
cloudfoundry-client/src/main/java/org/cloudfoundry/client/v2/spaces/_UpdateSpaceRequest.java
Java
apache-2.0
2,193
<!DOCTYPE html> <!-- Copyright 2016 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://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 --> <html> <head> <meta charset="utf-8"> <title>MDC Toolbar Demo</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/png" href="/images/logo_components_color_2x_web_48dp.png" /> <script src="../assets/material-components-web.css.js" charset="utf-8"></script> <link href="../demos.css" rel="stylesheet"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <style> .mdc-toolbar-demo { margin: 0px; } .demo-paragraph { margin: 0px; padding: 20px 28px; } @media (max-width: 599px) { .demo-paragraph { padding: 16px; } } </style> </head> <body class="mdc-typography mdc-toolbar-demo"> <header class="mdc-toolbar mdc-toolbar--fixed"> <div class="mdc-toolbar__row"> <section class="mdc-toolbar__section mdc-toolbar__section--align-start"> <a href="#" class="material-icons mdc-toolbar__icon--menu">menu</a> <span class="mdc-toolbar__title">Title</span> </section> <section class="mdc-toolbar__section mdc-toolbar__section--align-end" role="toolbar"> <a href="#" class="material-icons mdc-toolbar__icon" aria-label="Download" alt="Download">file_download</a> <a href="#" class="material-icons mdc-toolbar__icon" aria-label="Print this page" alt="Print this page">print</a> <a href="#" class="material-icons mdc-toolbar__icon" aria-label="Bookmark this page" alt="Bookmark this page">more_vert</a> </section> </div> </header> <main> <div class="mdc-toolbar-fixed-adjust"> <p class="demo-paragraph"> Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. </p> <p class="demo-paragraph"> Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. </p> <p class="demo-paragraph"> Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. </p> </div> </main> </body> </html>
fillipegb/toksaude-prototipo
demos/toolbar/fixed-toolbar.html
HTML
apache-2.0
4,015
# AUTOGENERATED FILE FROM balenalib/orangepi-plus2-debian:bullseye-build ENV NODE_VERSION 12.21.0 ENV YARN_VERSION 1.22.4 RUN for key in \ 6A010C5166006599AA17F08146C2130DFD2497F5 \ ; do \ gpg --batch --keyserver pgp.mit.edu --recv-keys "$key" || \ gpg --batch --keyserver keyserver.pgp.com --recv-keys "$key" || \ gpg --batch --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \ done \ && curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-armv7l.tar.gz" \ && echo "6edc31a210e47eb72b0a2a150f7fe604539c1b2a45e8c81d378ac9315053a54f node-v$NODE_VERSION-linux-armv7l.tar.gz" | sha256sum -c - \ && tar -xzf "node-v$NODE_VERSION-linux-armv7l.tar.gz" -C /usr/local --strip-components=1 \ && rm "node-v$NODE_VERSION-linux-armv7l.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \ && gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && mkdir -p /opt/yarn \ && tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \ && rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && npm config set unsafe-perm true -g --unsafe-perm \ && rm -rf /tmp/* CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/[email protected]" \ && echo "Running test-stack@node" \ && chmod +x [email protected] \ && bash [email protected] \ && rm -rf [email protected] RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Debian Bullseye \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v12.21.0, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
nghiant2710/base-images
balena-base-images/node/orangepi-plus2/debian/bullseye/12.21.0/build/Dockerfile
Dockerfile
apache-2.0
2,795
/* ### * IP: GHIDRA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package agent.lldb.manager.evt; import agent.lldb.lldb.DebugThreadInfo; /** * The event corresponding with SBThread.eBroadcastBitThreadResumed */ public class LldbThreadResumedEvent extends AbstractLldbEvent<DebugThreadInfo> { public LldbThreadResumedEvent(DebugThreadInfo info) { super(info); } }
NationalSecurityAgency/ghidra
Ghidra/Debug/Debugger-agent-lldb/src/main/java/agent/lldb/manager/evt/LldbThreadResumedEvent.java
Java
apache-2.0
893
/** * Copyright (C) 2013 * by 52 North Initiative for Geospatial Open Source Software GmbH * * Contact: Andreas Wytzisk * 52 North Initiative for Geospatial Open Source Software GmbH * Martin-Luther-King-Weg 24 * 48155 Muenster, Germany * [email protected] * * This program is free software; you can redistribute and/or modify it under * the terms of the GNU General Public License version 2 as published by the * Free Software Foundation. * * This program is distributed WITHOUT ANY WARRANTY; even without the implied * WARRANTY OF MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program (see gnu-gpl v2.txt). If not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA or * visit the Free Software Foundation web page, http://www.fsf.org. */ package org.n52.sos.binding.rest.resources; import org.n52.sos.binding.rest.requests.RestRequest; /** * @author <a href="mailto:[email protected]">Eike Hinderk J&uuml;rrens</a> * */ public class OptionsRestRequest implements RestRequest { private String resourceType; private boolean isGlobalResource; private boolean isResourceCollection; public OptionsRestRequest(String resourceType, boolean isGlobalResource, boolean isResourceCollection) { this.resourceType = resourceType; this.isGlobalResource = isGlobalResource; this.isResourceCollection = isResourceCollection; } public String getResourceType() { return resourceType; } public boolean isGlobalResource() { return isGlobalResource; } public boolean isResourceCollection() { return isResourceCollection; } }
sauloperez/sos
src/bindings/rest/code/src/main/java/org/n52/sos/binding/rest/resources/OptionsRestRequest.java
Java
apache-2.0
1,863
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Watcher.Model { public class GreatThan : IPredicate { public string Quantifier { get { return "great than"; } } public bool IsSatisfiedBy(int a, int b) { return a > b; } } }
hotjk/ace
Watcher.Model/Predicate/GreatThan.cs
C#
apache-2.0
429
package org.adligo.tests4j.system.shared.trials; import org.adligo.tests4j.shared.common.ClassMethods; import org.adligo.tests4j.shared.xml.I_XML_Builder; public class TrialParamValue implements I_TrialParamValue { public static final String TAG_NAME = "value"; public static final String CLASS_NAME = "class"; public static final String PARAMETER_VALUE_MUST_BE_A_NON_VOID_PRIMITIVE_OR_STRING = "Parameter value must be a non Void primitive or String."; private Object value_; public TrialParamValue(Object value) { if (value == null) { throw new NullPointerException(); } Class<?> c = value.getClass(); if ( (ClassMethods.isPrimitiveClass(c) && !ClassMethods.isClass(Void.class, c)) || ClassMethods.isClass(String.class, c)) { value_ = value; } else { throw new IllegalArgumentException( PARAMETER_VALUE_MUST_BE_A_NON_VOID_PRIMITIVE_OR_STRING); } } @Override public String getClassName() { return value_.getClass().getName(); } @Override public Object getValue() { return value_; } @Override public void toXml(I_XML_Builder builder) { builder.addIndent(); builder.addStartTag(TAG_NAME); String name = ClassMethods.getSimpleName(value_.getClass()); builder.addAttribute(CLASS_NAME, name); builder.endHeader(); builder.addText(value_.toString()); builder.addEndTag(TAG_NAME); builder.endLine(); } }
adligo/tests4j.adligo.org
src/org/adligo/tests4j/system/shared/trials/TrialParamValue.java
Java
apache-2.0
1,384
""" Installs and configures MySQL """ import uuid import logging from packstack.installer import validators from packstack.installer import utils from packstack.modules.ospluginutils import getManifestTemplate, appendManifestFile # Controller object will be initialized from main flow controller = None # Plugin name PLUGIN_NAME = "OS-MySQL" PLUGIN_NAME_COLORED = utils.color_text(PLUGIN_NAME, 'blue') logging.debug("plugin %s loaded", __name__) def initConfig(controllerObject): global controller controller = controllerObject logging.debug("Adding MySQL OpenStack configuration") paramsList = [ {"CMD_OPTION" : "mysql-host", "USAGE" : "The IP address of the server on which to install MySQL", "PROMPT" : "Enter the IP address of the MySQL server", "OPTION_LIST" : [], "VALIDATORS" : [validators.validate_ssh], "DEFAULT_VALUE" : utils.get_localhost_ip(), "MASK_INPUT" : False, "LOOSE_VALIDATION": True, "CONF_NAME" : "CONFIG_MYSQL_HOST", "USE_DEFAULT" : False, "NEED_CONFIRM" : False, "CONDITION" : False }, {"CMD_OPTION" : "mysql-user", "USAGE" : "Username for the MySQL admin user", "PROMPT" : "Enter the username for the MySQL admin user", "OPTION_LIST" : [], "VALIDATORS" : [validators.validate_not_empty], "DEFAULT_VALUE" : "root", "MASK_INPUT" : False, "LOOSE_VALIDATION": False, "CONF_NAME" : "CONFIG_MYSQL_USER", "USE_DEFAULT" : True, "NEED_CONFIRM" : False, "CONDITION" : False }, {"CMD_OPTION" : "mysql-pw", "USAGE" : "Password for the MySQL admin user", "PROMPT" : "Enter the password for the MySQL admin user", "OPTION_LIST" : [], "VALIDATORS" : [validators.validate_not_empty], "DEFAULT_VALUE" : uuid.uuid4().hex[:16], "MASK_INPUT" : True, "LOOSE_VALIDATION": True, "CONF_NAME" : "CONFIG_MYSQL_PW", "USE_DEFAULT" : False, "NEED_CONFIRM" : True, "CONDITION" : False }, ] groupDict = { "GROUP_NAME" : "MYSQL", "DESCRIPTION" : "MySQL Config parameters", "PRE_CONDITION" : lambda x: 'yes', "PRE_CONDITION_MATCH" : "yes", "POST_CONDITION" : False, "POST_CONDITION_MATCH" : True} controller.addGroup(groupDict, paramsList) def initSequences(controller): mysqlsteps = [ {'title': 'Adding MySQL manifest entries', 'functions':[createmanifest]} ] controller.addSequence("Installing MySQL", [], [], mysqlsteps) def createmanifest(config): if config['CONFIG_MYSQL_INSTALL'] == 'y': install = True suffix = 'install' else: install = False suffix = 'noinstall' # In case we are not installing MySQL server, mysql* manifests have # to be run from Keystone host host = install and config['CONFIG_MYSQL_HOST'] \ or config['CONFIG_KEYSTONE_HOST'] manifestfile = "%s_mysql.pp" % host manifestdata = [getManifestTemplate('mysql_%s.pp' % suffix)] def append_for(module, suffix): # Modules have to be appended to the existing mysql.pp # otherwise pp will fail for some of them saying that # Mysql::Config definition is missing. template = "mysql_%s_%s.pp" % (module, suffix) manifestdata.append(getManifestTemplate(template)) append_for("keystone", suffix) hosts = set() for mod in ['nova', 'cinder', 'glance', 'neutron', 'heat']: if config['CONFIG_%s_INSTALL' % mod.upper()] == 'y': append_for(mod, suffix) # Check wich modules are enabled so we can allow their # hosts on the firewall if mod != 'nova' and mod != 'neutron': hosts.add(config.get('CONFIG_%s_HOST' % mod.upper()).strip()) elif mod == 'neutron': hosts.add(config.get('CONFIG_NEUTRON_SERVER_HOST').strip()) elif config['CONFIG_NOVA_INSTALL'] != 'n': #In that remote case that we have lot's of nova hosts hosts.add(config.get('CONFIG_NOVA_API_HOST').strip()) hosts.add(config.get('CONFIG_NOVA_CERT_HOST').strip()) hosts.add(config.get('CONFIG_NOVA_VNCPROXY_HOST').strip()) hosts.add(config.get('CONFIG_NOVA_CONDUCTOR_HOST').strip()) hosts.add(config.get('CONFIG_NOVA_SCHED_HOST').strip()) if config['CONFIG_NEUTRON_INSTALL'] != 'y': dbhosts = split_hosts(config['CONFIG_NOVA_NETWORK_HOSTS']) hosts |= dbhosts for host in config.get('CONFIG_NOVA_COMPUTE_HOSTS').split(','): hosts.add(host.strip()) config['FIREWALL_ALLOWED'] = ",".join(["'%s'" % i for i in hosts]) config['FIREWALL_SERVICE_NAME'] = "mysql" config['FIREWALL_PORTS'] = "'3306'" manifestdata.append(getManifestTemplate("firewall.pp")) appendManifestFile(manifestfile, "\n".join(manifestdata), 'pre')
tangfeixiong/packstack
packstack/plugins/mysql_001.py
Python
apache-2.0
5,760
```nginx server { listen 80; charset utf-8; client_max_body_size 128M; server_name meotrics.com; return 301 https://$host$request_uri; } server { listen 80; server_name www.meotrics.com; return 301 http://meotrics.com$request_uri; } server { listen 443; server_name www.meotrics.com meotrics.com; ssl on; ssl_certificate /etc/ssl/certs/chained.pem; ssl_certificate_key /etc/ssl/private/domain.key; ssl_session_timeout 5m; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-G$ ssl_session_cache shared:SSL:50m; ssl_dhparam /etc/ssl/certs/dhparam.pem; ssl_prefer_server_ciphers on; root /home/thanhpk/meotrics/landing/; location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ { expires 1y; log_not_found off; } server_tokens off; #more_set_headers "Server: Meotrics"; index index.html; location ~ /\.(ht|svn|git) { deny all; } # Common bandwidth hoggers and hacking tools. if ($http_user_agent ~ "libwww-perl") { set $block_user_agents 1; } if ($http_user_agent ~ "GetRight") { set $block_user_agents 1; } if ($http_user_agent ~ "GetWeb!") { set $block_user_agents 1; } if ($http_user_agent ~ "Go!Zilla") { set $block_user_agents 1; } if ($http_user_agent ~ "Download Demon") { set $block_user_agents 1; } if ($http_user_agent ~ "Go-Ahead-Got-It") { set $block_user_agents 1; } if ($http_user_agent ~ "TurnitinBot") { set $block_user_agents 1; } if ($http_user_agent ~ "GrabNet") { set $block_user_agents 1; } if ($block_user_agents = 1) { return 403; } } server { listen 80; server_name api.meotrics.com; location / { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_pass http://127.0.0.1:1711/api; } } server { listen 443; server_name api.meotrics.com; ssl on; ssl_certificate /etc/ssl/certs/chained.pem; ssl_certificate_key /etc/ssl/private/domain.key; ssl_session_timeout 5m; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA; ssl_session_cache shared:SSL:50m; ssl_dhparam /etc/ssl/certs/dhparam.pem; ssl_prefer_server_ciphers on; large_client_header_buffers 8 32k; location / { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_pass http://127.0.0.1:1711/api; } } server { listen 80; server_name app.meotrics.com; return 301 https://$server_name$request_uri; } map $http_upgrade $connection_upgrade{ default upgrade; '' close; } upstream websocket { server 127.0.0.1:2910; } server { charset utf-8; listen 443; server_name app.meotrics.com; root /home/thanhpk/meotrics/dashboard/public/; index index.php; ssl on; ssl_certificate /etc/ssl/certs/chained.pem; ssl_certificate_key /etc/ssl/private/domain.key; ssl_session_timeout 5m; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA; ssl_session_cache shared:SSL:50m; ssl_dhparam /etc/ssl/certs/dhparam.pem; ssl_prefer_server_ciphers on; access_log /home/thanhpk/tmp/meotrics-access443.log; error_log /home/thanhpk/tmp/meotrics-error443.log; location /ws { proxy_pass http://websocket; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; } location / { try_files $uri $uri/ /index.php?$args; } location ~ \.php$ { include fastcgi_params; fastcgi_param REMOTE_ADDR $http_x_real_ip; fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name; fastcgi_pass unix:/var/run/php5-fpm.sock; try_files $uri =404; } location ~ /\.(ht|svn|git) { deny all; } } ```
meotrics/meotrics
docs/nginxconf.md
Markdown
apache-2.0
4,477
/* Copyright 2018 The OpenEBS Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package v1alpha2 import ( ndmapis "github.com/openebs/maya/pkg/apis/openebs.io/ndm/v1alpha1" apis "github.com/openebs/maya/pkg/apis/openebs.io/v1alpha1" bd "github.com/openebs/maya/pkg/blockdevice/v1alpha2" bdc "github.com/openebs/maya/pkg/blockdeviceclaim/v1alpha1" cspc "github.com/openebs/maya/pkg/cstor/poolcluster/v1alpha1" csp "github.com/openebs/maya/pkg/cstor/poolinstance/v1alpha3" nodeapis "github.com/openebs/maya/pkg/kubernetes/node/v1alpha1" "github.com/openebs/maya/pkg/volume" "github.com/pkg/errors" k8serror "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/klog" ) // SelectNode returns a node where pool should be created. func (ac *Config) SelectNode() (*apis.PoolSpec, string, error) { usedNodes, err := ac.GetUsedNode() if err != nil { return nil, "", errors.Wrapf(err, "could not get used nodes list for pool creation") } for _, pool := range ac.CSPC.Spec.Pools { // pin it pool := pool nodeName, err := GetNodeFromLabelSelector(pool.NodeSelector) if err != nil || nodeName == "" { klog.Errorf("could not use node for selectors {%v}", pool.NodeSelector) continue } if ac.VisitedNodes[nodeName] { continue } else { ac.VisitedNodes[nodeName] = true if !usedNodes[nodeName] { return &pool, nodeName, nil } } } return nil, "", errors.New("no node qualified for pool creation") } // GetNodeFromLabelSelector returns the node name selected by provided labels // TODO : Move it to node package func GetNodeFromLabelSelector(labels map[string]string) (string, error) { nodeList, err := nodeapis.NewKubeClient().List(metav1.ListOptions{LabelSelector: getLabelSelectorString(labels)}) if err != nil { return "", errors.Wrap(err, "failed to get node list from the node selector") } if len(nodeList.Items) != 1 { return "", errors.Errorf("invalid no.of nodes %d from the given node selectors", len(nodeList.Items)) } return nodeList.Items[0].Name, nil } // getLabelSelectorString returns a string of label selector form label map to be used in // list options. // TODO : Move it to node package func getLabelSelectorString(selector map[string]string) string { var selectorString string for key, value := range selector { selectorString = selectorString + key + "=" + value + "," } selectorString = selectorString[:len(selectorString)-len(",")] return selectorString } // GetUsedNode returns a map of node for which pool has already been created. // Note : Filter function is not used from node builder package as it needs // CSP builder package which cam cause import loops. func (ac *Config) GetUsedNode() (map[string]bool, error) { usedNode := make(map[string]bool) cspList, err := csp. NewKubeClient(). WithNamespace(ac.Namespace). List( metav1. ListOptions{LabelSelector: string(apis.CStorPoolClusterCPK) + "=" + ac.CSPC.Name}, ) if err != nil { return nil, errors.Wrap(err, "could not list already created csp(s)") } for _, cspObj := range cspList.Items { usedNode[cspObj.Labels[string(apis.HostNameCPK)]] = true } return usedNode, nil } // GetBDListForNode returns a list of BD from the pool spec. // TODO : Move it to CStorPoolCluster packgage func (ac *Config) GetBDListForNode(pool *apis.PoolSpec) []string { var BDList []string for _, group := range pool.RaidGroups { for _, bd := range group.BlockDevices { BDList = append(BDList, bd.BlockDeviceName) } } return BDList } // ClaimBDsForNode claims a given BlockDevice for node // If the block device(s) is/are already claimed for any other CSPC it returns error. // If the block device(s) is/are already calimed for the same CSPC -- it is left as it is and can be used for // pool provisioning. // If the block device(s) is/are unclaimed, then those are claimed. func (ac *Config) ClaimBDsForNode(BD []string) error { pendingClaim := 0 for _, bdName := range BD { bdAPIObj, err := bd.NewKubeClient().WithNamespace(ac.Namespace).Get(bdName, metav1.GetOptions{}) if err != nil { return errors.Wrapf(err, "error in getting details for BD {%s} whether it is claimed", bdName) } if bd.BuilderForAPIObject(bdAPIObj).BlockDevice.IsClaimed() { IsClaimedBDUsable, errBD := ac.IsClaimedBDUsable(bdAPIObj) if errBD != nil { return errors.Wrapf(err, "error in getting details for BD {%s} for usability", bdName) } if !IsClaimedBDUsable { return errors.Errorf("BD {%s} already in use", bdName) } continue } err = ac.ClaimBD(bdAPIObj) if err != nil { return errors.Wrapf(err, "Failed to claim BD {%s}", bdName) } pendingClaim++ } if pendingClaim > 0 { return errors.Errorf("%d block device claims are pending", pendingClaim) } return nil } // ClaimBD claims a given BlockDevice func (ac *Config) ClaimBD(bdObj *ndmapis.BlockDevice) error { newBDCObj, err := bdc.NewBuilder(). WithName("bdc-cstor-" + string(bdObj.UID)). WithNamespace(ac.Namespace). WithLabels(map[string]string{string(apis.CStorPoolClusterCPK): ac.CSPC.Name}). WithBlockDeviceName(bdObj.Name). WithHostName(bdObj.Labels[string(apis.HostNameCPK)]). WithCapacity(volume.ByteCount(bdObj.Spec.Capacity.Storage)). WithCSPCOwnerReference(ac.CSPC). WithFinalizer(cspc.CSPCFinalizer). Build() if err != nil { return errors.Wrapf(err, "failed to build block device claim for bd {%s}", bdObj.Name) } _, err = bdc.NewKubeClient().WithNamespace(ac.Namespace).Create(newBDCObj.Object) if k8serror.IsAlreadyExists(err) { klog.Infof("BDC for BD {%s} already created", bdObj.Name) return nil } if err != nil { return errors.Wrapf(err, "failed to create block device claim for bd {%s}", bdObj.Name) } return nil } // IsClaimedBDUsable returns true if the passed BD is already claimed and can be // used for provisioning func (ac *Config) IsClaimedBDUsable(bdAPIObj *ndmapis.BlockDevice) (bool, error) { bdObj := bd.BuilderForAPIObject(bdAPIObj) if bdObj.BlockDevice.IsClaimed() { bdcName := bdObj.BlockDevice.Object.Spec.ClaimRef.Name bdcAPIObject, err := bdc.NewKubeClient().WithNamespace(ac.Namespace).Get(bdcName, metav1.GetOptions{}) if err != nil { return false, errors.Wrapf(err, "could not get block device claim for block device {%s}", bdAPIObj.Name) } bdcObj := bdc.BuilderForAPIObject(bdcAPIObject) if bdcObj.BDC.HasLabel(string(apis.CStorPoolClusterCPK), ac.CSPC.Name) { return true, nil } } else { return false, errors.Errorf("block device {%s} is not claimed", bdAPIObj.Name) } return false, nil } // ValidatePoolSpec validates the pool spec. // TODO: Fix following function -- (Current is mock only ) func ValidatePoolSpec(pool *apis.PoolSpec) bool { return true }
prateekpandey14/maya
pkg/algorithm/nodeselect/v1alpha2/select_node.go
GO
apache-2.0
7,242
#ifndef __PropertyGroup_h__ #define __PropertyGroup_h__ /* -------------------------------------------------------------------------- * * OpenSim: PropertyGroup.h * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2017 Stanford University and the Authors * * Author(s): Peter Loan * * * * 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. * * -------------------------------------------------------------------------- */ #ifdef _WIN32 #pragma warning( disable : 4251 ) #endif // INCLUDE #include "osimCommonDLL.h" #include "Property_Deprecated.h" #include "Array.h" namespace OpenSim { #ifdef SWIG #ifdef OSIMCOMMON_API #undef OSIMCOMMON_API #define OSIMCOMMON_API #endif #endif //============================================================================= //============================================================================= /** * A class implementing a property group. * * @author Peter Loan * @version 1.0 */ class OSIMCOMMON_API PropertyGroup { //============================================================================= // DATA //============================================================================= private: /** Name of the group. */ std::string _name; protected: /** Pointers to the properties in the group. */ Array<Property_Deprecated*> _properties; //============================================================================= // METHODS //============================================================================= //-------------------------------------------------------------------------- // CONSTRUCTION //-------------------------------------------------------------------------- public: PropertyGroup(); PropertyGroup(std::string& aName); PropertyGroup(const PropertyGroup &aGroup); virtual ~PropertyGroup(); virtual PropertyGroup* clone() const; #ifndef SWIG PropertyGroup& operator=(const PropertyGroup &aGroup); bool operator<(const PropertyGroup &aGroup) const; bool operator==(const PropertyGroup& aGroup) const; #endif void copyData(const PropertyGroup &aGroup); void clear(); bool contains(const std::string& aName) const; void add(Property_Deprecated* aProperty); void remove(Property_Deprecated* aProperty); #ifndef SWIG const Array<Property_Deprecated*>& getProperties() const { return _properties; } #endif Property_Deprecated* get(int aIndex); int getPropertyIndex(Property_Deprecated* aProperty) const; // NAME void setName(const std::string &aName) { _name = aName; } const std::string& getName() const { return _name; } private: void setNull(); //============================================================================= }; // END of class PropertyGroup //============================================================================= //============================================================================= } // end of namespace OpenSim #endif // __PropertyGroup_h__
opensim-org/opensim-core
OpenSim/Common/PropertyGroup.h
C
apache-2.0
4,388
define( ['app/models/proto_model'], function(ProtoModel) { var Model = ProtoModel.extend({ // matches first part of method name in @remote.method urlRoot: '/cru_api.order_', must_be_floats: ['sub_total', 'actual_total'], }); return Model; } );
babybunny/rebuildingtogethercaptain
gae/js/app/models/order.js
JavaScript
apache-2.0
317
#include <cassert> #include <iostream> #include <sstream> #include <boost/program_options/variables_map.hpp> #include "optimize.h" #include "online_optimizer.h" #include "sparse_vector.h" #include "fdict.h" using namespace std; double TestOptimizer(BatchOptimizer* opt) { cerr << "TESTING NON-PERSISTENT OPTIMIZER\n"; // f(x,y) = 4x1^2 + x1*x2 + x2^2 + x3^2 + 6x3 + 5 // df/dx1 = 8*x1 + x2 // df/dx2 = 2*x2 + x1 // df/dx3 = 2*x3 + 6 vector<double> x(3); vector<double> g(3); x[0] = 8; x[1] = 8; x[2] = 8; double obj = 0; do { g[0] = 8 * x[0] + x[1]; g[1] = 2 * x[1] + x[0]; g[2] = 2 * x[2] + 6; obj = 4 * x[0]*x[0] + x[0] * x[1] + x[1]*x[1] + x[2]*x[2] + 6 * x[2] + 5; opt->Optimize(obj, g, &x); cerr << x[0] << " " << x[1] << " " << x[2] << endl; cerr << " obj=" << obj << "\td/dx1=" << g[0] << " d/dx2=" << g[1] << " d/dx3=" << g[2] << endl; } while (!opt->HasConverged()); return obj; } double TestPersistentOptimizer(BatchOptimizer* opt) { cerr << "\nTESTING PERSISTENT OPTIMIZER\n"; // f(x,y) = 4x1^2 + x1*x2 + x2^2 + x3^2 + 6x3 + 5 // df/dx1 = 8*x1 + x2 // df/dx2 = 2*x2 + x1 // df/dx3 = 2*x3 + 6 vector<double> x(3); vector<double> g(3); x[0] = 8; x[1] = 8; x[2] = 8; double obj = 0; string state; bool converged = false; while (!converged) { g[0] = 8 * x[0] + x[1]; g[1] = 2 * x[1] + x[0]; g[2] = 2 * x[2] + 6; obj = 4 * x[0]*x[0] + x[0] * x[1] + x[1]*x[1] + x[2]*x[2] + 6 * x[2] + 5; { if (state.size() > 0) { istringstream is(state, ios::binary); opt->Load(&is); } opt->Optimize(obj, g, &x); ostringstream os(ios::binary); opt->Save(&os); state = os.str(); } cerr << x[0] << " " << x[1] << " " << x[2] << endl; cerr << " obj=" << obj << "\td/dx1=" << g[0] << " d/dx2=" << g[1] << " d/dx3=" << g[2] << endl; converged = opt->HasConverged(); if (!converged) { // now screw up the state (should be undone by Load) obj += 2.0; g[1] = -g[2]; vector<double> x2 = x; try { opt->Optimize(obj, g, &x2); } catch (...) { } } } return obj; } template <class O> void TestOptimizerVariants(int num_vars) { O oa(num_vars); cerr << "-------------------------------------------------------------------------\n"; cerr << "TESTING: " << oa.Name() << endl; double o1 = TestOptimizer(&oa); O ob(num_vars); double o2 = TestPersistentOptimizer(&ob); if (o1 != o2) { cerr << oa.Name() << " VARIANTS PERFORMED DIFFERENTLY!\n" << o1 << " vs. " << o2 << endl; exit(1); } cerr << oa.Name() << " SUCCESS\n"; } using namespace std::tr1; void TestOnline() { size_t N = 20; double C = 1.0; double eta0 = 0.2; std::tr1::shared_ptr<LearningRateSchedule> r(new ExponentialDecayLearningRate(N, eta0, 0.85)); //shared_ptr<LearningRateSchedule> r(new StandardLearningRate(N, eta0)); CumulativeL1OnlineOptimizer opt(r, N, C, std::vector<int>()); assert(r->eta(10) < r->eta(1)); } int main() { int n = 3; TestOptimizerVariants<LBFGSOptimizer>(n); TestOptimizerVariants<RPropOptimizer>(n); TestOnline(); return 0; }
kho/mr-cdec
training/utils/optimize_test.cc
C++
apache-2.0
3,168
package com.sequenceiq.freeipa.entity.util; import com.sequenceiq.cloudbreak.converter.DefaultEnumConverter; import com.sequenceiq.freeipa.api.v1.kerberos.model.KerberosType; public class KerberosTypeConverter extends DefaultEnumConverter<KerberosType> { @Override public KerberosType getDefault() { return KerberosType.FREEIPA; } }
hortonworks/cloudbreak
freeipa/src/main/java/com/sequenceiq/freeipa/entity/util/KerberosTypeConverter.java
Java
apache-2.0
356
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="Ionic makes it incredibly easy to build beautiful and interactive mobile apps using HTML5 and AngularJS."> <meta name="keywords" content="html5,javascript,mobile,drifty,ionic,hybrid,phonegap,cordova,native,ios,android,angularjs"> <meta name="author" content="Drifty"> <meta property="og:image" content="http://ionicframework.com/img/ionic-logo-blog.png"/> <!-- version /docs/1.0.0-beta.10 should not be indexed --> <meta name="robots" content="noindex"> <title>Services in module ionic - 11 services - Ionic Framework</title> <link href="/css/site.css?12" rel="stylesheet"> <!--<script src="//cdn.optimizely.com/js/595530035.js"></script>--> <script type="text/javascript">var _sf_startpt=(new Date()).getTime()</script> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-44023830-1', 'ionicframework.com'); ga('send', 'pageview'); </script> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> </head> <body class="docs docs-page docs-api"> <nav class="navbar navbar-default horizontal-gradient" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle button ionic" data-toggle="collapse" data-target=".navbar-ex1-collapse"> <i class="icon ion-navicon"></i> </button> <a class="navbar-brand" href="/"> <img src="/img/ionic-logo-white.svg" width="123" height="43" alt="Ionic Framework"> </a> <a href="http://blog.ionic.io/announcing-ionic-1-0/" target="_blank"> <img src="/img/ionic1-tag.png" alt="Ionic 1.0 is out!" width="28" height="32" style="margin-left: 140px; margin-top:22px; display:block"> </a> </div> <div class="collapse navbar-collapse navbar-ex1-collapse"> <ul class="nav navbar-nav navbar-right"> <li><a class="getting-started-nav nav-link" href="/getting-started/">Getting Started</a></li> <li><a class="docs-nav nav-link" href="/docs/">Docs</a></li> <li><a class="nav-link" href="http://ionic.io/support">Support</a></li> <li><a class="blog-nav nav-link" href="http://blog.ionic.io/">Blog <span id="blog-badge">1</span></a></li> <li><a class="nav-link" href="http://forum.ionicframework.com/">Forum</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">More <span class="caret"></span></a> <ul class="dropdown-menu" role="menu"> <div class="arrow-up"></div> <li><a class="products-nav nav-link" href="http://ionic.io/">Ionic.io</a></li> <li><a class="examples-nav nav-link" href="http://showcase.ionicframework.com/">Showcase</a></li> <li><a class="nav-link" href="http://jobs.ionic.io/">Job Board</a></li> <li><a class="nav-link" href="http://market.ionic.io/">Market</a></li> <li><a class="nav-link" href="http://ionicworldwide.herokuapp.com/">Ionic Worldwide</a></li> <li><a class="nav-link" href="http://play.ionic.io/">Playground</a></li> <li><a class="nav-link" href="http://creator.ionic.io/">Creator</a></li> <li><a class="nav-link" href="http://shop.ionic.io/">Shop</a></li> <!--<li><a class="nav-link" href="http://ngcordova.com/">ngCordova</a></li>--> </ul> </li> </ul> </div> </div> </nav> <div class="header horizontal-gradient"> <div class="container"> <h3>Services in module ionic</h3> <h4>11 services</h4> </div> <div class="news"> <div class="container"> <div class="row"> <div class="col-sm-8 news-col"> <div class="picker"> <select onchange="window.location.href=this.options[this.selectedIndex].value"> <option value="/docs/nightly/api/ionic/service" > nightly </option> <option value="/docs/api/ionic/service" > 1.1.0 (latest) </option> <option value="/docs/1.0.1/api/ionic/service" > 1.0.1 </option> <option value="/docs/1.0.0/api/ionic/service" > 1.0.0 </option> <option value="/docs/1.0.0-rc.5/api/ionic/service" > 1.0.0-rc.5 </option> <option value="/docs/1.0.0-rc.4/api/ionic/service" > 1.0.0-rc.4 </option> <option value="/docs/1.0.0-rc.3/api/ionic/service" > 1.0.0-rc.3 </option> <option value="/docs/1.0.0-rc.2/api/ionic/service" > 1.0.0-rc.2 </option> <option value="/docs/1.0.0-rc.1/api/ionic/service" > 1.0.0-rc.1 </option> <option value="/docs/1.0.0-rc.0/api/ionic/service" > 1.0.0-rc.0 </option> <option value="/docs/1.0.0-beta.14/api/ionic/service" > 1.0.0-beta.14 </option> <option value="/docs/1.0.0-beta.13/api/ionic/service" > 1.0.0-beta.13 </option> <option value="/docs/1.0.0-beta.12/api/ionic/service" > 1.0.0-beta.12 </option> <option value="/docs/1.0.0-beta.11/api/ionic/service" > 1.0.0-beta.11 </option> <option value="/docs/1.0.0-beta.10/api/ionic/service" > 1.0.0-beta.10 </option> </select> </div> </div> <div class="col-sm-4 search-col"> <div class="search-bar"> <span class="search-icon ionic"><i class="ion-ios7-search-strong"></i></span> <input type="search" id="search-input" value="Search"> </div> </div> </div> </div> </div> </div> <div id="search-results" class="search-results" style="display:none"> <div class="container"> <div class="search-section search-api"> <h4>JavaScript</h4> <ul id="results-api"></ul> </div> <div class="search-section search-css"> <h4>CSS</h4> <ul id="results-css"></ul> </div> <div class="search-section search-content"> <h4>Resources</h4> <ul id="results-content"></ul> </div> </div> </div> <div class="container content-container"> <div class="row"> <div class="col-md-2 col-sm-3 aside-menu"> <div> <ul class="nav left-menu"> <li class="menu-title"> <a href="/docs/overview/">Overview</a> </li> </ul> <ul class="nav left-menu"> <li class="menu-title"> <a href="/docs/components/">CSS</a> </li> </ul> <!-- Docs: JavaScript --> <ul class="nav left-menu active-menu"> <li class="menu-title"> <a href="/docs/1.0.0-beta.10/api/"> JavaScript </a> </li> <!-- Tabs --> <li class="menu-section"> <a href="#" class="api-section"> Tabs </a> <ul> <li> <a href="/docs/1.0.0-beta.10/api/directive/ionTabs/"> ion-tabs </a> </li> <li> <a href="/docs/1.0.0-beta.10/api/directive/ionTab/"> ion-tab </a> </li> <li> <a href="/docs/1.0.0-beta.10/api/service/$ionicTabsDelegate/"> $ionicTabsDelegate </a> </li> </ul> </li> <!-- Side Menus --> <li class="menu-section"> <a href="#" class="api-section"> Side Menus </a> <ul> <li> <a href="/docs/1.0.0-beta.10/api/directive/ionSideMenus/"> ion-side-menus </a> </li> <li> <a href="/docs/1.0.0-beta.10/api/directive/ionSideMenuContent/"> ion-side-menu-content </a> </li> <li> <a href="/docs/1.0.0-beta.10/api/directive/ionSideMenu/"> ion-side-menu </a> </li> <li> <a href="/docs/1.0.0-beta.10/api/directive/menuToggle/"> menu-toggle </a> </li> <li> <a href="/docs/1.0.0-beta.10/api/directive/menuClose/"> menu-close </a> </li> <li> <a href="/docs/1.0.0-beta.10/api/service/$ionicSideMenuDelegate/"> $ionicSideMenuDelegate </a> </li> </ul> </li> <!-- Navigation --> <li class="menu-section"> <a href="#" class="api-section"> Navigation </a> <ul> <li> <a href="/docs/1.0.0-beta.10/api/directive/ionNavView/"> ion-nav-view </a> </li> <li> <a href="/docs/1.0.0-beta.10/api/directive/ionView/"> ion-view </a> </li> <li> <a href="/docs/1.0.0-beta.10/api/directive/ionNavBar/"> ion-nav-bar </a> </li> <li> <a href="/docs/1.0.0-beta.10/api/directive/ionNavButtons/"> ion-nav-buttons </a> </li> <li> <a href="/docs/1.0.0-beta.10/api/directive/ionNavBackButton/"> ion-nav-back-button </a> </li> <li> <a href="/docs/1.0.0-beta.10/api/directive/navClear/"> nav-clear </a> </li> <li> <a href="/docs/1.0.0-beta.10/api/service/$ionicNavBarDelegate/"> $ionicNavBarDelegate </a> </li> </ul> </li> <!-- Headers/Footers --> <li class="menu-section"> <a href="#" class="api-section"> Headers/Footers </a> <ul> <li> <a href="/docs/1.0.0-beta.10/api/directive/ionHeaderBar/"> ion-header-bar </a> </li> <li> <a href="/docs/1.0.0-beta.10/api/directive/ionFooterBar/"> ion-footer-bar </a> </li> </ul> </li> <!-- Content --> <li class="menu-section"> <a href="#" class="api-section"> Content </a> <ul> <li> <a href="/docs/1.0.0-beta.10/api/directive/ionContent/"> ion-content </a> </li> <li> <a href="/docs/1.0.0-beta.10/api/directive/ionRefresher/"> ion-refresher </a> </li> <li> <a href="/docs/1.0.0-beta.10/api/directive/ionPane/"> ion-pane </a> </li> </ul> </li> <!-- Scroll --> <li class="menu-section"> <a href="#" class="api-section"> Scroll </a> <ul> <li> <a href="/docs/1.0.0-beta.10/api/directive/ionScroll/"> ion-scroll </a> </li> <li> <a href="/docs/1.0.0-beta.10/api/directive/ionInfiniteScroll/"> ion-infinite-scroll </a> </li> <li> <a href="/docs/1.0.0-beta.10/api/service/$ionicScrollDelegate/"> $ionicScrollDelegate </a> </li> </ul> </li> <!-- Lists --> <li class="menu-section"> <a href="#" class="api-section"> Lists </a> <ul> <li> <a href="/docs/1.0.0-beta.10/api/directive/ionList/"> ion-list </a> </li> <li> <a href="/docs/1.0.0-beta.10/api/directive/ionItem/"> ion-item </a> </li> <li> <a href="/docs/1.0.0-beta.10/api/directive/ionDeleteButton/"> ion-delete-button </a> </li> <li> <a href="/docs/1.0.0-beta.10/api/directive/ionReorderButton/"> ion-reorder-button </a> </li> <li> <a href="/docs/1.0.0-beta.10/api/directive/ionOptionButton/"> ion-option-button </a> </li> <li> <a href="/docs/1.0.0-beta.10/api/directive/collectionRepeat/"> collection-repeat </a> </li> <li> <a href="/docs/1.0.0-beta.10/api/service/$ionicListDelegate/"> $ionicListDelegate </a> </li> </ul> </li> <!-- Form Inputs --> <li class="menu-section"> <a href="#" class="api-section"> Form Inputs </a> <ul> <li> <a href="/docs/1.0.0-beta.10/api/directive/ionCheckbox/"> ion-checkbox </a> </li> <li> <a href="/docs/1.0.0-beta.10/api/directive/ionRadio/"> ion-radio </a> </li> <li> <a href="/docs/1.0.0-beta.10/api/directive/ionToggle/"> ion-toggle </a> </li> </ul> </li> <!-- Slide Box --> <li class="menu-section"> <a href="#" class="api-section"> Slide Box </a> <ul> <li> <a href="/docs/1.0.0-beta.10/api/directive/ionSlideBox/"> ion-slide-box </a> </li> <li> <a href="/docs/1.0.0-beta.10/api/service/$ionicSlideBoxDelegate/"> $ionicSlideBoxDelegate </a> </li> </ul> </li> <!-- Modal --> <li class="menu-section"> <a href="#" class="api-section"> Modal </a> <ul> <li> <a href="/docs/1.0.0-beta.10/api/service/$ionicModal/"> $ionicModal </a> </li> <li> <a href="/docs/1.0.0-beta.10/api/controller/ionicModal/"> ionicModal </a> </li> </ul> </li> <!-- Action Sheet --> <li class="menu-section"> <a href="#" class="api-section"> Action Sheet </a> <ul> <li> <a href="/docs/1.0.0-beta.10/api/service/$ionicActionSheet/"> $ionicActionSheet </a> </li> </ul> </li> <!-- Popup --> <li class="menu-section"> <a href="#" class="api-section"> Popup </a> <ul> <li> <a href="/docs/1.0.0-beta.10/api/service/$ionicPopup/"> $ionicPopup </a> </li> </ul> </li> <!-- Loading --> <li class="menu-section"> <a href="#" class="api-section"> Loading </a> <ul> <li> <a href="/docs/1.0.0-beta.10/api/service/$ionicLoading/"> $ionicLoading </a> </li> </ul> <ul> <li> <a href="/docs/1.0.0-beta.10/api/object/$ionicLoadingConfig/"> $ionicLoadingConfig </a> </li> </ul> </li> <!-- Platform --> <li class="menu-section"> <a href="#" class="api-section"> Platform </a> <ul> <li> <a href="/docs/1.0.0-beta.10/api/service/$ionicPlatform/"> $ionicPlatform </a> </li> </ul> </li> <!-- Events --> <li class="menu-section"> <a href="#" class="api-section"> Events </a> <ul> <li> <a href="/docs/1.0.0-beta.10/api/directive/onHold/"> on-hold </a> </li> <li> <a href="/docs/1.0.0-beta.10/api/directive/onTap/"> on-tap </a> </li> <li> <a href="/docs/1.0.0-beta.10/api/directive/onTouch/"> on-touch </a> </li> <li> <a href="/docs/1.0.0-beta.10/api/directive/onRelease/"> on-release </a> </li> <li> <a href="/docs/1.0.0-beta.10/api/directive/onDrag/"> on-drag </a> </li> <li> <a href="/docs/1.0.0-beta.10/api/directive/onDragUp/"> on-drag-up </a> </li> <li> <a href="/docs/1.0.0-beta.10/api/directive/onDragRight/"> on-drag-right </a> </li> <li> <a href="/docs/1.0.0-beta.10/api/directive/onDragDown/"> on-drag-down </a> </li> <li> <a href="/docs/1.0.0-beta.10/api/directive/onDragLeft/"> on-drag-left </a> </li> <li> <a href="/docs/1.0.0-beta.10/api/directive/onSwipe/"> on-swipe </a> </li> <li> <a href="/docs/1.0.0-beta.10/api/directive/onSwipeUp/"> on-swipe-up </a> </li> <li> <a href="/docs/1.0.0-beta.10/api/directive/onSwipeRight/"> on-swipe-right </a> </li> <li> <a href="/docs/1.0.0-beta.10/api/directive/onSwipeDown/"> on-swipe-down </a> </li> <li> <a href="/docs/1.0.0-beta.10/api/directive/onSwipeLeft/"> on-swipe-left </a> </li> </ul> </li> <!-- Gesture --> <li class="menu-section"> <a href="#" class="api-section"> Gesture </a> <ul> <li> <a href="/docs/1.0.0-beta.10/api/service/$ionicGesture/"> $ionicGesture </a> </li> </ul> </li> <!-- Backdrop --> <li class="menu-section"> <a href="#" class="api-section"> Backdrop </a> <ul> <li> <a href="/docs/1.0.0-beta.10/api/service/$ionicBackdrop/"> $ionicBackdrop </a> </li> </ul> </li> <!-- Utility --> <li class="menu-section"> <a href="#" class="api-section"> Utility </a> <ul> <li> <a href="/docs/1.0.0-beta.10/api/utility/ionic.Platform/"> ionic.Platform </a> </li> <li> <a href="/docs/1.0.0-beta.10/api/utility/ionic.DomUtil/"> ionic.DomUtil </a> </li> <li> <a href="/docs/1.0.0-beta.10/api/utility/ionic.EventController/"> ionic.EventController </a> </li> </ul> </li> <!-- Tap --> <li class="menu-section"> <a href="/docs/1.0.0-beta.10/api/page/tap/" class="api-section"> Tap &amp; Click </a> </li> <!-- Keyboard --> <li class="menu-section"> <a href="#" class="api-section"> Keyboard </a> <ul> <li> <a href="/docs/1.0.0-beta.10/api/page/keyboard/"> Keyboard </a> </li> <li> <a href="/docs/1.0.0-beta.10/api/directive/keyboardAttach/"> keyboard-attach </a> </li> </ul> </li> </ul> <ul class="nav left-menu"> <li class="menu-title"> <a href="/docs/cli/">CLI</a> </li> </ul> <ul class="nav left-menu"> <li class="menu-title"> <a href="http://learn.ionicframework.com/">Learn Ionic</a> </li> </ul> <ul class="nav left-menu"> <li class="menu-title"> <a href="/docs/guide/">Guide</a> </li> </ul> <ul class="nav left-menu"> <li class="menu-title"> <a href="/docs/ionic-cli-faq/">FAQ</a> </li> </ul> <ul class="nav left-menu"> <li class="menu-title"> <a href="/docs/getting-help/">Getting Help</a> </li> </ul> <ul class="nav left-menu"> <li class="menu-title"> <a href="/docs/concepts/">Ionic Concepts</a> </li> </ul> </div> </div> <div class="col-md-10 col-sm-9 main-content"> <table class="table"> <tr> <th>Name</th> <th>Description</th> </tr> <tr> <td><a href="/docs/api/service/$ionicScrollDelegate/">$ionicScrollDelegate</a></td> <td><p>Delegate for controlling scrollViews (created by <a href="/docs/api/directive/ionContent/"><code>ionContent</code></a> and <a href="/docs/api/directive/ionScroll/"><code>ionScroll</code></a> directives).</p> </td> </tr> <tr> <td><a href="/docs/api/service/$ionicNavBarDelegate/">$ionicNavBarDelegate</a></td> <td><p>Delegate for controlling the <a href="/docs/api/directive/ionNavBar/"><code>ionNavBar</code></a> directive.</p> </td> </tr> <tr> <td><a href="/docs/api/service/$ionicSideMenuDelegate/">$ionicSideMenuDelegate</a></td> <td><p>Delegate for controlling the <a href="/docs/api/directive/ionSideMenus/"><code>ionSideMenus</code></a> directive.</p> </td> </tr> <tr> <td><a href="/docs/api/service/$ionicSlideBoxDelegate/">$ionicSlideBoxDelegate</a></td> <td><p>Delegate that controls the <a href="/docs/api/directive/ionSlideBox/"><code>ionSlideBox</code></a> directive.</p> </td> </tr> <tr> <td><a href="/docs/api/service/$ionicTabsDelegate/">$ionicTabsDelegate</a></td> <td><p>Delegate for controlling the <a href="/docs/api/directive/ionTabs/"><code>ionTabs</code></a> directive.</p> </td> </tr> <tr> <td><a href="/docs/api/service/$ionicActionSheet/">$ionicActionSheet</a></td> <td><p>The Action Sheet is a slide-up pane that lets the user choose from a set of options. Dangerous options are highlighted in red and made obvious.</p> </td> </tr> <tr> <td><a href="/docs/api/service/$ionicGesture/">$ionicGesture</a></td> <td><p>An angular service exposing ionic <a href="/docs/api/utility/ionic.EventController/"><code>ionic.EventController</code></a>&#39;s gestures.</p> </td> </tr> <tr> <td><a href="/docs/api/service/$ionicLoading/">$ionicLoading</a></td> <td><p>An overlay that can be used to indicate activity while blocking user interaction.</p> </td> </tr> <tr> <td><a href="/docs/api/service/$ionicModal/">$ionicModal</a></td> <td><p>The Modal is a content pane that can go over the user&#39;s main view temporarily. Usually used for making a choice or editing an item.</p> </td> </tr> <tr> <td><a href="/docs/api/service/$ionicPlatform/">$ionicPlatform</a></td> <td><p>An angular abstraction of <a href="/docs/api/utility/ionic.Platform/"><code>ionic.Platform</code></a>.</p> </td> </tr> <tr> <td><a href="/docs/api/service/$ionicPopup/">$ionicPopup</a></td> <td><p>The Ionic Popup service makes it easy to programatically create and show popup windows that require the user to respond in order to continue:</p> </td> </tr> </table> </div> </div> </div> <div class="pre-footer"> <div class="row ionic"> <div class="col-sm-6 col-a"> <h4> <a href="/getting-started/">Getting started <span class="icon ion-arrow-right-c"></span></a> </h4> <p> Learn more about how Ionic was built, why you should use it, and what's included. We'll cover the basics and help you get started from the ground up. </p> </div> <div class="col-sm-6 col-b"> <h4> <a href="/docs/">Documentation <span class="icon ion-arrow-right-c"></span></a> </h4> <p> What are you waiting for? Take a look and get coding! Our documentation covers all you need to know to get an app up and running in minutes. </p> </div> </div> </div> <footer class="footer"> <nav class="base-links"> <dl> <dt>Docs</dt> <dd><a href="http://ionicframework.com/docs/">Documentation</a></dd> <dd><a href="http://ionicframework.com/getting-started/">Getting Started</a></dd> <dd><a href="http://ionicframework.com/docs/overview/">Overview</a></dd> <dd><a href="http://ionicframework.com/docs/components/">Components</a></dd> <dd><a href="http://ionicframework.com/docs/api/">JavaScript</a></dd> <dd><a href="http://ionicframework.com/submit-issue/">Submit Issue</a></dd> </dl> <dl> <dt>Resources</dt> <dd><a href="http://learn.ionicframework.com/">Learn Ionic</a></dd> <dd><a href="http://ngcordova.com/">ngCordova</a></dd> <dd><a href="http://ionicons.com/">Ionicons</a></dd> <dd><a href="http://creator.ionic.io/">Creator</a></dd> <dd><a href="http://showcase.ionicframework.com/">Showcase</a></dd> <dd><a href="http://manning.com/wilken/?a_aid=ionicinactionben&a_bid=1f0a0e1d">The Ionic Book</a></dd> </dl> <dl> <dt>Contribute</dt> <dd><a href="http://forum.ionicframework.com/">Community Forum</a></dd> <dd><a href="http://webchat.freenode.net/?randomnick=1&amp;channels=%23ionic&amp;uio=d4">Ionic IRC</a></dd> <dd><a href="http://ionicframework.com/present-ionic/">Present Ionic</a></dd> <dd><a href="http://ionicframework.com/contribute/">Contribute</a></dd> <dd><a href="https://github.com/driftyco/ionic-learn/issues/new">Write for us</a></dd> <dd><a href="http://shop.ionic.io/">Ionic Shop</a></dd> </dl> <dl class="small-break"> <dt>About</dt> <dd><a href="http://blog.ionic.io/">Blog</a></dd> <dd><a href="http://ionic.io">Services</a></dd> <dd><a href="http://drifty.com">Company</a></dd> <dd><a href="https://s3.amazonaws.com/ionicframework.com/logo-pack.zip">Logo Pack</a></dd> <dd><a href="mailto:[email protected]">Contact</a></dd> <dd><a href="http://ionicframework.com/jobs/">Jobs</a></dd> </dl> <dl> <dt>Connect</dt> <dd><a href="https://twitter.com/IonicFramework">Twitter</a></dd> <dd><a href="https://github.com/driftyco/ionic">GitHub</a></dd> <dd><a href="https://www.facebook.com/ionicframework">Facebook</a></dd> <dd><a href="https://plus.google.com/b/112280728135675018538/+Ionicframework/posts">Google+</a></dd> <dd><a href="https://www.youtube.com/channel/UChYheBnVeCfhCmqZfCUdJQw">YouTube</a></dd> <dd><a href="https://twitter.com/ionitron">Ionitron</a></dd> </dl> </nav> <div class="newsletter row"> <div class="newsletter-container"> <div class="col-sm-7"> <div class="newsletter-text">Stay in the loop</div> <div class="sign-up">Sign up to receive emails for the latest updates, features, and news on the framework.</div> </div> <form action="http://codiqa.createsend.com/t/t/s/jytylh/" method="post" class="input-group col-sm-5"> <input id="fieldEmail" name="cm-jytylh-jytylh" class="form-control" type="email" placeholder="Email" required /> <span class="input-group-btn"> <button class="btn btn-default" type="submit">Subscribe</button> </span> </form> </div> </div> <div class="copy"> <div class="copy-container"> <p class="authors"> Code licensed under <a href="/docs/#license">MIT</a>. Docs under <a href="https://tldrlegal.com/license/apache-license-2.0-(apache-2.0)">Apache 2</a> <span>|</span> &copy; 2013-2015 <a href="http://drifty.com/">Drifty Co</a> </p> </div> </div> </footer> <script type="text/javascript"> var _sf_async_config = { uid: 54141, domain: 'ionicframework.com', useCanonical: true }; (function() { function loadChartbeat() { window._sf_endpt = (new Date()).getTime(); var e = document.createElement('script'); e.setAttribute('language', 'javascript'); e.setAttribute('type', 'text/javascript'); e.setAttribute('src','//static.chartbeat.com/js/chartbeat.js'); document.body.appendChild(e); }; var oldonload = window.onload; window.onload = (typeof window.onload != 'function') ? loadChartbeat : function() { oldonload(); loadChartbeat(); }; })(); </script> <script src="//netdna.bootstrapcdn.com/bootstrap/3.0.2/js/bootstrap.min.js"></script> <script src="/js/site.js?1"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/Cookies.js/0.4.0/cookies.min.js"></script> <script> $('.navbar .dropdown').on('show.bs.dropdown', function(e){ //$(this).find('.dropdown-menu').addClass('animated fadeInDown'); }); // ADD SLIDEUP ANIMATION TO DROPDOWN // $('.navbar .dropdown').on('hide.bs.dropdown', function(e){ //$(this).find('.dropdown-menu').first().stop(true, true).slideUp(200); //$(this).find('.dropdown-menu').removeClass('animated fadeInDown'); }); try { var d = new Date('2015-03-20 05:00:00 +0000'); var ts = d.getTime(); var cd = Cookies.get('_iondj'); if(cd) { cd = JSON.parse(atob(cd)); if(parseInt(cd.lp) < ts) { var bt = document.getElementById('blog-badge'); bt.style.display = 'block'; } cd.lp = ts; } else { var bt = document.getElementById('blog-badge'); bt.style.display = 'block'; cd = { lp: ts } } Cookies.set('_iondj', btoa(JSON.stringify(cd))); } catch(e) { } </script> <div id="fb-root"></div> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/all.js#xfbml=1"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> </body> </html>
martinjbaker/ionic-site
_site/docs/1.0.0-beta.10/api/ionic/service/index.html
HTML
apache-2.0
29,172
#!/usr/bin/env bash echo "Puppet6 Platform Detection and Installation" /usr/bin/wget -O - https://raw.githubusercontent.com/petems/puppet-install-shell/master/install_puppet_6_agent.sh | /bin/sh echo "Install R10k and Hiera-Eyaml" /opt/puppetlabs/puppet/bin/gem install r10k hiera-eyaml echo "Retrieve Puppetfile from puppet-maas repo" #/usr/bin/wget -O /etc/puppetlabs/code/environments/production/Puppetfile https://raw.githubusercontent.com/ppouliot/Puppetfile/master/Puppetfile /usr/bin/wget -O /etc/puppetlabs/code/environments/production/Puppetfile https://raw.githubusercontent.com/ppouliot/puppet-maas/master/Puppetfile echo "Run R10k on downloaded Puppetfile" cd /etc/puppetlabs/code/environments/production && /opt/puppetlabs/puppet/bin/r10k puppetfile install --verbose DEBUG2 /opt/puppetlabs/bin/puppet apply --debug --trace --verbose --modulepath=/etc/puppetlabs/code/environments/production/modules:/etc/puppetlabs/code/modules /etc/puppetlabs/code/environments/production/modules/maas/examples/init.pp
ppouliot/puppet-maas
files/scripts/bootstrap_puppet_to_maas.sh
Shell
apache-2.0
1,017
namespace TrelloToExcel.Trello { public class TextData { public Emoji3 emoji { get; set; } } }
ymotton/TrelloToExcel
TrelloToExcel/Trello/TextData.cs
C#
apache-2.0
117
def power_digit_sum(exponent): power_of_2 = str(2 ** exponent) return sum([int(x) for x in power_of_2])
plilja/project-euler
problem_16/power_digit_sum.py
Python
apache-2.0
111
# Copyright 2022 The Magenta Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Constants for music processing in Magenta.""" # Meter-related constants. DEFAULT_QUARTERS_PER_MINUTE = 120.0 DEFAULT_STEPS_PER_BAR = 16 # 4/4 music sampled at 4 steps per quarter note. DEFAULT_STEPS_PER_QUARTER = 4 # Default absolute quantization. DEFAULT_STEPS_PER_SECOND = 100 # Standard pulses per quarter. # https://en.wikipedia.org/wiki/Pulses_per_quarter_note STANDARD_PPQ = 220 # Special melody events. NUM_SPECIAL_MELODY_EVENTS = 2 MELODY_NOTE_OFF = -1 MELODY_NO_EVENT = -2 # Other melody-related constants. MIN_MELODY_EVENT = -2 MAX_MELODY_EVENT = 127 MIN_MIDI_PITCH = 0 # Inclusive. MAX_MIDI_PITCH = 127 # Inclusive. NUM_MIDI_PITCHES = MAX_MIDI_PITCH - MIN_MIDI_PITCH + 1 NOTES_PER_OCTAVE = 12 # Velocity-related constants. MIN_MIDI_VELOCITY = 1 # Inclusive. MAX_MIDI_VELOCITY = 127 # Inclusive. # Program-related constants. MIN_MIDI_PROGRAM = 0 MAX_MIDI_PROGRAM = 127 # MIDI programs that typically sound unpitched. UNPITCHED_PROGRAMS = ( list(range(96, 104)) + list(range(112, 120)) + list(range(120, 128))) # Chord symbol for "no chord". NO_CHORD = 'N.C.' # The indices of the pitch classes in a major scale. MAJOR_SCALE = [0, 2, 4, 5, 7, 9, 11] # NOTE_KEYS[note] = The major keys that note belongs to. # ex. NOTE_KEYS[0] lists all the major keys that contain the note C, # which are: # [0, 1, 3, 5, 7, 8, 10] # [C, C#, D#, F, G, G#, A#] # # 0 = C # 1 = C# # 2 = D # 3 = D# # 4 = E # 5 = F # 6 = F# # 7 = G # 8 = G# # 9 = A # 10 = A# # 11 = B # # NOTE_KEYS can be generated using the code below, but is explicitly declared # for readability: # NOTE_KEYS = [[j for j in range(12) if (i - j) % 12 in MAJOR_SCALE] # for i in range(12)] NOTE_KEYS = [ [0, 1, 3, 5, 7, 8, 10], [1, 2, 4, 6, 8, 9, 11], [0, 2, 3, 5, 7, 9, 10], [1, 3, 4, 6, 8, 10, 11], [0, 2, 4, 5, 7, 9, 11], [0, 1, 3, 5, 6, 8, 10], [1, 2, 4, 6, 7, 9, 11], [0, 2, 3, 5, 7, 8, 10], [1, 3, 4, 6, 8, 9, 11], [0, 2, 4, 5, 7, 9, 10], [1, 3, 5, 6, 8, 10, 11], [0, 2, 4, 6, 7, 9, 11] ]
magenta/note-seq
note_seq/constants.py
Python
apache-2.0
2,620
# Copyright 2018 PerfKitBenchmarker Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Module containing classes related to AWS CloudWatch Logs.""" import json from perfkitbenchmarker import resource from perfkitbenchmarker import vm_util from perfkitbenchmarker.providers.aws import util class LogGroup(resource.BaseResource): """Class representing a CloudWatch log group.""" def __init__(self, region, name, retention_in_days=7): super(LogGroup, self).__init__() self.region = region self.name = name self.retention_in_days = retention_in_days def _Create(self): """Create the log group.""" create_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'create-log-group', '--log-group-name', self.name ] vm_util.IssueCommand(create_cmd) def _Delete(self): """Delete the log group.""" delete_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'delete-log-group', '--log-group-name', self.name ] vm_util.IssueCommand(delete_cmd, raise_on_failure=False) def Exists(self): """Returns True if the log group exists.""" describe_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'describe-log-groups', '--log-group-name-prefix', self.name, '--no-paginate' ] stdout, _, _ = vm_util.IssueCommand(describe_cmd) log_groups = json.loads(stdout)['logGroups'] group = next((group for group in log_groups if group['logGroupName'] == self.name), None) return bool(group) def _PostCreate(self): """Set the retention policy.""" put_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'put-retention-policy', '--log-group-name', self.name, '--retention-in-days', str(self.retention_in_days) ] vm_util.IssueCommand(put_cmd) def GetLogs(region, stream_name, group_name, token=None): """Fetches the JSON formatted log stream starting at the token.""" get_cmd = util.AWS_PREFIX + [ '--region', region, 'logs', 'get-log-events', '--start-from-head', '--log-group-name', group_name, '--log-stream-name', stream_name, ] if token: get_cmd.extend(['--next-token', token]) stdout, _, _ = vm_util.IssueCommand(get_cmd) return json.loads(stdout) def GetLogStreamAsString(region, stream_name, log_group): """Returns the messages of the log stream as a string.""" log_lines = [] token = None events = [] while token is None or events: response = GetLogs(region, stream_name, log_group, token) events = response['events'] token = response['nextForwardToken'] for event in events: log_lines.append(event['message']) return '\n'.join(log_lines)
GoogleCloudPlatform/PerfKitBenchmarker
perfkitbenchmarker/providers/aws/aws_logs.py
Python
apache-2.0
3,293
package com.lyubenblagoev.postfixrest.security; import com.lyubenblagoev.postfixrest.entity.User; import com.lyubenblagoev.postfixrest.repository.UserRepository; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import java.util.Optional; @Service public class CustomUserDetailsService implements UserDetailsService { private final UserRepository userRepository; public CustomUserDetailsService(UserRepository userRepository) { this.userRepository = userRepository; } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { return userRepository.findByEmail(username) .map(u -> new UserPrincipal(u)) .orElseThrow(() -> new UsernameNotFoundException("No user found for " + username)); } }
lyubenblagoev/postfix-rest-server
src/main/java/com/lyubenblagoev/postfixrest/security/CustomUserDetailsService.java
Java
apache-2.0
1,026
/* * Copyright (c) 2021 Citrix Systems, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package network /** * Binding object which returns the resources bound to vrid_binding. */ type Vridbinding struct { /** * Integer value that uniquely identifies the VMAC address.<br/>Minimum value = 1<br/>Maximum value = 255 */ Id int `json:"id,omitempty"` }
citrix/terraform-provider-netscaler
vendor/github.com/citrix/adc-nitro-go/resource/config/network/vrid_binding.go
GO
apache-2.0
881
/* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "fmt" "io" "os" "strconv" "strings" "time" "github.com/spf13/cobra" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/cli-runtime/pkg/genericclioptions" "k8s.io/client-go/kubernetes" _ "k8s.io/client-go/plugin/pkg/client/auth" "k8s.io/klog" "k8s.io/kops/cmd/kops/util" api "k8s.io/kops/pkg/apis/kops" "k8s.io/kops/pkg/cloudinstances" "k8s.io/kops/pkg/featureflag" "k8s.io/kops/pkg/instancegroups" "k8s.io/kops/pkg/pretty" "k8s.io/kops/upup/pkg/fi/cloudup" "k8s.io/kops/util/pkg/tables" "k8s.io/kubernetes/pkg/kubectl/util/i18n" "k8s.io/kubernetes/pkg/kubectl/util/templates" ) var ( rollingupdateLong = pretty.LongDesc(i18n.T(` This command updates a kubernetes cluster to match the cloud and kops specifications. To perform a rolling update, you need to update the cloud resources first with the command ` + pretty.Bash("kops update cluster") + `. If rolling-update does not report that the cluster needs to be rolled, you can force the cluster to be rolled with the force flag. Rolling update drains and validates the cluster by default. A cluster is deemed validated when all required nodes are running and all pods in the kube-system namespace are operational. When a node is deleted, rolling-update sleeps the interval for the node type, and then tries for the same period of time for the cluster to be validated. For instance, setting --master-interval=3m causes rolling-update to wait for 3 minutes after a master is rolled, and another 3 minutes for the cluster to stabilize and pass validation. Note: terraform users will need to run all of the following commands from the same directory ` + pretty.Bash("kops update cluster --target=terraform") + ` then ` + pretty.Bash("terraform plan") + ` then ` + pretty.Bash("terraform apply") + ` prior to running ` + pretty.Bash("kops rolling-update cluster") + `.`)) rollingupdateExample = templates.Examples(i18n.T(` # Preview a rolling-update. kops rolling-update cluster # Roll the currently selected kops cluster with defaults. # Nodes will be drained and the cluster will be validated between node replacement. kops rolling-update cluster --yes # Roll the k8s-cluster.example.com kops cluster, # do not fail if the cluster does not validate, # wait 8 min to create new node, and wait at least # 8 min to validate the cluster. kops rolling-update cluster k8s-cluster.example.com --yes \ --fail-on-validate-error="false" \ --master-interval=8m \ --node-interval=8m # Roll the k8s-cluster.example.com kops cluster, # do not validate the cluster because of the cloudonly flag. # Force the entire cluster to roll, even if rolling update # reports that the cluster does not need to be rolled. kops rolling-update cluster k8s-cluster.example.com --yes \ --cloudonly \ --force # Roll the k8s-cluster.example.com kops cluster, # only roll the node instancegroup, # use the new drain and validate functionality. kops rolling-update cluster k8s-cluster.example.com --yes \ --fail-on-validate-error="false" \ --node-interval 8m \ --instance-group nodes `)) rollingupdateShort = i18n.T(`Rolling update a cluster.`) ) // RollingUpdateOptions is the command Object for a Rolling Update. type RollingUpdateOptions struct { Yes bool Force bool CloudOnly bool // The following two variables are when kops is validating a cluster // during a rolling update. // FailOnDrainError fail rolling-update if drain errors. FailOnDrainError bool // FailOnValidate fail the cluster rolling-update when the cluster // does not validate, after a validation period. FailOnValidate bool // PostDrainDelay is the duration of a pause after a drain operation PostDrainDelay time.Duration // ValidationTimeout is the timeout for validation to succeed after the drain and pause ValidationTimeout time.Duration // MasterInterval is the minimum time to wait after stopping a master node. This does not include drain and validate time. MasterInterval time.Duration // NodeInterval is the minimum time to wait after stopping a (non-master) node. This does not include drain and validate time. NodeInterval time.Duration // BastionInterval is the minimum time to wait after stopping a bastion. This does not include drain and validate time. BastionInterval time.Duration // Interactive rolling-update prompts user to continue after each instances is updated. Interactive bool ClusterName string // InstanceGroups is the list of instance groups to rolling-update; // if not specified, all instance groups will be updated InstanceGroups []string // InstanceGroupRoles is the list of roles we should rolling-update // if not specified, all instance groups will be updated InstanceGroupRoles []string } func (o *RollingUpdateOptions) InitDefaults() { o.Yes = false o.Force = false o.CloudOnly = false o.FailOnDrainError = false o.FailOnValidate = true o.MasterInterval = 15 * time.Second o.NodeInterval = 15 * time.Second o.BastionInterval = 15 * time.Second o.Interactive = false o.PostDrainDelay = 5 * time.Second o.ValidationTimeout = 15 * time.Minute } func NewCmdRollingUpdateCluster(f *util.Factory, out io.Writer) *cobra.Command { var options RollingUpdateOptions options.InitDefaults() cmd := &cobra.Command{ Use: "cluster", Short: rollingupdateShort, Long: rollingupdateLong, Example: rollingupdateExample, } cmd.Flags().BoolVarP(&options.Yes, "yes", "y", options.Yes, "Perform rolling update immediately, without --yes rolling-update executes a dry-run") cmd.Flags().BoolVar(&options.Force, "force", options.Force, "Force rolling update, even if no changes") cmd.Flags().BoolVar(&options.CloudOnly, "cloudonly", options.CloudOnly, "Perform rolling update without confirming progress with k8s") cmd.Flags().DurationVar(&options.ValidationTimeout, "validation-timeout", options.ValidationTimeout, "Maximum time to wait for a cluster to validate") cmd.Flags().DurationVar(&options.MasterInterval, "master-interval", options.MasterInterval, "Time to wait between restarting masters") cmd.Flags().DurationVar(&options.NodeInterval, "node-interval", options.NodeInterval, "Time to wait between restarting nodes") cmd.Flags().DurationVar(&options.BastionInterval, "bastion-interval", options.BastionInterval, "Time to wait between restarting bastions") cmd.Flags().DurationVar(&options.PostDrainDelay, "post-drain-delay", options.PostDrainDelay, "Time to wait after draining each node") cmd.Flags().BoolVarP(&options.Interactive, "interactive", "i", options.Interactive, "Prompt to continue after each instance is updated") cmd.Flags().StringSliceVar(&options.InstanceGroups, "instance-group", options.InstanceGroups, "List of instance groups to update (defaults to all if not specified)") cmd.Flags().StringSliceVar(&options.InstanceGroupRoles, "instance-group-roles", options.InstanceGroupRoles, "If specified, only instance groups of the specified role will be updated (e.g. Master,Node,Bastion)") if featureflag.DrainAndValidateRollingUpdate.Enabled() { cmd.Flags().BoolVar(&options.FailOnDrainError, "fail-on-drain-error", true, "The rolling-update will fail if draining a node fails.") cmd.Flags().BoolVar(&options.FailOnValidate, "fail-on-validate-error", true, "The rolling-update will fail if the cluster fails to validate.") } cmd.Run = func(cmd *cobra.Command, args []string) { err := rootCommand.ProcessArgs(args) if err != nil { exitWithError(err) return } clusterName := rootCommand.ClusterName() if clusterName == "" { exitWithError(fmt.Errorf("--name is required")) return } options.ClusterName = clusterName err = RunRollingUpdateCluster(f, os.Stdout, &options) if err != nil { exitWithError(err) return } } return cmd } func RunRollingUpdateCluster(f *util.Factory, out io.Writer, options *RollingUpdateOptions) error { clientset, err := f.Clientset() if err != nil { return err } cluster, err := GetCluster(f, options.ClusterName) if err != nil { return err } contextName := cluster.ObjectMeta.Name clientGetter := genericclioptions.NewConfigFlags() clientGetter.Context = &contextName config, err := clientGetter.ToRESTConfig() if err != nil { return fmt.Errorf("cannot load kubecfg settings for %q: %v", contextName, err) } var nodes []v1.Node var k8sClient kubernetes.Interface if !options.CloudOnly { k8sClient, err = kubernetes.NewForConfig(config) if err != nil { return fmt.Errorf("cannot build kube client for %q: %v", contextName, err) } nodeList, err := k8sClient.CoreV1().Nodes().List(metav1.ListOptions{}) if err != nil { fmt.Fprintf(os.Stderr, "Unable to reach the kubernetes API.\n") fmt.Fprintf(os.Stderr, "Use --cloudonly to do a rolling-update without confirming progress with the k8s API\n\n") return fmt.Errorf("error listing nodes in cluster: %v", err) } if nodeList != nil { nodes = nodeList.Items } } list, err := clientset.InstanceGroupsFor(cluster).List(metav1.ListOptions{}) if err != nil { return err } var instanceGroups []*api.InstanceGroup for i := range list.Items { instanceGroups = append(instanceGroups, &list.Items[i]) } warnUnmatched := true if len(options.InstanceGroups) != 0 { var filtered []*api.InstanceGroup for _, instanceGroupName := range options.InstanceGroups { var found *api.InstanceGroup for _, ig := range instanceGroups { if ig.ObjectMeta.Name == instanceGroupName { found = ig break } } if found == nil { return fmt.Errorf("InstanceGroup %q not found", instanceGroupName) } filtered = append(filtered, found) } instanceGroups = filtered // Don't warn if we find more ASGs than IGs warnUnmatched = false } if len(options.InstanceGroupRoles) != 0 { var filtered []*api.InstanceGroup for _, ig := range instanceGroups { for _, role := range options.InstanceGroupRoles { if ig.Spec.Role == api.InstanceGroupRole(strings.Title(strings.ToLower(role))) { filtered = append(filtered, ig) continue } } } instanceGroups = filtered // Don't warn if we find more ASGs than IGs warnUnmatched = false } cloud, err := cloudup.BuildCloud(cluster) if err != nil { return err } groups, err := cloud.GetCloudGroups(cluster, instanceGroups, warnUnmatched, nodes) if err != nil { return err } { t := &tables.Table{} t.AddColumn("NAME", func(r *cloudinstances.CloudInstanceGroup) string { return r.InstanceGroup.ObjectMeta.Name }) t.AddColumn("STATUS", func(r *cloudinstances.CloudInstanceGroup) string { return r.Status() }) t.AddColumn("NEEDUPDATE", func(r *cloudinstances.CloudInstanceGroup) string { return strconv.Itoa(len(r.NeedUpdate)) }) t.AddColumn("READY", func(r *cloudinstances.CloudInstanceGroup) string { return strconv.Itoa(len(r.Ready)) }) t.AddColumn("MIN", func(r *cloudinstances.CloudInstanceGroup) string { return strconv.Itoa(r.MinSize) }) t.AddColumn("MAX", func(r *cloudinstances.CloudInstanceGroup) string { return strconv.Itoa(r.MaxSize) }) t.AddColumn("NODES", func(r *cloudinstances.CloudInstanceGroup) string { var nodes []*v1.Node for _, i := range r.Ready { if i.Node != nil { nodes = append(nodes, i.Node) } } for _, i := range r.NeedUpdate { if i.Node != nil { nodes = append(nodes, i.Node) } } return strconv.Itoa(len(nodes)) }) var l []*cloudinstances.CloudInstanceGroup for _, v := range groups { l = append(l, v) } columns := []string{"NAME", "STATUS", "NEEDUPDATE", "READY", "MIN", "MAX"} if !options.CloudOnly { columns = append(columns, "NODES") } err := t.Render(l, out, columns...) if err != nil { return err } } needUpdate := false for _, group := range groups { if len(group.NeedUpdate) != 0 { needUpdate = true } } if !needUpdate && !options.Force { fmt.Printf("\nNo rolling-update required.\n") return nil } if !options.Yes { fmt.Printf("\nMust specify --yes to rolling-update.\n") return nil } if featureflag.DrainAndValidateRollingUpdate.Enabled() { klog.V(2).Infof("Rolling update with drain and validate enabled.") } d := &instancegroups.RollingUpdateCluster{ MasterInterval: options.MasterInterval, NodeInterval: options.NodeInterval, BastionInterval: options.BastionInterval, Interactive: options.Interactive, Force: options.Force, Cloud: cloud, K8sClient: k8sClient, ClientGetter: clientGetter, FailOnDrainError: options.FailOnDrainError, FailOnValidate: options.FailOnValidate, CloudOnly: options.CloudOnly, ClusterName: options.ClusterName, PostDrainDelay: options.PostDrainDelay, ValidationTimeout: options.ValidationTimeout, } return d.RollingUpdate(groups, cluster, list) }
gambol99/kops
cmd/kops/rollingupdatecluster.go
GO
apache-2.0
13,554
"""Auto-generated file, do not edit by hand. BM metadata""" from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata PHONE_METADATA_BM = PhoneMetadata(id='BM', country_code=1, international_prefix='011', general_desc=PhoneNumberDesc(national_number_pattern='(?:441|[58]\\d\\d|900)\\d{7}', possible_length=(10,), possible_length_local_only=(7,)), fixed_line=PhoneNumberDesc(national_number_pattern='441(?:[46]\\d\\d|5(?:4\\d|60|89))\\d{4}', example_number='4414123456', possible_length=(10,), possible_length_local_only=(7,)), mobile=PhoneNumberDesc(national_number_pattern='441(?:[2378]\\d|5[0-39])\\d{5}', example_number='4413701234', possible_length=(10,), possible_length_local_only=(7,)), toll_free=PhoneNumberDesc(national_number_pattern='8(?:00|33|44|55|66|77|88)[2-9]\\d{6}', example_number='8002123456', possible_length=(10,)), premium_rate=PhoneNumberDesc(national_number_pattern='900[2-9]\\d{6}', example_number='9002123456', possible_length=(10,)), personal_number=PhoneNumberDesc(national_number_pattern='52(?:3(?:[2-46-9][02-9]\\d|5(?:[02-46-9]\\d|5[0-46-9]))|4(?:[2-478][02-9]\\d|5(?:[034]\\d|2[024-9]|5[0-46-9])|6(?:0[1-9]|[2-9]\\d)|9(?:[05-9]\\d|2[0-5]|49)))\\d{4}|52[34][2-9]1[02-9]\\d{4}|5(?:00|2[12]|33|44|66|77|88)[2-9]\\d{6}', example_number='5002345678', possible_length=(10,)), national_prefix='1', national_prefix_for_parsing='1|([2-8]\\d{6})$', national_prefix_transform_rule='441\\1', leading_digits='441', mobile_number_portable_region=True)
daviddrysdale/python-phonenumbers
python/phonenumbers/data/region_BM.py
Python
apache-2.0
1,530
<head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>{% if page.title %}{{ page.title }}{% else %}{{ site.title }}{% endif %}</title> <meta name="viewport" content="width=device-width"> <meta name="description" content="{{ site.description }}"> <link rel="canonical" href="{{ page.url | replace:'index.html','' | prepend: site.baseurl | prepend: site.url }}"> <!-- Custom CSS & Bootstrap Core CSS - Uses Bootswatch Flatly Theme: http://bootswatch.com/flatly/ --> <link rel="stylesheet" href="{{ "/style.css" | prepend: site.baseurl }}"> <!-- Custom Fonts --> <link rel="stylesheet" href="{{ "/css/font-awesome/css/font-awesome.min.css" | prepend: site.baseurl }}"> <link href="//fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" rel="stylesheet" type="text/css"> <link href="//fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head>
Shirotobi/oretachi.github.io
_includes/head.html
HTML
apache-2.0
1,365
/******************************************************************************* * Copyright (c) 2012, 2015 Pivotal Software, Inc. * * All rights reserved. This program and the accompanying materials * are made available under the terms of 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. * * Contributors: * Pivotal Software, Inc. - initial API and implementation ********************************************************************************/ package cn.dockerfoundry.ide.eclipse.server.core.internal; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import org.cloudfoundry.client.lib.domain.CloudService; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.wst.server.core.IModule; import cn.dockerfoundry.ide.eclipse.server.core.internal.application.ModuleChangeEvent; import cn.dockerfoundry.ide.eclipse.server.core.internal.client.CloudRefreshEvent; /** * Fires server refresh events. Only one handler is active per workbench runtime * session. * */ public class ServerEventHandler { private static ServerEventHandler handler; public static ServerEventHandler getDefault() { if (handler == null) { handler = new ServerEventHandler(); } return handler; } private final List<CloudServerListener> applicationListeners = new CopyOnWriteArrayList<CloudServerListener>(); public synchronized void addServerListener(CloudServerListener listener) { if (listener != null && !applicationListeners.contains(listener)) { applicationListeners.add(listener); } } public synchronized void removeServerListener(CloudServerListener listener) { applicationListeners.remove(listener); } public void fireServicesUpdated(DockerFoundryServer server, List<DockerApplicationService> services) { fireServerEvent(new CloudRefreshEvent(server, null, CloudServerEvent.EVENT_UPDATE_SERVICES, services)); } public void firePasswordUpdated(DockerFoundryServer server) { fireServerEvent(new CloudServerEvent(server, CloudServerEvent.EVENT_UPDATE_PASSWORD)); } public void fireServerRefreshed(DockerFoundryServer server) { fireServerEvent(new CloudServerEvent(server, CloudServerEvent.EVENT_SERVER_REFRESHED)); } public void fireAppInstancesChanged(DockerFoundryServer server, IModule module) { fireServerEvent(new ModuleChangeEvent(server, CloudServerEvent.EVENT_INSTANCES_UPDATED, module, Status.OK_STATUS)); } public void fireApplicationRefreshed(DockerFoundryServer server, IModule module) { fireServerEvent(new ModuleChangeEvent(server, CloudServerEvent.EVENT_APPLICATION_REFRESHED, module, Status.OK_STATUS)); } public void fireAppDeploymentChanged(DockerFoundryServer server, IModule module) { fireServerEvent(new ModuleChangeEvent(server, CloudServerEvent.EVENT_APP_DEPLOYMENT_CHANGED, module, Status.OK_STATUS)); } public void fireError(DockerFoundryServer server, IModule module, IStatus status) { fireServerEvent(new ModuleChangeEvent(server, CloudServerEvent.EVENT_CLOUD_OP_ERROR, module, status)); } public synchronized void fireServerEvent(CloudServerEvent event) { CloudServerListener[] listeners = applicationListeners.toArray(new CloudServerListener[0]); for (CloudServerListener listener : listeners) { listener.serverChanged(event); } } }
osswangxining/dockerfoundry
cn.dockerfoundry.ide.eclipse.server.core/src/cn/dockerfoundry/ide/eclipse/server/core/internal/ServerEventHandler.java
Java
apache-2.0
3,808
# AUTOGENERATED FILE FROM balenalib/artik530-debian:buster-run RUN apt-get update \ && apt-get install -y --no-install-recommends \ ca-certificates \ curl \ \ # .NET Core dependencies libc6 \ libgcc1 \ libgssapi-krb5-2 \ libicu63 \ libssl1.1 \ libstdc++6 \ zlib1g \ && rm -rf /var/lib/apt/lists/* # Configure web servers to bind to port 80 when present ENV ASPNETCORE_URLS=http://+:80 \ # Enable detection of running in a container DOTNET_RUNNING_IN_CONTAINER=true # Install .NET Core ENV DOTNET_VERSION 6.0.0 RUN curl -SL --output dotnet.tar.gz "https://dotnetcli.blob.core.windows.net/dotnet/Runtime/$DOTNET_VERSION/dotnet-runtime-$DOTNET_VERSION-linux-arm.tar.gz" \ && dotnet_sha512='575037f2e164deaf3bcdd82f7b3f2b5a5784547c5bad4070375c00373722265401b88a81695b919f92ca176f21c1bdf1716f8fce16ab3d301ae666daa8cae750' \ && echo "$dotnet_sha512 dotnet.tar.gz" | sha512sum -c - \ && mkdir -p /usr/share/dotnet \ && tar -zxf dotnet.tar.gz -C /usr/share/dotnet \ && rm dotnet.tar.gz \ && ln -s /usr/share/dotnet/dotnet /usr/bin/dotnet CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/44e597e40f2010cdde15b3ba1e397aea3a5c5271/scripts/assets/tests/[email protected]" \ && echo "Running test-stack@dotnet" \ && chmod +x [email protected] \ && bash [email protected] \ && rm -rf [email protected] RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Debian Buster \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \ndotnet 6.0-runtime \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
resin-io-library/base-images
balena-base-images/dotnet/artik530/debian/buster/6.0-runtime/run/Dockerfile
Dockerfile
apache-2.0
2,521
# AUTOGENERATED FILE FROM balenalib/jetson-xavier-nx-devkit-seeed-2mic-hat-fedora:33-build ENV NODE_VERSION 14.18.3 ENV YARN_VERSION 1.22.4 RUN for key in \ 6A010C5166006599AA17F08146C2130DFD2497F5 \ ; do \ gpg --keyserver pgp.mit.edu --recv-keys "$key" || \ gpg --keyserver keyserver.pgp.com --recv-keys "$key" || \ gpg --keyserver keyserver.ubuntu.com --recv-keys "$key" ; \ done \ && curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-arm64.tar.gz" \ && echo "2d071ca1bc1d0ea1eb259e79b81ebb4387237b2f77b3cf616806534e0030eaa8 node-v$NODE_VERSION-linux-arm64.tar.gz" | sha256sum -c - \ && tar -xzf "node-v$NODE_VERSION-linux-arm64.tar.gz" -C /usr/local --strip-components=1 \ && rm "node-v$NODE_VERSION-linux-arm64.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \ && gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && mkdir -p /opt/yarn \ && tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \ && rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && npm config set unsafe-perm true -g --unsafe-perm \ && rm -rf /tmp/* CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/[email protected]" \ && echo "Running test-stack@node" \ && chmod +x [email protected] \ && bash [email protected] \ && rm -rf [email protected] RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Fedora 33 \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v14.18.3, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo $'#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
resin-io-library/base-images
balena-base-images/node/jetson-xavier-nx-devkit-seeed-2mic-hat/fedora/33/14.18.3/build/Dockerfile
Dockerfile
apache-2.0
2,775
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #pragma once #include <aws/codecommit/CodeCommit_EXPORTS.h> #include <aws/codecommit/CodeCommitRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace CodeCommit { namespace Model { /** */ class AWS_CODECOMMIT_API ListTagsForResourceRequest : public CodeCommitRequest { public: ListTagsForResourceRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "ListTagsForResource"; } Aws::String SerializePayload() const override; Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override; /** * <p>The Amazon Resource Name (ARN) of the resource for which you want to get * information about tags, if any.</p> */ inline const Aws::String& GetResourceArn() const{ return m_resourceArn; } /** * <p>The Amazon Resource Name (ARN) of the resource for which you want to get * information about tags, if any.</p> */ inline bool ResourceArnHasBeenSet() const { return m_resourceArnHasBeenSet; } /** * <p>The Amazon Resource Name (ARN) of the resource for which you want to get * information about tags, if any.</p> */ inline void SetResourceArn(const Aws::String& value) { m_resourceArnHasBeenSet = true; m_resourceArn = value; } /** * <p>The Amazon Resource Name (ARN) of the resource for which you want to get * information about tags, if any.</p> */ inline void SetResourceArn(Aws::String&& value) { m_resourceArnHasBeenSet = true; m_resourceArn = std::move(value); } /** * <p>The Amazon Resource Name (ARN) of the resource for which you want to get * information about tags, if any.</p> */ inline void SetResourceArn(const char* value) { m_resourceArnHasBeenSet = true; m_resourceArn.assign(value); } /** * <p>The Amazon Resource Name (ARN) of the resource for which you want to get * information about tags, if any.</p> */ inline ListTagsForResourceRequest& WithResourceArn(const Aws::String& value) { SetResourceArn(value); return *this;} /** * <p>The Amazon Resource Name (ARN) of the resource for which you want to get * information about tags, if any.</p> */ inline ListTagsForResourceRequest& WithResourceArn(Aws::String&& value) { SetResourceArn(std::move(value)); return *this;} /** * <p>The Amazon Resource Name (ARN) of the resource for which you want to get * information about tags, if any.</p> */ inline ListTagsForResourceRequest& WithResourceArn(const char* value) { SetResourceArn(value); return *this;} /** * <p>An enumeration token that, when provided in a request, returns the next batch * of the results.</p> */ inline const Aws::String& GetNextToken() const{ return m_nextToken; } /** * <p>An enumeration token that, when provided in a request, returns the next batch * of the results.</p> */ inline bool NextTokenHasBeenSet() const { return m_nextTokenHasBeenSet; } /** * <p>An enumeration token that, when provided in a request, returns the next batch * of the results.</p> */ inline void SetNextToken(const Aws::String& value) { m_nextTokenHasBeenSet = true; m_nextToken = value; } /** * <p>An enumeration token that, when provided in a request, returns the next batch * of the results.</p> */ inline void SetNextToken(Aws::String&& value) { m_nextTokenHasBeenSet = true; m_nextToken = std::move(value); } /** * <p>An enumeration token that, when provided in a request, returns the next batch * of the results.</p> */ inline void SetNextToken(const char* value) { m_nextTokenHasBeenSet = true; m_nextToken.assign(value); } /** * <p>An enumeration token that, when provided in a request, returns the next batch * of the results.</p> */ inline ListTagsForResourceRequest& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;} /** * <p>An enumeration token that, when provided in a request, returns the next batch * of the results.</p> */ inline ListTagsForResourceRequest& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;} /** * <p>An enumeration token that, when provided in a request, returns the next batch * of the results.</p> */ inline ListTagsForResourceRequest& WithNextToken(const char* value) { SetNextToken(value); return *this;} private: Aws::String m_resourceArn; bool m_resourceArnHasBeenSet; Aws::String m_nextToken; bool m_nextTokenHasBeenSet; }; } // namespace Model } // namespace CodeCommit } // namespace Aws
cedral/aws-sdk-cpp
aws-cpp-sdk-codecommit/include/aws/codecommit/model/ListTagsForResourceRequest.h
C
apache-2.0
5,662
<?php /** * MyBB 1.6 Spanish Language Pack * Copyright 2010 MyBB Group, All Rights Reserved * * $Id: report.lang.php 5016 2010-08-10 12:32:33Z Anio_pke $ */ $l['report_post'] = "Reportar mensaje"; $l['report_to_mod'] = "Reporta este mensaje a un moderador"; $l['only_report'] = "Solo debes reportar mensajes que sean spam, de publicidad, o abusivos."; $l['report_reason'] = "Tu razón para reportar este mensaje:"; $l['thank_you'] = "Gracias."; $l['post_reported'] = "El mensaje se ha reportado correctamente. Ya puedes cerrar la ventana."; $l['report_error'] = "Error"; $l['no_reason'] = "No puedes reportar un mensaje sin especificar la razón del reporte."; $l['go_back'] = "Volver"; $l['close_window'] = "Cerrar ventana"; ?>
Flauschbaellchen/florensia-base
forum/inc/languages/espanol/report.lang.php
PHP
apache-2.0
755
# Laboulbenia neoguineensis Speg. SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Laboulbenia neoguineensis Speg. ### Remarks null
mdoering/backbone
life/Fungi/Ascomycota/Laboulbeniomycetes/Laboulbeniales/Laboulbeniaceae/Laboulbenia/Laboulbenia neoguineensis/README.md
Markdown
apache-2.0
191
<html dir="LTR"> <head> <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" /> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" /> <title>BasicConfigurator.Configure Method ()</title> <xml> </xml> <link rel="stylesheet" type="text/css" href="MSDN.css" /> </head> <body id="bodyID" class="dtBODY"> <div id="nsbanner"> <div id="bannerrow1"> <table class="bannerparthead" cellspacing="0"> <tr id="hdr"> <td class="runninghead">Apache log4net™ SDK Documentation - Microsoft .NET Framework 4.0</td> <td class="product"> </td> </tr> </table> </div> <div id="TitleRow"> <h1 class="dtH1">BasicConfigurator.Configure Method ()</h1> </div> </div> <div id="nstext"> <p> Initializes the log4net system with a default configuration. </p> <div class="syntax"> <span class="lang">[Visual Basic]</span> <br />Overloads Public Shared Function Configure() As <a href="ms-help://MS.NETFrameworkSDKv1.1/cpref/html/frlrfSystemCollectionsICollectionClassTopic.htm">ICollection</a></div> <div class="syntax"> <span class="lang">[C#]</span> <br />public static <a href="ms-help://MS.NETFrameworkSDKv1.1/cpref/html/frlrfSystemCollectionsICollectionClassTopic.htm">ICollection</a> Configure();</div> <h4 class="dtH4">Remarks</h4> <p> Initializes the log4net logging system using a <a href="log4net.Appender.ConsoleAppender.html">ConsoleAppender</a> that will write to <code>Console.Out</code>. The log messages are formatted using the <a href="log4net.Layout.PatternLayout.html">PatternLayout</a> layout object with the <a href="log4net.Layout.PatternLayout.DetailConversionPattern.html">DetailConversionPattern</a> layout style. </p> <h4 class="dtH4">See Also</h4><p><a href="log4net.Config.BasicConfigurator.html">BasicConfigurator Class</a> | <a href="log4net.Config.html">log4net.Config Namespace</a> | <a href="log4net.Config.BasicConfigurator.Configure_overloads.html">BasicConfigurator.Configure Overload List</a></p><object type="application/x-oleobject" classid="clsid:1e2a7bd0-dab9-11d0-b93a-00c04fc99f9e" viewastext="true" style="display: none;"><param name="Keyword" value="Configure method"></param><param name="Keyword" value="Configure method, BasicConfigurator class"></param><param name="Keyword" value="BasicConfigurator.Configure method"></param></object><hr /><div id="footer"><a href='http://logging.apache.org/log4net/'>Copyright 2004-2013 The Apache Software Foundation.</a><br></br>Apache log4net, Apache and log4net are trademarks of The Apache Software Foundation.</div></div> </body> </html>
gersonkurz/manualisator
manualisator/log4net-1.2.13/doc/release/sdk/log4net.Config.BasicConfigurator.Configure_overload_1.html
HTML
apache-2.0
2,814
/** * @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ // This file can be replaced during build by using the `fileReplacements` array. // `ng build --prod` replaces `environment.ts` with `environment.prod.ts`. // The list of file replacements can be found in `angular.json`. import { version } from '../../../../package.json'; export const environment = { production: false, interactiveVisualizerUrl: `https://storage.googleapis.com/interactive_visualizer/${version}/index.html`, models: [ { displayName: 'Birds V1', description: 'AIY natural world insects classification model', type: 'image classification', metadataUrl: 'https://storage.googleapis.com/tfhub-visualizers/google/aiy/vision/classifier/birds_V1/1/metadata.json', }, { displayName: 'Insects V1', description: 'AIY natural world birds quantized classification model', type: 'image classification', metadataUrl: 'https://storage.googleapis.com/tfhub-visualizers/google/aiy/vision/classifier/insects_V1/1/metadata.json', }, { displayName: 'Mobile Object Localizer V1', description: 'Mobile model to localize objects in an image', type: 'object detection', metadataUrl: 'https://storage.googleapis.com/tfhub-visualizers/google/object_detection/mobile_object_localizer_v1/1/metadata.json', }, ], }; /* * For easier debugging in development mode, you can import the following file * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`. * * This import should be commented out in production mode because it will have a negative impact * on performance if an error is thrown. */ // import 'zone.js/dist/zone-error'; // Included with Angular CLI.
tensorflow/tfjs-examples
interactive-visualizers/projects/playground/src/environments/environment.ts
TypeScript
apache-2.0
2,403
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Linq; using System.Text; using System.Diagnostics; namespace MT5LiquidityIndicator.Net.Settings { [DisplayName("Line Settings")] public class LineSettings { #region contruction public LineSettings() { this.Volume = 0; this.m_bidColor = Color.Black; this.m_askColor = Color.Black; } internal LineSettings(LineSettings settings) { this.Volume = settings.Volume; this.m_bidColor = settings.m_bidColor; this.m_askColor = settings.m_askColor; } internal LineSettings(double volume, Color bidColor, Color askColor) { this.Volume = volume; this.m_bidColor = bidColor; this.m_askColor = askColor; } #endregion #region properties [DefaultValue(1)] public double Volume { get { return m_volume; } set { if ((value < m_minVolume) || (value > m_maxVolume)) { string message = string.Format("Volum can be from {0} to {1}", m_minVolume, m_maxVolume); throw new ArgumentOutOfRangeException("value", value, message); } m_volume = value; } } [DisplayName("Bid Color")] [DefaultValue(typeof(Color), "Black")] public Color BidColor { get { return m_bidColor; } set { m_bidColor = NormalizeColor(value); } } [DisplayName("Ask Color")] [DefaultValue(typeof(Color), "Black")] public Color AskColor { get { return m_askColor; } set { m_askColor = NormalizeColor(value); } } #endregion #region private members private static Color NormalizeColor(Color value) { if (255 == value.A) { return value; } Color result = Color.FromArgb(255, value.R, value.G, value.B); return result; } #endregion #region overrode methods public override string ToString() { string result = string.Format("Volume = {0}", this.Volume); return result; } #endregion #region members private double m_volume; private const double m_minVolume = 0; private const double m_maxVolume = 10000; private Color m_bidColor; private Color m_askColor; #endregion } }
marmysh/MT5-Liquidity-Indicator
Source/MT5LiquidityIndicator/MT5LiquidityIndicator.Net/Settings/LineSettings.cs
C#
apache-2.0
2,168
/* * Copyright 2016 Bjoern Bilger * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jrestless.core.container; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response.Status; import org.glassfish.jersey.server.ContainerResponse; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import com.jrestless.core.container.JRestlessHandlerContainer.JRestlessContainerResponse; import com.jrestless.core.container.JRestlessHandlerContainer.JRestlessContainerResponseWriter; import com.jrestless.core.container.io.JRestlessResponseWriter; public class JRestlessContainerResponseWriterTest { private JRestlessContainerResponseWriter containerResponseWriter; private JRestlessContainerResponse response; @BeforeEach public void setup() { JRestlessResponseWriter responseWriter = mock(JRestlessResponseWriter.class); when(responseWriter.getEntityOutputStream()).thenReturn(new ByteArrayOutputStream()); response = spy(new JRestlessContainerResponse(responseWriter)); containerResponseWriter = new JRestlessContainerResponseWriter(response); } @Test public void commit_ResponseNotYetClosed_ShouldCloseResponse() { containerResponseWriter.commit(); verify(response, times(1)).close(); } @Test public void writeResponseStatusAndHeaders_ContextHeaderAndStatusGiven_ShouldUpdateResponseStatusAndHeaders() { MultivaluedMap<String, String> actualHeaders = new MultivaluedHashMap<>(); actualHeaders.add("header0", "value0_0"); actualHeaders.add("header0", "value0_1"); actualHeaders.add("header1", "value1_0"); MultivaluedMap<String, String> expectedHeaders = new MultivaluedHashMap<>(); expectedHeaders.add("header0", "value0_0"); expectedHeaders.add("header0", "value0_1"); expectedHeaders.add("header1", "value1_0"); ContainerResponse context = mock(ContainerResponse.class); when(context.getStatusInfo()).thenReturn(Status.CONFLICT); when(context.getStringHeaders()).thenReturn(actualHeaders); containerResponseWriter.writeResponseStatusAndHeaders(-1, context); assertEquals(Status.CONFLICT, response.getStatusType()); assertEquals(expectedHeaders, response.getHeaders()); } @Test public void writeResponseStatusAndHeaders_ShouldReturnEntityOutputStreamOfResponse() { ContainerResponse context = mock(ContainerResponse.class); when(context.getStringHeaders()).thenReturn(new MultivaluedHashMap<>()); when(context.getStatusInfo()).thenReturn(Status.OK); OutputStream entityOutputStream = containerResponseWriter.writeResponseStatusAndHeaders(-1, context); assertSame(response.getEntityOutputStream(), entityOutputStream); } @Test public void failure_ResponseNotYetCommitted_ShouldSetInternalServerErrorStatusOnFail() { ContainerResponse context = mock(ContainerResponse.class); when(context.getStatusInfo()).thenReturn(Status.OK); when(context.getStringHeaders()).thenReturn(new MultivaluedHashMap<>()); containerResponseWriter.writeResponseStatusAndHeaders(-1, context); containerResponseWriter.failure(new RuntimeException()); assertEquals(Status.INTERNAL_SERVER_ERROR, response.getStatusType()); } @Test public void failure_ResponseNotYetCommitted_ShouldCommitOnFailure() { containerResponseWriter = spy(containerResponseWriter); containerResponseWriter.failure(new RuntimeException()); verify(containerResponseWriter, times(1)).commit(); } @Test public void failure_ResponseNotYetCommitted_ShouldRethrowOnCommitFailure() { containerResponseWriter = spy(containerResponseWriter); containerResponseWriter.failure(new RuntimeException()); doThrow(CommitException.class).when(containerResponseWriter).commit(); assertThrows(RuntimeException.class, () -> containerResponseWriter.failure(new RuntimeException())); } @Test public void enableResponseBuffering_Always_ShouldBeDisabled() { assertFalse(containerResponseWriter.enableResponseBuffering()); } @Test public void setSuspendTimeout_Always_ShouldBeUnsupported() { assertThrows(UnsupportedOperationException.class, () -> containerResponseWriter.setSuspendTimeout(1, null)); } @Test public void suspend_Always_ShouldBeUnsupported() { assertThrows(UnsupportedOperationException.class, () -> containerResponseWriter.suspend(1, null, null)); } @SuppressWarnings("serial") private static class CommitException extends RuntimeException { } }
bbilger/jrestless
core/jrestless-core-container/src/test/java/com/jrestless/core/container/JRestlessContainerResponseWriterTest.java
Java
apache-2.0
5,472
#!/bin/bash # Clone pinned Kuberay commit to temporary directory, copy the CRD definitions # into the autoscaler folder. SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) DIR=$(mktemp -d -t "kuberay-XXXXXX") pushd "$DIR" || exit git clone https://github.com/ray-project/kuberay/ pushd "kuberay" || exit # If you changed the Kuberay CRD, you need to update this commit to point # to the new CRD. The following always need to be compatible: The used CRDs, # the docker image of the Kuberay operator and the KuberayNodeProvider. # This is normally not a problem since the KuberayNodeProvider uses a # stable part of the CRD definition and the Kuberay operator and the # CRDs are in the https://github.com/ray-project/kuberay/ so they # get updated together. It is important to keep this in mind when making # changes. The CRD is designed to be stable so one operator can run many # different versions of Ray. git checkout 6f87ca64c107cd51d3ab955faf4be198e0094536 # Here is where we specify the docker image that is used for the operator. # If you want to use your own version of Kuberay, you should change the content # of kuberay-autoscaler.patch to point to your operator. # This would normally better be done with kustomization, but we don't want to make # kustomization a dependency for running this. git apply "$SCRIPT_DIR/kuberay-autoscaler.patch" cp -r ray-operator/config "$SCRIPT_DIR/" popd || exit popd || exit
ray-project/ray
python/ray/autoscaler/kuberay/init-config.sh
Shell
apache-2.0
1,600
/** * Copyright (c) 2015-2022, Michael Yang 杨福海 ([email protected]). * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.jboot.support.metric.annotation; import java.lang.annotation.*; @Documented @Target(ElementType.METHOD) @Inherited @Retention(RetentionPolicy.RUNTIME) public @interface EnableMetricTimer { String value() default ""; }
yangfuhai/jboot
src/main/java/io/jboot/support/metric/annotation/EnableMetricTimer.java
Java
apache-2.0
888
<?php header("Content-Type: text/html;charset=utf-8"); $name = $_POST['first_name']; $email = $_POST['email']; $message = $_POST['comments']; $to = "[email protected]"; $subject = "Estimado Representante"; $body = ' <html> <head> <title>Estimado Representante</title> </head> <body> <p><b>Name: </b> '.$name.'</p> <p><b>Email: </b> '.$email.'</p> <p><b>Message: </b> '.$message.'</p> </body> </html> '; $headers = "MIME-Version: 1.0\r\n"; $headers .= "Content-type: text/html; charset=utf-8\r\n"; $headers .= "Bcc: [email protected]" . "\r\n"; $headers .= "From: ".$name." <".$email.">\r\n"; $sended = mail($to, $subject, $body, $headers); ?> <html> <head> <title>Estimado Representante</title> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <div class="bigone"> <div class="menu clearfix"> <a href="index.html"><h2>Home</h2></a> <a href="about.html"><h2>About</h2></a> </div> <div class="line"></div> <div class="cta"> <h1>Estimado Representante,</h1> <h4> Esta p&aacute;gina es dedicada al pueblo puertorrique&ntilde;o para ejercer nuestro derecho de libertad de expresi&oacute;n <br>y exigir el m&aacute;s alto respeto y cumplimiento a nuestros representantes legislativos. Este canal ser&aacute; una fuente de ideas, uno que fomente la unidad y el progreso, uno que demande fiscalizaci&oacute;n, responsabilidad, &eacute;tica, e igualdad.<br> <br><b>Puertorrique&ntilde;o</b>, felicita, comenta, y protesta pero siempre con propiedad y respeto. Di lo que ves. Di lo que piensas. La libertad de expresi&oacute;n te lo permite. La democracia te lo pide. Porque todo representante tiene que escuchar para poder cumplir. </h4> </div> <div class="about"> <h5><b>Tu mensaje fue enviado.</b><br> <br>Si te gust&oacute; la p&aacute;gina, por favor comp&aacute;rtela, y as&iacute; lograremos que m&aacute;s puertorrique&ntilde;os se expresen.<br> <br>Gracias por usar Estimado Representante.</h5> </div> </body> </html>
efrenpagan/estimadolegislador
jgo.php
PHP
apache-2.0
2,041
--- date: 2017-03-21T23:55:53Z title: Comment fonctionne Waziup? url: /fr/documentation/how-waziup-works/ --- Regardons à l'intérieur de la grande machine. Dans cette section vous pouvez trouver: - [L'architecture] (/fr/documentation/how-waziup-works/architecture) - [Concepts Cloud locaux et globaux] (/fr/documentation/how-waziup-works/localglobal) - [Les exigences] (/fr/documentation/how-waziup-works/requirements)
paulpascal/waziup.io
content/documentation/how waziup works/index.fr.md
Markdown
apache-2.0
422
/* * 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. */ package com.github.fhuss.kafka.streams.cep.core.state.internal; import java.util.Objects; /** * Class for aggregated state. * * @param <K> the record key type. */ public class Aggregated<K> { private final K key; private final Aggregate aggregate; /** * Creates a new {@link Aggregated} instance. * @param key the record key * @param aggregate the instance of {@link Aggregate}. */ public Aggregated(final K key, final Aggregate aggregate) { this.key = key; this.aggregate = aggregate; } public K getKey() { return key; } public Aggregate getAggregate() { return aggregate; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Aggregated<?> that = (Aggregated<?>) o; return Objects.equals(key, that.key) && Objects.equals(aggregate, that.aggregate); } @Override public int hashCode() { return Objects.hash(key, aggregate); } @Override public String toString() { return "Aggregated{" + "key=" + key + ", aggregate=" + aggregate + '}'; } }
fhussonnois/kafkastreams-cep
core/src/main/java/com/github/fhuss/kafka/streams/cep/core/state/internal/Aggregated.java
Java
apache-2.0
2,076
/* * ! ${copyright} */ sap.ui.define([ "delegates/odata/v4/TableDelegate", "sap/ui/core/Core" ], function( TableDelegate, Core ) { "use strict"; /** * Test delegate for OData V4. */ var ODataTableDelegate = Object.assign({}, TableDelegate); /** * Updates the binding info with the relevant path and model from the metadata. * * @param {Object} oTable The MDC table instance * @param {Object} oBindingInfo The bindingInfo of the table */ ODataTableDelegate.updateBindingInfo = function(oTable, oBindingInfo) { TableDelegate.updateBindingInfo.apply(this, arguments); var oFilterBar = Core.byId(oTable.getFilter()); if (oFilterBar) { // get the basic search var sSearchText = oFilterBar.getSearch instanceof Function ? oFilterBar.getSearch() : ""; if (sSearchText && sSearchText.indexOf(" ") === -1) { // to allow search for "("..... sSearchText = '"' + sSearchText + '"'; // TODO: escape " in string } // if it contains spaces allow opeartors like OR... oBindingInfo.parameters.$search = sSearchText || undefined; } }; return ODataTableDelegate; });
SAP/openui5
src/sap.ui.mdc/test/sap/ui/mdc/internal/TableWithFilterBar/delegate/GridTable.delegate.js
JavaScript
apache-2.0
1,110
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.apigateway.model.transform; import java.util.List; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.apigateway.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * UpdateMethodResponseRequestMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class UpdateMethodResponseRequestMarshaller { private static final MarshallingInfo<String> RESTAPIID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PATH) .marshallLocationName("restapi_id").build(); private static final MarshallingInfo<String> RESOURCEID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PATH) .marshallLocationName("resource_id").build(); private static final MarshallingInfo<String> HTTPMETHOD_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PATH) .marshallLocationName("http_method").build(); private static final MarshallingInfo<String> STATUSCODE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PATH) .marshallLocationName("status_code").build(); private static final MarshallingInfo<List> PATCHOPERATIONS_BINDING = MarshallingInfo.builder(MarshallingType.LIST) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("patchOperations").build(); private static final UpdateMethodResponseRequestMarshaller instance = new UpdateMethodResponseRequestMarshaller(); public static UpdateMethodResponseRequestMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(UpdateMethodResponseRequest updateMethodResponseRequest, ProtocolMarshaller protocolMarshaller) { if (updateMethodResponseRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(updateMethodResponseRequest.getRestApiId(), RESTAPIID_BINDING); protocolMarshaller.marshall(updateMethodResponseRequest.getResourceId(), RESOURCEID_BINDING); protocolMarshaller.marshall(updateMethodResponseRequest.getHttpMethod(), HTTPMETHOD_BINDING); protocolMarshaller.marshall(updateMethodResponseRequest.getStatusCode(), STATUSCODE_BINDING); protocolMarshaller.marshall(updateMethodResponseRequest.getPatchOperations(), PATCHOPERATIONS_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
jentfoo/aws-sdk-java
aws-java-sdk-api-gateway/src/main/java/com/amazonaws/services/apigateway/model/transform/UpdateMethodResponseRequestMarshaller.java
Java
apache-2.0
3,397
package ip_test import ( . "github.com/cloudfoundry/bosh-init/internal/github.com/onsi/ginkgo" . "github.com/cloudfoundry/bosh-init/internal/github.com/onsi/gomega" "testing" ) func TestPlatform(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Ip Suite") }
allomov/bosh-init
internal/github.com/cloudfoundry/bosh-agent/platform/net/ip/ip_suite_test.go
GO
apache-2.0
271
# -*- coding: utf-8 -*- # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function from future import standard_library standard_library.install_aliases() from builtins import str from past.builtins import basestring from datetime import datetime import logging from urllib.parse import urlparse from time import sleep import airflow from airflow import hooks, settings from airflow.exceptions import AirflowException, AirflowSensorTimeout, AirflowSkipException from airflow.models import BaseOperator, TaskInstance, Connection as DB from airflow.hooks.base_hook import BaseHook from airflow.utils.state import State from airflow.utils.decorators import apply_defaults class BaseSensorOperator(BaseOperator): ''' Sensor operators are derived from this class an inherit these attributes. Sensor operators keep executing at a time interval and succeed when a criteria is met and fail if and when they time out. :param soft_fail: Set to true to mark the task as SKIPPED on failure :type soft_fail: bool :param poke_interval: Time in seconds that the job should wait in between each tries :type poke_interval: int :param timeout: Time, in seconds before the task times out and fails. :type timeout: int ''' ui_color = '#e6f1f2' @apply_defaults def __init__( self, poke_interval=60, timeout=60*60*24*7, soft_fail=False, *args, **kwargs): super(BaseSensorOperator, self).__init__(*args, **kwargs) self.poke_interval = poke_interval self.soft_fail = soft_fail self.timeout = timeout def poke(self, context): ''' Function that the sensors defined while deriving this class should override. ''' raise AirflowException('Override me.') def execute(self, context): started_at = datetime.now() while not self.poke(context): if (datetime.now() - started_at).total_seconds() > self.timeout: if self.soft_fail: raise AirflowSkipException('Snap. Time is OUT.') else: raise AirflowSensorTimeout('Snap. Time is OUT.') sleep(self.poke_interval) logging.info("Success criteria met. Exiting.") class SqlSensor(BaseSensorOperator): """ Runs a sql statement until a criteria is met. It will keep trying until sql returns no row, or if the first cell in (0, '0', ''). :param conn_id: The connection to run the sensor against :type conn_id: string :param sql: The sql to run. To pass, it needs to return at least one cell that contains a non-zero / empty string value. """ template_fields = ('sql',) template_ext = ('.hql', '.sql',) @apply_defaults def __init__(self, conn_id, sql, *args, **kwargs): self.sql = sql self.conn_id = conn_id super(SqlSensor, self).__init__(*args, **kwargs) def poke(self, context): hook = BaseHook.get_connection(self.conn_id).get_hook() logging.info('Poking: ' + self.sql) records = hook.get_records(self.sql) if not records: return False else: if str(records[0][0]) in ('0', '',): return False else: return True print(records[0][0]) class MetastorePartitionSensor(SqlSensor): """ An alternative to the HivePartitionSensor that talk directly to the MySQL db. This was created as a result of observing sub optimal queries generated by the Metastore thrift service when hitting subpartitioned tables. The Thrift service's queries were written in a way that wouldn't leverage the indexes. :param schema: the schema :type schema: str :param table: the table :type table: str :param partition_name: the partition name, as defined in the PARTITIONS table of the Metastore. Order of the fields does matter. Examples: ``ds=2016-01-01`` or ``ds=2016-01-01/sub=foo`` for a sub partitioned table :type partition_name: str :param mysql_conn_id: a reference to the MySQL conn_id for the metastore :type mysql_conn_id: str """ template_fields = ('partition_name', 'table', 'schema') @apply_defaults def __init__( self, table, partition_name, schema="default", mysql_conn_id="metastore_mysql", *args, **kwargs): self.partition_name = partition_name self.table = table self.schema = schema self.first_poke = True self.conn_id = mysql_conn_id super(SqlSensor, self).__init__(*args, **kwargs) def poke(self, context): if self.first_poke: self.first_poke = False if '.' in self.table: self.schema, self.table = self.table.split('.') self.sql = """ SELECT 'X' FROM PARTITIONS A0 LEFT OUTER JOIN TBLS B0 ON A0.TBL_ID = B0.TBL_ID LEFT OUTER JOIN DBS C0 ON B0.DB_ID = C0.DB_ID WHERE B0.TBL_NAME = '{self.table}' AND C0.NAME = '{self.schema}' AND A0.PART_NAME = '{self.partition_name}'; """.format(self=self) return super(MetastorePartitionSensor, self).poke(context) class ExternalTaskSensor(BaseSensorOperator): """ Waits for a task to complete in a different DAG :param external_dag_id: The dag_id that contains the task you want to wait for :type external_dag_id: string :param external_task_id: The task_id that contains the task you want to wait for :type external_task_id: string :param allowed_states: list of allowed states, default is ``['success']`` :type allowed_states: list :param execution_delta: time difference with the previous execution to look at, the default is the same execution_date as the current task. For yesterday, use [positive!] datetime.timedelta(days=1). Either execution_delta or execution_date_fn can be passed to ExternalTaskSensor, but not both. :type execution_delta: datetime.timedelta :param execution_date_fn: function that receives the current execution date and returns the desired execution date to query. Either execution_delta or execution_date_fn can be passed to ExternalTaskSensor, but not both. :type execution_date_fn: callable """ @apply_defaults def __init__( self, external_dag_id, external_task_id, allowed_states=None, execution_delta=None, execution_date_fn=None, *args, **kwargs): super(ExternalTaskSensor, self).__init__(*args, **kwargs) self.allowed_states = allowed_states or [State.SUCCESS] if execution_delta is not None and execution_date_fn is not None: raise ValueError( 'Only one of `execution_date` or `execution_date_fn` may' 'be provided to ExternalTaskSensor; not both.') self.execution_delta = execution_delta self.execution_date_fn = execution_date_fn self.external_dag_id = external_dag_id self.external_task_id = external_task_id def poke(self, context): if self.execution_delta: dttm = context['execution_date'] - self.execution_delta elif self.execution_date_fn: dttm = self.execution_date_fn(context['execution_date']) else: dttm = context['execution_date'] logging.info( 'Poking for ' '{self.external_dag_id}.' '{self.external_task_id} on ' '{dttm} ... '.format(**locals())) TI = TaskInstance session = settings.Session() count = session.query(TI).filter( TI.dag_id == self.external_dag_id, TI.task_id == self.external_task_id, TI.state.in_(self.allowed_states), TI.execution_date == dttm, ).count() session.commit() session.close() return count class NamedHivePartitionSensor(BaseSensorOperator): """ Waits for a set of partitions to show up in Hive. :param partition_names: List of fully qualified names of the partitions to wait for. A fully qualified name is of the form schema.table/pk1=pv1/pk2=pv2, for example, default.users/ds=2016-01-01. This is passed as is to the metastore Thrift client "get_partitions_by_name" method. Note that you cannot use logical operators as in HivePartitionSensor. :type partition_names: list of strings :param metastore_conn_id: reference to the metastore thrift service connection id :type metastore_conn_id: str """ template_fields = ('partition_names', ) @apply_defaults def __init__( self, partition_names, metastore_conn_id='metastore_default', poke_interval=60*3, *args, **kwargs): super(NamedHivePartitionSensor, self).__init__( poke_interval=poke_interval, *args, **kwargs) if isinstance(partition_names, basestring): raise TypeError('partition_names must be an array of strings') self.metastore_conn_id = metastore_conn_id self.partition_names = partition_names self.next_poke_idx = 0 def parse_partition_name(self, partition): try: schema, table_partition = partition.split('.') table, partition = table_partition.split('/', 1) return schema, table, partition except ValueError as e: raise ValueError('Could not parse ' + partition) def poke(self, context): if not hasattr(self, 'hook'): self.hook = airflow.hooks.hive_hooks.HiveMetastoreHook( metastore_conn_id=self.metastore_conn_id) def poke_partition(partition): schema, table, partition = self.parse_partition_name(partition) logging.info( 'Poking for {schema}.{table}/{partition}'.format(**locals()) ) return self.hook.check_for_named_partition( schema, table, partition) while self.next_poke_idx < len(self.partition_names): if poke_partition(self.partition_names[self.next_poke_idx]): self.next_poke_idx += 1 else: return False return True class HivePartitionSensor(BaseSensorOperator): """ Waits for a partition to show up in Hive. Note: Because @partition supports general logical operators, it can be inefficient. Consider using NamedHivePartitionSensor instead if you don't need the full flexibility of HivePartitionSensor. :param table: The name of the table to wait for, supports the dot notation (my_database.my_table) :type table: string :param partition: The partition clause to wait for. This is passed as is to the metastore Thrift client "get_partitions_by_filter" method, and apparently supports SQL like notation as in `ds='2015-01-01' AND type='value'` and > < sings as in "ds>=2015-01-01" :type partition: string :param metastore_conn_id: reference to the metastore thrift service connection id :type metastore_conn_id: str """ template_fields = ('schema', 'table', 'partition',) @apply_defaults def __init__( self, table, partition="ds='{{ ds }}'", metastore_conn_id='metastore_default', schema='default', poke_interval=60*3, *args, **kwargs): super(HivePartitionSensor, self).__init__( poke_interval=poke_interval, *args, **kwargs) if not partition: partition = "ds='{{ ds }}'" self.metastore_conn_id = metastore_conn_id self.table = table self.partition = partition self.schema = schema def poke(self, context): if '.' in self.table: self.schema, self.table = self.table.split('.') logging.info( 'Poking for table {self.schema}.{self.table}, ' 'partition {self.partition}'.format(**locals())) if not hasattr(self, 'hook'): self.hook = airflow.hooks.hive_hooks.HiveMetastoreHook( metastore_conn_id=self.metastore_conn_id) return self.hook.check_for_partition( self.schema, self.table, self.partition) class HdfsSensor(BaseSensorOperator): """ Waits for a file or folder to land in HDFS """ template_fields = ('filepath',) @apply_defaults def __init__( self, filepath, hdfs_conn_id='hdfs_default', *args, **kwargs): super(HdfsSensor, self).__init__(*args, **kwargs) self.filepath = filepath self.hdfs_conn_id = hdfs_conn_id def poke(self, context): import airflow.hooks.hdfs_hook sb = airflow.hooks.hdfs_hook.HDFSHook(self.hdfs_conn_id).get_conn() logging.getLogger("snakebite").setLevel(logging.WARNING) logging.info( 'Poking for file {self.filepath} '.format(**locals())) try: files = [f for f in sb.ls([self.filepath])] except: return False return True class WebHdfsSensor(BaseSensorOperator): """ Waits for a file or folder to land in HDFS """ template_fields = ('filepath',) @apply_defaults def __init__( self, filepath, webhdfs_conn_id='webhdfs_default', *args, **kwargs): super(WebHdfsSensor, self).__init__(*args, **kwargs) self.filepath = filepath self.webhdfs_conn_id = webhdfs_conn_id def poke(self, context): c = airflow.hooks.webhdfs_hook.WebHDFSHook(self.webhdfs_conn_id) logging.info( 'Poking for file {self.filepath} '.format(**locals())) return c.check_for_path(hdfs_path=self.filepath) class S3KeySensor(BaseSensorOperator): """ Waits for a key (a file-like instance on S3) to be present in a S3 bucket. S3 being a key/value it does not support folders. The path is just a key a resource. :param bucket_key: The key being waited on. Supports full s3:// style url or relative path from root level. :type bucket_key: str :param bucket_name: Name of the S3 bucket :type bucket_name: str :param wildcard_match: whether the bucket_key should be interpreted as a Unix wildcard pattern :type wildcard_match: bool :param s3_conn_id: a reference to the s3 connection :type s3_conn_id: str """ template_fields = ('bucket_key', 'bucket_name') @apply_defaults def __init__( self, bucket_key, bucket_name=None, wildcard_match=False, s3_conn_id='s3_default', *args, **kwargs): super(S3KeySensor, self).__init__(*args, **kwargs) session = settings.Session() db = session.query(DB).filter(DB.conn_id == s3_conn_id).first() if not db: raise AirflowException("conn_id doesn't exist in the repository") # Parse if bucket_name is None: parsed_url = urlparse(bucket_key) if parsed_url.netloc == '': raise AirflowException('Please provide a bucket_name') else: bucket_name = parsed_url.netloc if parsed_url.path[0] == '/': bucket_key = parsed_url.path[1:] else: bucket_key = parsed_url.path self.bucket_name = bucket_name self.bucket_key = bucket_key self.wildcard_match = wildcard_match self.s3_conn_id = s3_conn_id session.commit() session.close() def poke(self, context): import airflow.hooks.S3_hook hook = airflow.hooks.S3_hook.S3Hook(s3_conn_id=self.s3_conn_id) full_url = "s3://" + self.bucket_name + "/" + self.bucket_key logging.info('Poking for key : {full_url}'.format(**locals())) if self.wildcard_match: return hook.check_for_wildcard_key(self.bucket_key, self.bucket_name) else: return hook.check_for_key(self.bucket_key, self.bucket_name) class S3PrefixSensor(BaseSensorOperator): """ Waits for a prefix to exist. A prefix is the first part of a key, thus enabling checking of constructs similar to glob airfl* or SQL LIKE 'airfl%'. There is the possibility to precise a delimiter to indicate the hierarchy or keys, meaning that the match will stop at that delimiter. Current code accepts sane delimiters, i.e. characters that are NOT special characters in the Python regex engine. :param bucket_name: Name of the S3 bucket :type bucket_name: str :param prefix: The prefix being waited on. Relative path from bucket root level. :type prefix: str :param delimiter: The delimiter intended to show hierarchy. Defaults to '/'. :type delimiter: str """ template_fields = ('prefix', 'bucket_name') @apply_defaults def __init__( self, bucket_name, prefix, delimiter='/', s3_conn_id='s3_default', *args, **kwargs): super(S3PrefixSensor, self).__init__(*args, **kwargs) session = settings.Session() db = session.query(DB).filter(DB.conn_id == s3_conn_id).first() if not db: raise AirflowException("conn_id doesn't exist in the repository") # Parse self.bucket_name = bucket_name self.prefix = prefix self.delimiter = delimiter self.full_url = "s3://" + bucket_name + '/' + prefix self.s3_conn_id = s3_conn_id session.commit() session.close() def poke(self, context): logging.info('Poking for prefix : {self.prefix}\n' 'in bucket s3://{self.bucket_name}'.format(**locals())) import airflow.hooks.S3_hook hook = airflow.hooks.S3_hook.S3Hook(s3_conn_id=self.s3_conn_id) return hook.check_for_prefix( prefix=self.prefix, delimiter=self.delimiter, bucket_name=self.bucket_name) class TimeSensor(BaseSensorOperator): """ Waits until the specified time of the day. :param target_time: time after which the job succeeds :type target_time: datetime.time """ template_fields = tuple() @apply_defaults def __init__(self, target_time, *args, **kwargs): super(TimeSensor, self).__init__(*args, **kwargs) self.target_time = target_time def poke(self, context): logging.info( 'Checking if the time ({0}) has come'.format(self.target_time)) return datetime.now().time() > self.target_time class TimeDeltaSensor(BaseSensorOperator): """ Waits for a timedelta after the task's execution_date + schedule_interval. In Airflow, the daily task stamped with ``execution_date`` 2016-01-01 can only start running on 2016-01-02. The timedelta here represents the time after the execution period has closed. :param delta: time length to wait after execution_date before succeeding :type delta: datetime.timedelta """ template_fields = tuple() @apply_defaults def __init__(self, delta, *args, **kwargs): super(TimeDeltaSensor, self).__init__(*args, **kwargs) self.delta = delta def poke(self, context): dag = context['dag'] target_dttm = dag.following_schedule(context['execution_date']) target_dttm += self.delta logging.info('Checking if the time ({0}) has come'.format(target_dttm)) return datetime.now() > target_dttm class HttpSensor(BaseSensorOperator): """ Executes a HTTP get statement and returns False on failure: 404 not found or response_check function returned False :param http_conn_id: The connection to run the sensor against :type http_conn_id: string :param endpoint: The relative part of the full url :type endpoint: string :param params: The parameters to be added to the GET url :type params: a dictionary of string key/value pairs :param headers: The HTTP headers to be added to the GET request :type headers: a dictionary of string key/value pairs :param response_check: A check against the 'requests' response object. Returns True for 'pass' and False otherwise. :type response_check: A lambda or defined function. :param extra_options: Extra options for the 'requests' library, see the 'requests' documentation (options to modify timeout, ssl, etc.) :type extra_options: A dictionary of options, where key is string and value depends on the option that's being modified. """ template_fields = ('endpoint',) @apply_defaults def __init__(self, endpoint, http_conn_id='http_default', params=None, headers=None, response_check=None, extra_options=None, *args, **kwargs): super(HttpSensor, self).__init__(*args, **kwargs) self.endpoint = endpoint self.http_conn_id = http_conn_id self.params = params or {} self.headers = headers or {} self.extra_options = extra_options or {} self.response_check = response_check self.hook = hooks.http_hook.HttpHook(method='GET', http_conn_id=http_conn_id) def poke(self, context): logging.info('Poking: ' + self.endpoint) try: response = self.hook.run(self.endpoint, data=self.params, headers=self.headers, extra_options=self.extra_options) if self.response_check: # run content check on response return self.response_check(response) except AirflowException as ae: if str(ae).startswith("404"): return False raise ae return True
d-lee/airflow
airflow/operators/sensors.py
Python
apache-2.0
22,890
/* Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package multiwriter provides an io.Writer that duplicates its writes to multiple writers concurrently. package multiwriter import ( "io" ) // multiWriter duplicates writes to multiple writers. type multiWriter []io.Writer // New returns an io.Writer that duplicates writes to all provided writers. func New(w ...io.Writer) io.Writer { return multiWriter(w) } // Write writes p to all writers concurrently. If any errors occur, the shortest write is returned. func (mw multiWriter) Write(p []byte) (int, error) { done := make(chan result, len(mw)) for _, w := range mw { go send(w, p, done) } endResult := result{n: len(p)} for _ = range mw { res := <-done if res.err != nil && (endResult.err == nil || res.n < endResult.n) { endResult = res } } return endResult.n, endResult.err } func send(w io.Writer, p []byte, done chan<- result) { var res result res.n, res.err = w.Write(p) if res.n < len(p) && res.err == nil { res.err = io.ErrShortWrite } done <- res } type result struct { n int err error }
zombiezen/cardcpx
multiwriter/multiwriter.go
GO
apache-2.0
1,627
package org.aksw.servicecat.web.api; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import org.aksw.servicecat.core.ServiceAnalyzerProcessor; import org.springframework.beans.factory.annotation.Autowired; @org.springframework.stereotype.Service @Path("/services") public class ServletServiceApi { @Autowired private ServiceAnalyzerProcessor processor; @GET @Produces(MediaType.APPLICATION_JSON) @Path("/put") public String registerService(@QueryParam("url") String serviceUrl) { processor.process(serviceUrl); String result = "{}"; return result; } }
GeoKnow/SparqlServiceCatalogue
servicecat-webapp/src/main/java/org/aksw/servicecat/web/api/ServletServiceApi.java
Java
apache-2.0
728
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.macie2.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.macie2.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * AccountDetailMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class AccountDetailMarshaller { private static final MarshallingInfo<String> ACCOUNTID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("accountId").build(); private static final MarshallingInfo<String> EMAIL_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("email").build(); private static final AccountDetailMarshaller instance = new AccountDetailMarshaller(); public static AccountDetailMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(AccountDetail accountDetail, ProtocolMarshaller protocolMarshaller) { if (accountDetail == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(accountDetail.getAccountId(), ACCOUNTID_BINDING); protocolMarshaller.marshall(accountDetail.getEmail(), EMAIL_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
aws/aws-sdk-java
aws-java-sdk-macie2/src/main/java/com/amazonaws/services/macie2/model/transform/AccountDetailMarshaller.java
Java
apache-2.0
2,226
package org.apache.rya.indexing.external; import java.net.UnknownHostException; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.List; import org.apache.accumulo.core.client.AccumuloException; import org.apache.accumulo.core.client.AccumuloSecurityException; import org.apache.accumulo.core.client.Connector; import org.apache.accumulo.core.client.TableExistsException; import org.apache.accumulo.core.client.TableNotFoundException; import org.apache.accumulo.core.client.mock.MockInstance; import org.apache.accumulo.core.client.security.tokens.PasswordToken; import org.apache.rya.indexing.pcj.storage.PcjException; import org.apache.rya.indexing.pcj.storage.accumulo.PcjVarOrderFactory; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.openrdf.model.URI; import org.openrdf.model.impl.LiteralImpl; import org.openrdf.model.impl.URIImpl; import org.openrdf.model.vocabulary.RDF; import org.openrdf.model.vocabulary.RDFS; import org.openrdf.query.BindingSet; import org.openrdf.query.MalformedQueryException; import org.openrdf.query.QueryEvaluationException; import org.openrdf.query.QueryLanguage; import org.openrdf.query.QueryResultHandlerException; import org.openrdf.query.TupleQueryResultHandler; import org.openrdf.query.TupleQueryResultHandlerException; import org.openrdf.repository.RepositoryException; import org.openrdf.repository.sail.SailRepository; import org.openrdf.repository.sail.SailRepositoryConnection; import org.openrdf.sail.SailException; import com.google.common.base.Optional; import org.apache.rya.api.persist.RyaDAOException; import org.apache.rya.rdftriplestore.inference.InferenceEngineException; public class AccumuloConstantPcjIntegrationTest { private SailRepositoryConnection conn, pcjConn; private SailRepository repo, pcjRepo; private Connector accCon; String prefix = "table_"; String tablename = "table_INDEX_"; URI obj, obj2, subclass, subclass2, talksTo; @Before public void init() throws RepositoryException, TupleQueryResultHandlerException, QueryEvaluationException, MalformedQueryException, AccumuloException, AccumuloSecurityException, TableExistsException, TableNotFoundException, RyaDAOException, InferenceEngineException, NumberFormatException, UnknownHostException, SailException { repo = PcjIntegrationTestingUtil.getNonPcjRepo(prefix, "instance"); conn = repo.getConnection(); pcjRepo = PcjIntegrationTestingUtil.getPcjRepo(prefix, "instance"); pcjConn = pcjRepo.getConnection(); final URI sub = new URIImpl("uri:entity"); subclass = new URIImpl("uri:class"); obj = new URIImpl("uri:obj"); talksTo = new URIImpl("uri:talksTo"); conn.add(sub, RDF.TYPE, subclass); conn.add(sub, RDFS.LABEL, new LiteralImpl("label")); conn.add(sub, talksTo, obj); final URI sub2 = new URIImpl("uri:entity2"); subclass2 = new URIImpl("uri:class2"); obj2 = new URIImpl("uri:obj2"); conn.add(sub2, RDF.TYPE, subclass2); conn.add(sub2, RDFS.LABEL, new LiteralImpl("label2")); conn.add(sub2, talksTo, obj2); accCon = new MockInstance("instance").getConnector("root",new PasswordToken("")); } @After public void close() throws RepositoryException, AccumuloException, AccumuloSecurityException, TableNotFoundException { PcjIntegrationTestingUtil.closeAndShutdown(conn, repo); PcjIntegrationTestingUtil.closeAndShutdown(pcjConn, pcjRepo); PcjIntegrationTestingUtil.deleteCoreRyaTables(accCon, prefix); PcjIntegrationTestingUtil.deleteIndexTables(accCon, 2, prefix); } @Test public void testEvaluateTwoIndexVarInstantiate1() throws PcjException, RepositoryException, AccumuloException, AccumuloSecurityException, TableNotFoundException, TableExistsException, MalformedQueryException, SailException, QueryEvaluationException, TupleQueryResultHandlerException { final URI superclass = new URIImpl("uri:superclass"); final URI superclass2 = new URIImpl("uri:superclass2"); conn.add(subclass, RDF.TYPE, superclass); conn.add(subclass2, RDF.TYPE, superclass2); conn.add(obj, RDFS.LABEL, new LiteralImpl("label")); conn.add(obj2, RDFS.LABEL, new LiteralImpl("label2")); conn.add(obj, RDFS.LABEL, new LiteralImpl("label")); conn.add(obj2, RDFS.LABEL, new LiteralImpl("label2")); final String indexSparqlString = ""// + "SELECT ?dog ?pig ?duck " // + "{" // + " ?pig a ?dog . "// + " ?pig <http://www.w3.org/2000/01/rdf-schema#label> ?duck "// + "}";// final String indexSparqlString2 = ""// + "SELECT ?o ?f ?e ?c ?l " // + "{" // + " ?e <uri:talksTo> ?o . "// + " ?o <http://www.w3.org/2000/01/rdf-schema#label> ?l. "// + " ?c a ?f . " // + "}";// final String queryString = ""// + "SELECT ?c ?l ?f ?o " // + "{" // + " <uri:entity> a ?c . "// + " <uri:entity> <http://www.w3.org/2000/01/rdf-schema#label> ?l. "// + " <uri:entity> <uri:talksTo> ?o . "// + " ?o <http://www.w3.org/2000/01/rdf-schema#label> ?l. "// + " ?c a ?f . " // + "}";// PcjIntegrationTestingUtil.createAndPopulatePcj(conn, accCon, tablename + 1, indexSparqlString, new String[] { "dog", "pig", "duck" }, Optional.<PcjVarOrderFactory> absent()); PcjIntegrationTestingUtil.createAndPopulatePcj(conn, accCon, tablename + 2, indexSparqlString2, new String[] { "o", "f", "e", "c", "l" }, Optional.<PcjVarOrderFactory> absent()); final CountingResultHandler crh1 = new CountingResultHandler(); final CountingResultHandler crh2 = new CountingResultHandler(); conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString) .evaluate(crh1); PcjIntegrationTestingUtil.deleteCoreRyaTables(accCon, prefix); pcjConn.prepareTupleQuery(QueryLanguage.SPARQL, queryString).evaluate(crh2); Assert.assertEquals(crh1.getCount(), crh2.getCount()); } @Test public void testEvaluateThreeIndexVarInstantiate() throws PcjException, RepositoryException, AccumuloException, AccumuloSecurityException, TableNotFoundException, TableExistsException, MalformedQueryException, SailException, QueryEvaluationException, TupleQueryResultHandlerException { final URI superclass = new URIImpl("uri:superclass"); final URI superclass2 = new URIImpl("uri:superclass2"); final URI sub = new URIImpl("uri:entity"); subclass = new URIImpl("uri:class"); obj = new URIImpl("uri:obj"); talksTo = new URIImpl("uri:talksTo"); final URI howlsAt = new URIImpl("uri:howlsAt"); final URI subType = new URIImpl("uri:subType"); conn.add(subclass, RDF.TYPE, superclass); conn.add(subclass2, RDF.TYPE, superclass2); conn.add(obj, RDFS.LABEL, new LiteralImpl("label")); conn.add(obj2, RDFS.LABEL, new LiteralImpl("label2")); conn.add(sub, howlsAt, superclass); conn.add(superclass, subType, obj); conn.add(obj, RDFS.LABEL, new LiteralImpl("label")); conn.add(obj2, RDFS.LABEL, new LiteralImpl("label2")); final String indexSparqlString = ""// + "SELECT ?dog ?pig ?duck " // + "{" // + " ?pig a ?dog . "// + " ?pig <http://www.w3.org/2000/01/rdf-schema#label> ?duck "// + "}";// final String indexSparqlString2 = ""// + "SELECT ?o ?f ?e ?c ?l " // + "{" // + " ?e <uri:talksTo> ?o . "// + " ?o <http://www.w3.org/2000/01/rdf-schema#label> ?l. "// + " ?c a ?f . " // + "}";// final String indexSparqlString3 = ""// + "SELECT ?wolf ?sheep ?chicken " // + "{" // + " ?wolf <uri:howlsAt> ?sheep . "// + " ?sheep <uri:subType> ?chicken. "// + "}";// final String queryString = ""// + "SELECT ?c ?l ?f ?o " // + "{" // + " <uri:entity> a ?c . "// + " <uri:entity> <http://www.w3.org/2000/01/rdf-schema#label> ?l. "// + " <uri:entity> <uri:talksTo> ?o . "// + " ?o <http://www.w3.org/2000/01/rdf-schema#label> ?l. "// + " ?c a ?f . " // + " <uri:entity> <uri:howlsAt> ?f. "// + " ?f <uri:subType> <uri:obj>. "// + "}";// PcjIntegrationTestingUtil.createAndPopulatePcj(conn, accCon, tablename + 1, indexSparqlString, new String[] { "dog", "pig", "duck" }, Optional.<PcjVarOrderFactory> absent()); PcjIntegrationTestingUtil.createAndPopulatePcj(conn, accCon, tablename + 2, indexSparqlString2, new String[] { "o", "f", "e", "c", "l" }, Optional.<PcjVarOrderFactory> absent()); PcjIntegrationTestingUtil.createAndPopulatePcj(conn, accCon, tablename + 3, indexSparqlString3, new String[] { "wolf", "sheep", "chicken" }, Optional.<PcjVarOrderFactory> absent()); final CountingResultHandler crh1 = new CountingResultHandler(); final CountingResultHandler crh2 = new CountingResultHandler(); conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString) .evaluate(crh1); PcjIntegrationTestingUtil.deleteCoreRyaTables(accCon, prefix); pcjConn.prepareTupleQuery(QueryLanguage.SPARQL, queryString).evaluate( crh2); Assert.assertEquals(crh1.getCount(), crh2.getCount()); } @Test public void testEvaluateFilterInstantiate() throws RepositoryException, PcjException, MalformedQueryException, SailException, QueryEvaluationException, TableNotFoundException, TupleQueryResultHandlerException, AccumuloException, AccumuloSecurityException { final URI e1 = new URIImpl("uri:e1"); final URI e2 = new URIImpl("uri:e2"); final URI e3 = new URIImpl("uri:e3"); final URI f1 = new URIImpl("uri:f1"); final URI f2 = new URIImpl("uri:f2"); final URI f3 = new URIImpl("uri:f3"); final URI g1 = new URIImpl("uri:g1"); final URI g2 = new URIImpl("uri:g2"); final URI g3 = new URIImpl("uri:g3"); conn.add(e1, talksTo, f1); conn.add(f1, talksTo, g1); conn.add(g1, talksTo, e1); conn.add(e2, talksTo, f2); conn.add(f2, talksTo, g2); conn.add(g2, talksTo, e2); conn.add(e3, talksTo, f3); conn.add(f3, talksTo, g3); conn.add(g3, talksTo, e3); final String queryString = ""// + "SELECT ?x ?y ?z " // + "{" // + "Filter(?x = <uri:e1>) . " // + " ?x <uri:talksTo> ?y. " // + " ?y <uri:talksTo> ?z. " // + " ?z <uri:talksTo> <uri:e1>. " // + "}";// final String indexSparqlString = ""// + "SELECT ?a ?b ?c ?d " // + "{" // + "Filter(?a = ?d) . " // + " ?a <uri:talksTo> ?b. " // + " ?b <uri:talksTo> ?c. " // + " ?c <uri:talksTo> ?d. " // + "}";// PcjIntegrationTestingUtil.createAndPopulatePcj(conn, accCon, tablename + 1, indexSparqlString, new String[] { "a", "b", "c", "d" }, Optional.<PcjVarOrderFactory> absent()); final CountingResultHandler crh1 = new CountingResultHandler(); final CountingResultHandler crh2 = new CountingResultHandler(); conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString) .evaluate(crh1); PcjIntegrationTestingUtil.deleteCoreRyaTables(accCon, prefix); pcjConn.prepareTupleQuery(QueryLanguage.SPARQL, queryString).evaluate(crh2); Assert.assertEquals(crh1.getCount(), crh2.getCount()); } @Test public void testEvaluateCompoundFilterInstantiate() throws RepositoryException, PcjException, MalformedQueryException, SailException, QueryEvaluationException, TableNotFoundException, TupleQueryResultHandlerException, AccumuloException, AccumuloSecurityException { final URI e1 = new URIImpl("uri:e1"); final URI f1 = new URIImpl("uri:f1"); conn.add(e1, talksTo, e1); conn.add(e1, talksTo, f1); conn.add(f1, talksTo, e1); final String queryString = ""// + "SELECT ?x ?y ?z " // + "{" // + "Filter(?x = <uri:e1> && ?y = <uri:e1>) . " // + " ?x <uri:talksTo> ?y. " // + " ?y <uri:talksTo> ?z. " // + " ?z <uri:talksTo> <uri:e1>. " // + "}";// final String indexSparqlString = ""// + "SELECT ?a ?b ?c ?d " // + "{" // + "Filter(?a = ?d && ?b = ?d) . " // + " ?a <uri:talksTo> ?b. " // + " ?b <uri:talksTo> ?c. " // + " ?c <uri:talksTo> ?d. " // + "}";// PcjIntegrationTestingUtil.createAndPopulatePcj(conn, accCon, tablename + 1, indexSparqlString, new String[] { "a", "b", "c", "d" }, Optional.<PcjVarOrderFactory> absent()); final CountingResultHandler crh1 = new CountingResultHandler(); final CountingResultHandler crh2 = new CountingResultHandler(); conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString) .evaluate(crh1); PcjIntegrationTestingUtil.deleteCoreRyaTables(accCon, prefix); pcjConn.prepareTupleQuery(QueryLanguage.SPARQL, queryString).evaluate( crh2); Assert.assertEquals(2, crh1.getCount()); Assert.assertEquals(crh1.getCount(), crh2.getCount()); } public static class CountingResultHandler implements TupleQueryResultHandler { private int count = 0; public int getCount() { return count; } public void resetCount() { count = 0; } @Override public void startQueryResult(final List<String> arg0) throws TupleQueryResultHandlerException { } @Override public void handleSolution(final BindingSet arg0) throws TupleQueryResultHandlerException { count++; } @Override public void endQueryResult() throws TupleQueryResultHandlerException { } @Override public void handleBoolean(final boolean arg0) throws QueryResultHandlerException { } @Override public void handleLinks(final List<String> arg0) throws QueryResultHandlerException { } } }
pujav65/incubator-rya
extras/indexing/src/test/java/org/apache/rya/indexing/external/AccumuloConstantPcjIntegrationTest.java
Java
apache-2.0
14,058
// Copyright 2007-2008 The Apache Software Foundation. // // 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. namespace MassTransit { using System; /// <summary> /// Specifies the elapsed time before a message expires. When a message expires, the content is no longer /// // important and it can be automatically discarded by the message service. /// </summary> [AttributeUsage(AttributeTargets.Class)] public class ExpiresInAttribute : Attribute { private readonly TimeSpan _timeToLive; /// <summary> /// Specifies the elapsed time before the message expires. /// </summary> /// <param name="timeToLive">The duration of the time period.</param> public ExpiresInAttribute(string timeToLive) { TimeSpan value; if (!TimeSpan.TryParse(timeToLive, out value)) throw new ArgumentException("Unable to convert string to TimeSpan", "timeToLive"); _timeToLive = value; } /// <summary> /// Returns the TimeSpan for the message expiration /// </summary> public TimeSpan TimeToLive { get { return _timeToLive; } } } }
rodolfograve/MassTransit
src/MassTransit/ExpiresInAttribute.cs
C#
apache-2.0
1,778
# aws included via metadata.rb # if node[:ebs_volumes] # node[:ebs_volumes].each do |name, conf| # aws_ebs_volume "attach hdfs volume #{conf.inspect}" do # provider "aws_ebs_volume" # aws_access_key node[:aws][:aws_access_key] # aws_secret_access_key node[:aws][:aws_secret_access_key] # aws_region node[:aws][:aws_region] # availability_zone node[:aws][:availability_zone] # volume_id conf[:volume_id] # device conf[:device] # action :attach # end # end # end
infochimps-away/cluster_chef
site-cookbooks/ebs/recipes/attach_volumes.rb
Ruby
apache-2.0
571
package de.jpaw.fixedpoint.tests; import java.math.BigDecimal; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import de.jpaw.fixedpoint.types.MicroUnits; public class TestConversions { @Test public void testFromConversions() throws Exception { MicroUnits fromLong = MicroUnits.valueOf(2); MicroUnits fromDouble = MicroUnits.valueOf(2.0); MicroUnits fromString = MicroUnits.valueOf("2.0"); MicroUnits fromBigDecimal = MicroUnits.valueOf(BigDecimal.valueOf(2)); MicroUnits fromMantissa = MicroUnits.of(2_000_000L); Assertions.assertEquals(fromMantissa, fromBigDecimal, "from BigDecimal"); Assertions.assertEquals(fromMantissa, fromString, "from String"); Assertions.assertEquals(fromMantissa, fromDouble, "from double"); Assertions.assertEquals(fromMantissa, fromLong, "from long"); } @Test public void testToConversions() throws Exception { MicroUnits value = MicroUnits.valueOf(2); Assertions.assertEquals("2", value.toString(), "to String"); Assertions.assertEquals(BigDecimal.valueOf(2).setScale(6), value.toBigDecimal(), "to BigDecimal"); Assertions.assertEquals(2, value.intValue(), "to int"); Assertions.assertEquals(2.0, value.doubleValue(), "to double"); Assertions.assertEquals(2_000_000L, value.getMantissa(), "to Mantissa"); } }
jpaw/jpaw
jpaw-fixedpoint-core/src/test/java/de/jpaw/fixedpoint/tests/TestConversions.java
Java
apache-2.0
1,420
package org.dominokit.domino.api.client; @FunctionalInterface public interface ApplicationStartHandler { void onApplicationStarted(); }
GwtDomino/domino
domino-api-client/src/main/java/org/dominokit/domino/api/client/ApplicationStartHandler.java
Java
apache-2.0
141
<!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_20) on Fri Mar 25 19:54:51 PDT 2011 --> <TITLE> org.apache.hadoop.io.nativeio (Hadoop 0.20.2-cdh3u0 API) </TITLE> <META NAME="date" CONTENT="2011-03-25"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> </HEAD> <BODY BGCOLOR="white"> <FONT size="+1" CLASS="FrameTitleFont"> <A HREF="../../../../../org/apache/hadoop/io/nativeio/package-summary.html" target="classFrame">org.apache.hadoop.io.nativeio</A></FONT> <TABLE BORDER="0" WIDTH="100%" SUMMARY=""> <TR> <TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont"> Classes</FONT>&nbsp; <FONT CLASS="FrameItemFont"> <BR> <A HREF="NativeIO.html" title="class in org.apache.hadoop.io.nativeio" target="classFrame">NativeIO</A></FONT></TD> </TR> </TABLE> <TABLE BORDER="0" WIDTH="100%" SUMMARY=""> <TR> <TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont"> Enums</FONT>&nbsp; <FONT CLASS="FrameItemFont"> <BR> <A HREF="Errno.html" title="enum in org.apache.hadoop.io.nativeio" target="classFrame">Errno</A></FONT></TD> </TR> </TABLE> <TABLE BORDER="0" WIDTH="100%" SUMMARY=""> <TR> <TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont"> Exceptions</FONT>&nbsp; <FONT CLASS="FrameItemFont"> <BR> <A HREF="NativeIOException.html" title="class in org.apache.hadoop.io.nativeio" target="classFrame">NativeIOException</A></FONT></TD> </TR> </TABLE> </BODY> </HTML>
InMobi/hadoop
docs/api/org/apache/hadoop/io/nativeio/package-frame.html
HTML
apache-2.0
1,525
Arkivo::Engine.routes.draw do namespace :api, defaults: { format: :json } do resources :items, except: :index end end
psu-stewardship/hydra-arkivo
config/routes.rb
Ruby
apache-2.0
126
/** * 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. */ package org.jboss.arquillian.warp.utils; import java.io.UnsupportedEncodingException; import org.apache.commons.codec.DecoderException; /** * Abstract superclass for Base-N encoders and decoders. * * <p> * This class is not thread-safe. Each thread should use its own instance. * </p> */ public abstract class BaseNCodec { /** * MIME chunk size per RFC 2045 section 6.8. * * <p> * The {@value} character limit does not count the trailing CRLF, but counts all other characters, including any equal * signs. * </p> * * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 6.8</a> */ public static final int MIME_CHUNK_SIZE = 76; /** * PEM chunk size per RFC 1421 section 4.3.2.4. * * <p> * The {@value} character limit does not count the trailing CRLF, but counts all other characters, including any equal * signs. * </p> * * @see <a href="http://tools.ietf.org/html/rfc1421">RFC 1421 section 4.3.2.4</a> */ public static final int PEM_CHUNK_SIZE = 64; private static final int DEFAULT_BUFFER_RESIZE_FACTOR = 2; /** * Defines the default buffer size - currently {@value} - must be large enough for at least one encoded block+separator */ private static final int DEFAULT_BUFFER_SIZE = 8192; /** Mask used to extract 8 bits, used in decoding bytes */ protected static final int MASK_8BITS = 0xff; /** * Byte used to pad output. */ protected static final byte PAD_DEFAULT = '='; // Allow static access to default protected final byte PAD = PAD_DEFAULT; // instance variable just in case it needs to vary later /** Number of bytes in each full block of unencoded data, e.g. 4 for Base64 and 5 for Base32 */ private final int unencodedBlockSize; /** Number of bytes in each full block of encoded data, e.g. 3 for Base64 and 8 for Base32 */ private final int encodedBlockSize; /** * Chunksize for encoding. Not used when decoding. A value of zero or less implies no chunking of the encoded data. Rounded * down to nearest multiple of encodedBlockSize. */ protected final int lineLength; /** * Size of chunk separator. Not used unless {@link #lineLength} > 0. */ private final int chunkSeparatorLength; /** * Buffer for streaming. */ protected byte[] buffer; /** * Position where next character should be written in the buffer. */ protected int pos; /** * Position where next character should be read from the buffer. */ private int readPos; /** * Boolean flag to indicate the EOF has been reached. Once EOF has been reached, this object becomes useless, and must be * thrown away. */ protected boolean eof; /** * Variable tracks how many characters have been written to the current line. Only used when encoding. We use it to make * sure each encoded line never goes beyond lineLength (if lineLength > 0). */ protected int currentLinePos; /** * Writes to the buffer only occur after every 3/5 reads when encoding, and every 4/8 reads when decoding. This variable * helps track that. */ protected int modulus; /** * Note <code>lineLength</code> is rounded down to the nearest multiple of {@link #encodedBlockSize} If * <code>chunkSeparatorLength</code> is zero, then chunking is disabled. * * @param unencodedBlockSize the size of an unencoded block (e.g. Base64 = 3) * @param encodedBlockSize the size of an encoded block (e.g. Base64 = 4) * @param lineLength if &gt; 0, use chunking with a length <code>lineLength</code> * @param chunkSeparatorLength the chunk separator length, if relevant */ protected BaseNCodec(int unencodedBlockSize, int encodedBlockSize, int lineLength, int chunkSeparatorLength) { this.unencodedBlockSize = unencodedBlockSize; this.encodedBlockSize = encodedBlockSize; this.lineLength = (lineLength > 0 && chunkSeparatorLength > 0) ? (lineLength / encodedBlockSize) * encodedBlockSize : 0; this.chunkSeparatorLength = chunkSeparatorLength; } /** * Returns true if this object has buffered data for reading. * * @return true if there is data still available for reading. */ boolean hasData() { // package protected for access from I/O streams return this.buffer != null; } /** * Returns the amount of buffered data available for reading. * * @return The amount of buffered data available for reading. */ int available() { // package protected for access from I/O streams return buffer != null ? pos - readPos : 0; } /** * Get the default buffer size. Can be overridden. * * @return {@link #DEFAULT_BUFFER_SIZE} */ protected int getDefaultBufferSize() { return DEFAULT_BUFFER_SIZE; } /** Increases our buffer by the {@link #DEFAULT_BUFFER_RESIZE_FACTOR}. */ private void resizeBuffer() { if (buffer == null) { buffer = new byte[getDefaultBufferSize()]; pos = 0; readPos = 0; } else { byte[] b = new byte[buffer.length * DEFAULT_BUFFER_RESIZE_FACTOR]; System.arraycopy(buffer, 0, b, 0, buffer.length); buffer = b; } } /** * Ensure that the buffer has room for <code>size</code> bytes * * @param size minimum spare space required */ protected void ensureBufferSize(int size) { if ((buffer == null) || (buffer.length < pos + size)) { resizeBuffer(); } } /** * Extracts buffered data into the provided byte[] array, starting at position bPos, up to a maximum of bAvail bytes. * Returns how many bytes were actually extracted. * * @param b byte[] array to extract the buffered data into. * @param bPos position in byte[] array to start extraction at. * @param bAvail amount of bytes we're allowed to extract. We may extract fewer (if fewer are available). * @return The number of bytes successfully extracted into the provided byte[] array. */ int readResults(byte[] b, int bPos, int bAvail) { // package protected for access from I/O streams if (buffer != null) { int len = Math.min(available(), bAvail); System.arraycopy(buffer, readPos, b, bPos, len); readPos += len; if (readPos >= pos) { buffer = null; // so hasData() will return false, and this method can return -1 } return len; } return eof ? -1 : 0; } /** * Checks if a byte value is whitespace or not. Whitespace is taken to mean: space, tab, CR, LF * * @param byteToCheck the byte to check * @return true if byte is whitespace, false otherwise */ protected static boolean isWhiteSpace(byte byteToCheck) { switch (byteToCheck) { case ' ': case '\n': case '\r': case '\t': return true; default: return false; } } /** * Resets this object to its initial newly constructed state. */ private void reset() { buffer = null; pos = 0; readPos = 0; currentLinePos = 0; modulus = 0; eof = false; } /** * Encodes an Object using the Base-N algorithm. This method is provided in order to satisfy the requirements of the Encoder * interface, and will throw an IllegalStateException if the supplied object is not of type byte[]. * * @param pObject Object to encode * @return An object (of type byte[]) containing the Base-N encoded data which corresponds to the byte[] supplied. * @throws IllegalStateException if the parameter supplied is not of type byte[] */ public Object encode(Object pObject) { if (!(pObject instanceof byte[])) { throw new IllegalStateException("Parameter supplied to Base-N encode is not a byte[]"); } return encode((byte[]) pObject); } /** * Encodes a byte[] containing binary data, into a String containing characters in the Base-N alphabet. * * @param pArray a byte array containing binary data * @return A String containing only Base-N character data */ public String encodeToString(byte[] pArray) { return newStringUtf8(encode(pArray)); } /** * Decodes an Object using the Base-N algorithm. This method is provided in order to satisfy the requirements of the Decoder * interface, and will throw a DecoderException if the supplied object is not of type byte[] or String. * * @param pObject Object to decode * @return An object (of type byte[]) containing the binary data which corresponds to the byte[] or String supplied. * @throws DecoderException if the parameter supplied is not of type byte[] */ public Object decode(Object pObject) throws IllegalStateException { if (pObject instanceof byte[]) { return decode((byte[]) pObject); } else if (pObject instanceof String) { return decode((String) pObject); } else { throw new IllegalStateException("Parameter supplied to Base-N decode is not a byte[] or a String"); } } /** * Decodes a String containing characters in the Base-N alphabet. * * @param pArray A String containing Base-N character data * @return a byte array containing binary data */ public byte[] decode(String pArray) { return decode(getBytesUtf8(pArray)); } /** * Decodes a byte[] containing characters in the Base-N alphabet. * * @param pArray A byte array containing Base-N character data * @return a byte array containing binary data */ public byte[] decode(byte[] pArray) { reset(); if (pArray == null || pArray.length == 0) { return pArray; } decode(pArray, 0, pArray.length); decode(pArray, 0, -1); // Notify decoder of EOF. byte[] result = new byte[pos]; readResults(result, 0, result.length); return result; } /** * Encodes a byte[] containing binary data, into a byte[] containing characters in the alphabet. * * @param pArray a byte array containing binary data * @return A byte array containing only the basen alphabetic character data */ public byte[] encode(byte[] pArray) { reset(); if (pArray == null || pArray.length == 0) { return pArray; } encode(pArray, 0, pArray.length); encode(pArray, 0, -1); // Notify encoder of EOF. byte[] buf = new byte[pos - readPos]; readResults(buf, 0, buf.length); return buf; } /** * Encodes a byte[] containing binary data, into a String containing characters in the appropriate alphabet. Uses UTF8 * encoding. * * @param pArray a byte array containing binary data * @return String containing only character data in the appropriate alphabet. */ public String encodeAsString(byte[] pArray) { return newStringUtf8(encode(pArray)); } abstract void encode(byte[] pArray, int i, int length); // package protected for access from I/O streams abstract void decode(byte[] pArray, int i, int length); // package protected for access from I/O streams /** * Returns whether or not the <code>octet</code> is in the current alphabet. Does not allow whitespace or pad. * * @param value The value to test * * @return <code>true</code> if the value is defined in the current alphabet, <code>false</code> otherwise. */ protected abstract boolean isInAlphabet(byte value); /** * Tests a given byte array to see if it contains only valid characters within the alphabet. The method optionally treats * whitespace and pad as valid. * * @param arrayOctet byte array to test * @param allowWSPad if <code>true</code>, then whitespace and PAD are also allowed * * @return <code>true</code> if all bytes are valid characters in the alphabet or if the byte array is empty; * <code>false</code>, otherwise */ public boolean isInAlphabet(byte[] arrayOctet, boolean allowWSPad) { for (int i = 0; i < arrayOctet.length; i++) { if (!isInAlphabet(arrayOctet[i]) && (!allowWSPad || (arrayOctet[i] != PAD) && !isWhiteSpace(arrayOctet[i]))) { return false; } } return true; } /** * Tests a given String to see if it contains only valid characters within the alphabet. The method treats whitespace and * PAD as valid. * * @param basen String to test * @return <code>true</code> if all characters in the String are valid characters in the alphabet or if the String is empty; * <code>false</code>, otherwise * @see #isInAlphabet(byte[], boolean) */ public boolean isInAlphabet(String basen) { return isInAlphabet(getBytesUtf8(basen), true); } /** * Tests a given byte array to see if it contains any characters within the alphabet or PAD. * * Intended for use in checking line-ending arrays * * @param arrayOctet byte array to test * @return <code>true</code> if any byte is a valid character in the alphabet or PAD; <code>false</code> otherwise */ protected boolean containsAlphabetOrPad(byte[] arrayOctet) { if (arrayOctet == null) { return false; } for (byte element : arrayOctet) { if (PAD == element || isInAlphabet(element)) { return true; } } return false; } /** * Calculates the amount of space needed to encode the supplied array. * * @param pArray byte[] array which will later be encoded * * @return amount of space needed to encoded the supplied array. Returns a long since a max-len array will require > * Integer.MAX_VALUE */ public long getEncodedLength(byte[] pArray) { // Calculate non-chunked size - rounded up to allow for padding // cast to long is needed to avoid possibility of overflow long len = ((pArray.length + unencodedBlockSize - 1) / unencodedBlockSize) * (long) encodedBlockSize; if (lineLength > 0) { // We're using chunking // Round up to nearest multiple len += ((len + lineLength - 1) / lineLength) * chunkSeparatorLength; } return len; } /** * Constructs a new <code>String</code> by decoding the specified array of bytes using the UTF-8 charset. * * @param bytes The bytes to be decoded into characters * @return A new <code>String</code> decoded from the specified array of bytes using the UTF-8 charset, or <code>null</code> * if the input byte array was <code>null</code>. * @throws IllegalStateException Thrown when a {@link UnsupportedEncodingException} is caught, which should never happen * since the charset is required. */ public static String newStringUtf8(byte[] bytes) { if (bytes == null) { return null; } try { return new String(bytes, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("UTF-8", e); } } /** * Encodes the given string into a sequence of bytes using the UTF-8 charset, storing the result into a new byte array. * * @param string the String to encode, may be <code>null</code> * @return encoded bytes, or <code>null</code> if the input string was <code>null</code> * @throws IllegalStateException Thrown when the charset is missing, which should be never according the the Java * specification. * @see <a href="http://download.oracle.com/javase/1.5.0/docs/api/java/nio/charset/Charset.html">Standard charsets</a> * @see #getBytesUnchecked(String, String) */ public static byte[] getBytesUtf8(String string) { if (string == null) { return null; } try { return string.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("UTF-8", e); } } }
aslakknutsen/arquillian-extension-warp
impl/src/main/java/org/jboss/arquillian/warp/utils/BaseNCodec.java
Java
apache-2.0
17,879
public class Customers { public static string[] allCustomers = {"Peter Parker", "Klark Kent", "Bruce Vayne"}; }
jasarsoft/ipcs-primjeri
IPCS_02/Vjezba 2/company/customers/Customers.cs
C#
apache-2.0
112
# Zygnema gorakhporense Singh SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Chlorophyta/Zygnematophyceae/Zygnematales/Zygnemataceae/Zygnema/Zygnema gorakhporense/README.md
Markdown
apache-2.0
185
package dk.lessismore.nojpa.reflection.db.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Created : with IntelliJ IDEA. * User: seb */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface SearchField { public static final String NULL = ""; public boolean translate() default false; public boolean searchReverse() default false; public float boostFactor() default 3f; public float reverseBoostFactor() default 0.3f; public String dynamicSolrPostName() default NULL; }
NoJPA-LESS-IS-MORE/NoJPA
nojpa_orm/src/main/java/dk/lessismore/nojpa/reflection/db/annotations/SearchField.java
Java
apache-2.0
664
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.hoang.fu; /** * * @author hoangpt */ public class Teacher extends Employee implements ITeacher { Teacher(String name) { this.name = name; } @Override float calculateSalary(){ return 500f; } @Override public int calculateBonus() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public float calculateAllowance() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
hoangphantich/fu.java192x17.1
hoangpt/Assignment_21/src/com/hoang/fu/Teacher.java
Java
apache-2.0
786
// Copyright (c) 1999-2004 Brian Wellington ([email protected]) package org.xbill.DNS; import java.io.*; import java.util.*; import org.xbill.DNS.utils.*; /** * Transaction Signature - this record is automatically generated by the * resolver. TSIG records provide transaction security between the * sender and receiver of a message, using a shared key. * @see org.xbill.DNS.Resolver * @see org.xbill.DNS.TSIG * * @author Brian Wellington */ public class TSIGRecord extends Record { private static final long serialVersionUID = -88820909016649306L; private Name alg; private Date timeSigned; private int fudge; private byte [] signature; private int originalID; private int error; private byte [] other; TSIGRecord() {} Record getObject() { return new TSIGRecord(); } /** * Creates a TSIG Record from the given data. This is normally called by * the TSIG class * @param alg The shared key's algorithm * @param timeSigned The time that this record was generated * @param fudge The fudge factor for time - if the time that the message is * received is not in the range [now - fudge, now + fudge], the signature * fails * @param signature The signature * @param originalID The message ID at the time of its generation * @param error The extended error field. Should be 0 in queries. * @param other The other data field. Currently used only in BADTIME * responses. * @see org.xbill.DNS.TSIG */ public TSIGRecord(Name name, int dclass, long ttl, Name alg, Date timeSigned, int fudge, byte [] signature, int originalID, int error, byte other[]) { super(name, Type.TSIG, dclass, ttl); this.alg = checkName("alg", alg); this.timeSigned = timeSigned; this.fudge = checkU16("fudge", fudge); this.signature = signature; this.originalID = checkU16("originalID", originalID); this.error = checkU16("error", error); this.other = other; } void rrFromWire(DNSInput in) throws IOException { alg = new Name(in); long timeHigh = in.readU16(); long timeLow = in.readU32(); long time = (timeHigh << 32) + timeLow; timeSigned = new Date(time * 1000); fudge = in.readU16(); int sigLen = in.readU16(); signature = in.readByteArray(sigLen); originalID = in.readU16(); error = in.readU16(); int otherLen = in.readU16(); if (otherLen > 0) other = in.readByteArray(otherLen); else other = null; } void rdataFromString(Tokenizer st, Name origin) throws IOException { throw st.exception("no text format defined for TSIG"); } /** Converts rdata to a String */ String rrToString() { StringBuffer sb = new StringBuffer(); sb.append(alg); sb.append(" "); if (Options.check("multiline")) sb.append("(\n\t"); sb.append (timeSigned.getTime() / 1000); sb.append (" "); sb.append (fudge); sb.append (" "); sb.append (signature.length); if (Options.check("multiline")) { sb.append ("\n"); sb.append (base64.formatString(signature, 64, "\t", false)); } else { sb.append (" "); sb.append (base64.toString(signature)); } sb.append (" "); sb.append (Rcode.TSIGstring(error)); sb.append (" "); if (other == null) sb.append (0); else { sb.append (other.length); if (Options.check("multiline")) sb.append("\n\n\n\t"); else sb.append(" "); if (error == Rcode.BADTIME) { if (other.length != 6) { sb.append("<invalid BADTIME other data>"); } else { long time = ((long)(other[0] & 0xFF) << 40) + ((long)(other[1] & 0xFF) << 32) + ((other[2] & 0xFF) << 24) + ((other[3] & 0xFF) << 16) + ((other[4] & 0xFF) << 8) + ((other[5] & 0xFF) ); sb.append("<server time: "); sb.append(new Date(time * 1000)); sb.append(">"); } } else { sb.append("<"); sb.append(base64.toString(other)); sb.append(">"); } } if (Options.check("multiline")) sb.append(" )"); return sb.toString(); } /** Returns the shared key's algorithm */ public Name getAlgorithm() { return alg; } /** Returns the time that this record was generated */ public Date getTimeSigned() { return timeSigned; } /** Returns the time fudge factor */ public int getFudge() { return fudge; } /** Returns the signature */ public byte [] getSignature() { return signature; } /** Returns the original message ID */ public int getOriginalID() { return originalID; } /** Returns the extended error */ public int getError() { return error; } /** Returns the other data */ public byte [] getOther() { return other; } void rrToWire(DNSOutput out, Compression c, boolean canonical) { alg.toWire(out, null, canonical); long time = timeSigned.getTime() / 1000; int timeHigh = (int) (time >> 32); long timeLow = (time & 0xFFFFFFFFL); out.writeU16(timeHigh); out.writeU32(timeLow); out.writeU16(fudge); out.writeU16(signature.length); out.writeByteArray(signature); out.writeU16(originalID); out.writeU16(error); if (other != null) { out.writeU16(other.length); out.writeByteArray(other); } else out.writeU16(0); } }
msdx/AndroidPNClient
androidpn/src/main/java/org/xbill/DNS/TSIGRecord.java
Java
apache-2.0
4,956
-- Users delete from user where id <= 6; insert into user (id,password,user_name, email, role) values (6,'$2a$08$rWw15tM4D8JGNkoSnosvUOWktluv1CnxCZfJslvHWaiFSaSOpnYZS','boisterous', '[email protected]', 'USER'); insert into user (id,password,user_name, email, role) values (5,'$2a$08$2/f6i7QzmdvM0wVDghFdkOUPtUA66SSaOGCNZj8uEczUodB49ZpIS','traumatic', '[email protected]', 'USER'); insert into user (id,password,user_name, email, role) values (4,'$2a$08$rxpMCbm7zfyQR5GVaah1duKOyoGDPCgsN1ruXkWgUagbfyyXl7J/a','chopchop', '[email protected]', 'USER'); insert into user (id,password,user_name, email, role) values (3,'$2a$08$5MBR1BRsenDZSKyQoofETubRmvH3GIxgDs3LTZlCFMjfftFn3HM9K','krisztmas', '[email protected]', 'USER'); insert into user (id,password,user_name, email, role) values (2,'$2a$08$P2LGQAUIk6TjQcLE533Ec.5EFTwUPJOmt1LsDKmS9PbJxW6tKGz8u','pivanyi', '[email protected]', 'USER'); insert into user (id,password,user_name, email, role) values (1,'$2a$08$0E.G3Tt9BsDtapmmc1pgruh4myKCy6ySEi//ptScWjRmres1U0txi','falatka', '[email protected]', 'USER'); -- Boards delete from board where id <= 2; insert into board (id,title) values (1,'Test board 1'); insert into board (id,title) values (2,'Test board 2'); -- User-Board delete from user_board_relation_table where user_id = 1; insert into user_board_relation_table (user_id,board_id) values (1,1); insert into user_board_relation_table (user_id,board_id) values (1,2); -- Columns delete from board_column where id <= 4; insert into board_column (id,title,board_id) values (1,'TODO',1); insert into board_column (id,title,board_id) values (2,'IN DEV',1); insert into board_column (id,title,board_id) values (3,'QA',1); insert into board_column (id,title,board_id) values (4,'DONE',1); -- Cards delete from card where id <= 8; insert into card (id,description,title,column_id) values (1,'Sample description for task 1','Task 1',1); insert into card (id,description,title,column_id) values (2,'Sample description for task 2','Task 2',1); insert into card (id,description,title,column_id) values (3,'Sample description for task 3','Task 3',2); insert into card (id,description,title,column_id) values (4,'Sample description for task 4','Task 4',3); insert into card (id,description,title,column_id) values (5,'Sample description for task 5','Task 5',3); insert into card (id,description,title,column_id) values (6,'Sample description for task 6','Task 6',4); insert into card (id,description,title,column_id) values (7,'Sample description for task 7','Task 7',4); insert into card (id,description,title,column_id) values (8,'Sample description for task 8','Task 8',4); insert into comment (id,content,created_time,user_id,card_id) values (1,"Some birthday content",'1993-12-03 12:30',1,1); insert into comment (id,content,created_time,user_id,card_id) values (2,"Some birthday content",'1994-08-20 12:30',2,1); insert into comment (id,content,created_time,user_id,card_id) values (3,"Some birthday content",'1994-08-19 06:30',3,1); -- User-Card delete from user_card_relation_table where user_id = 1; insert into user_card_relation_table (card_id,user_id) values (3,1); insert into user_card_relation_table (card_id,user_id) values (4,1); insert into user_card_relation_table (card_id,user_id) values (7,1);
NEU-2016/NEUban
persistence/src/main/resources/data-mysql.sql
SQL
apache-2.0
3,303
package app.monitor.job; import core.framework.internal.log.LogManager; import core.framework.json.JSON; import core.framework.kafka.MessagePublisher; import core.framework.log.message.StatMessage; import core.framework.scheduler.Job; import core.framework.scheduler.JobContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.time.Duration; import java.time.Instant; import java.time.ZonedDateTime; import java.util.List; import java.util.Map; /** * @author neo */ public class KubeMonitorJob implements Job { public final MessagePublisher<StatMessage> publisher; public final KubeClient kubeClient; public final List<String> namespaces; private final Logger logger = LoggerFactory.getLogger(KubeMonitorJob.class); public KubeMonitorJob(List<String> namespaces, KubeClient kubeClient, MessagePublisher<StatMessage> publisher) { this.publisher = publisher; this.kubeClient = kubeClient; this.namespaces = namespaces; } @Override public void execute(JobContext context) { try { var now = ZonedDateTime.now(); for (String namespace : namespaces) { KubePodList pods = kubeClient.listPods(namespace); for (KubePodList.Pod pod : pods.items) { String errorMessage = check(pod, now); if (errorMessage != null) { publishPodFailure(pod, errorMessage); } } } } catch (Throwable e) { logger.error(e.getMessage(), e); publisher.publish(StatMessageFactory.failedToCollect(LogManager.APP_NAME, null, e)); } } String check(KubePodList.Pod pod, ZonedDateTime now) { if (pod.metadata.deletionTimestamp != null) { Duration elapsed = Duration.between(pod.metadata.deletionTimestamp, now); if (elapsed.toSeconds() >= 300) { return "pod is still in deletion, elapsed=" + elapsed; } return null; } String phase = pod.status.phase; if ("Succeeded".equals(phase)) return null; // terminated if ("Failed".equals(phase) || "Unknown".equals(phase)) return "unexpected pod phase, phase=" + phase; if ("Pending".equals(phase)) { // newly created pod may not have container status yet, containerStatuses is initialized as empty for (KubePodList.ContainerStatus status : pod.status.containerStatuses) { if (status.state.waiting != null && "ImagePullBackOff".equals(status.state.waiting.reason)) { return "ImagePullBackOff: " + status.state.waiting.message; } } // for unschedulable pod for (KubePodList.PodCondition condition : pod.status.conditions) { if ("PodScheduled".equals(condition.type) && "False".equals(condition.status) && Duration.between(condition.lastTransitionTime, now).toSeconds() >= 300) { return condition.reason + ": " + condition.message; } } } if ("Running".equals(phase)) { boolean ready = true; for (KubePodList.ContainerStatus status : pod.status.containerStatuses) { if (status.state.waiting != null && "CrashLoopBackOff".equals(status.state.waiting.reason)) { return "CrashLoopBackOff: " + status.state.waiting.message; } boolean containerReady = Boolean.TRUE.equals(status.ready); if (!containerReady && status.lastState != null && status.lastState.terminated != null) { var terminated = status.lastState.terminated; return "pod was terminated, reason=" + terminated.reason + ", exitCode=" + terminated.exitCode; } if (!containerReady) { ready = false; } } if (ready) return null; // all running, all ready } ZonedDateTime startTime = pod.status.startTime != null ? pod.status.startTime : pod.metadata.creationTimestamp; // startTime may not be populated yet if pod is just created Duration elapsed = Duration.between(startTime, now); if (elapsed.toSeconds() >= 300) { // can be: 1) took long to be ready after start, or 2) readiness check failed in the middle run return "pod is not in ready state, uptime=" + elapsed; } return null; } private void publishPodFailure(KubePodList.Pod pod, String errorMessage) { var now = Instant.now(); var message = new StatMessage(); message.id = LogManager.ID_GENERATOR.next(now); message.date = now; message.result = "ERROR"; message.app = pod.metadata.labels.getOrDefault("app", pod.metadata.name); message.host = pod.metadata.name; message.errorCode = "POD_FAILURE"; message.errorMessage = errorMessage; message.info = Map.of("pod", JSON.toJSON(pod)); publisher.publish(message); } }
neowu/core-ng-project
ext/monitor/src/main/java/app/monitor/job/KubeMonitorJob.java
Java
apache-2.0
5,150
/* * 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 {AfterViewInit, ElementRef, EventEmitter, Injector, OnDestroy, OnInit, Output} from '@angular/core'; import {AbstractComponent} from '@common/component/abstract.component'; import {Field, Rule} from '@domain/data-preparation/pr-dataset'; export abstract class EditRuleComponent extends AbstractComponent implements OnInit, AfterViewInit, OnDestroy { /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Private Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Protected Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ public isShow: boolean = false; public mode: string = 'APPEND'; public ruleVO: Rule; public colDescs: any; public fields: Field[]; public selectedFields: Field[] = []; public forceFormula: string = ''; public forceCondition: string = ''; @Output() public onEvent: EventEmitter<any> = new EventEmitter(); /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Constructor |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ // 생성자 protected constructor( protected elementRef: ElementRef, protected injector: Injector) { super(elementRef, injector); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Override Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * 컴포넌트 초기 실행 */ public ngOnInit() { super.ngOnInit(); } // function - ngOnInit /** * 화면 초기화 */ public ngAfterViewInit() { super.ngAfterViewInit(); } // function - ngAfterViewInit /** * 컴포넌트 제거 */ public ngOnDestroy() { super.ngOnDestroy(); } // function - ngOnDestroy /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Method - API |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ public init(fields: Field[], selectedFields: Field[], data?: { ruleString?: string, jsonRuleString: any }) { this.fields = fields; this.selectedFields = selectedFields; if (!this.isNullOrUndefined(data)) { this.parsingRuleString(data); } this.beforeShowComp(); this.isShow = true; this.safelyDetectChanges(); this.afterShowComp(); this.safelyDetectChanges(); } // function - init public setValue(key: string, value: any) { Object.keys(this).some(item => { if (key === item && 'function' !== typeof this[key]) { this[key] = value; return true; } else { return false; } }); this.safelyDetectChanges(); } // function - setValue /** * Apply formula using Advanced formula popup * @param {{command: string, formula: string}} data */ public doneInputFormula(data: { command: string, formula: string }) { if (data.command === 'setCondition') { this.setValue('forceCondition', data.formula); } else { this.setValue('forceFormula', data.formula); } } /** * Returns value of variable name equals the key * @param {string} key * @returns {string} */ public getValue(key: string): string { let returnValue: string = undefined; if (!this.isNullOrUndefined(this[key])) { returnValue = this[key]; } this.safelyDetectChanges(); return returnValue; } // function - setValue /** * Rule 형식 정의 및 반환 */ public abstract getRuleData(); /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Protected Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * 컴포넌트 표시 전 실행 * @protected */ protected abstract beforeShowComp(); /** * 컴포넌트 표시 후 실행 * @protected */ protected abstract afterShowComp(); /** * rule string 을 분석한다. * @param ruleString * @protected */ protected abstract parsingRuleString(ruleString: any); protected getColumnNamesInArray(fields: Field[], isWrap: boolean = false): string[] { return fields.map((item) => { if (isWrap) { return '`' + item.name + '`' } else { return item.name } }); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Private Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ }
metatron-app/metatron-discovery
discovery-frontend/src/app/data-preparation/dataflow/dataflow-detail/component/edit-dataflow-rule/edit-rule/edit-rule.component.ts
TypeScript
apache-2.0
5,051
package mahjong type Hand []Pai func remove(list []Pai, p Pai) []Pai { var result []Pai removed := false for _, e := range list { if e == p && !removed { removed = true } else { result = append(result, e) } } return result } func contain(list []Pai, p Pai) bool { for _, a := range list { if a == p { return true } } return false } func contain2(list []Pai, p Pai) bool { count := 0 for _, a := range list { if a == p { count += 1 } } return count >= 2 } func createCandidates(list []Pai, cand [][][]Pai) [][][]Pai { if len(list) <= 0 { return cand } current := list[0] remain := list[1:] nextOne := current + 1 nextTwo := current + 2 if current.IsNumber() { if current.Suit() == nextOne.Suit() && current.Suit() == nextTwo.Suit() && contain(remain, nextOne) && contain(remain, nextTwo) { idx := len(cand) - 1 tmp := make([][]Pai, len(cand[idx])) copy(tmp, cand[idx]) cand[idx] = append(cand[idx], []Pai{current, nextOne, nextTwo}) _remain := remove(remove(remain, nextOne), nextTwo) cand = createCandidates(_remain, cand) cand = append(cand, tmp) } if current.Suit() == nextOne.Suit() && contain(remain, nextOne) { idx := len(cand) - 1 tmp := make([][]Pai, len(cand[idx])) copy(tmp, cand[idx]) cand[len(cand)-1] = append(cand[len(cand)-1], []Pai{current, nextOne}) _remain := remove(remain, nextOne) cand = createCandidates(_remain, cand) cand = append(cand, tmp) } if current.Suit() == nextTwo.Suit() && contain(remain, nextTwo) { idx := len(cand) - 1 tmp := make([][]Pai, len(cand[idx])) copy(tmp, cand[idx]) cand[len(cand)-1] = append(cand[len(cand)-1], []Pai{current, nextTwo}) _remain := remove(remain, nextTwo) cand = createCandidates(_remain, cand) cand = append(cand, tmp) } } if contain2(remain, current) { idx := len(cand) - 1 tmp := make([][]Pai, len(cand[idx])) copy(tmp, cand[idx]) cand[len(cand)-1] = append(cand[len(cand)-1], []Pai{current, current, current}) _remain := remove(remove(remain, current), current) cand = createCandidates(_remain, cand) cand = append(cand, tmp) } if contain(remain, current) { idx := len(cand) - 1 tmp := make([][]Pai, len(cand[idx])) copy(tmp, cand[idx]) cand[len(cand)-1] = append(cand[len(cand)-1], []Pai{current, current}) _remain := remove(remain, current) cand = createCandidates(_remain, cand) cand = append(cand, tmp) } cand[len(cand)-1] = append(cand[len(cand)-1], []Pai{current}) return createCandidates(remain, cand) } func isUnique(list []Pai) bool { result := []Pai{} for _, p := range list { if contain(result, p) { // nothing to do } else { result = append(result, p) } } return len(list) == len(result) } func isSevenPairs(list [][]Pai) bool { if len(list) != 7 { return false } stack := []Pai{} for _, pair := range list { if len(pair) == 2 && pair[0] != pair[1] { return false } stack = append(stack, pair[0]) } return isUnique(stack) } func isThirteenOrphans(list [][]Pai) bool { if len(list) == 12 || len(list) == 13 { for _, pair := range list { for _, pai := range pair { if !pai.IsOrphan() { return false } } } return true } return false } func (hand *Hand) IsTenpai() bool { _hand := *hand cand := [][][]Pai{[][]Pai{}} cand = createCandidates(_hand, cand) for _, a := range cand { // regular type if len(a) == 5 { return true } // seven pairs if isSevenPairs(a) { return true } if isThirteenOrphans(a) { return true } } return false }
tanaka51/tenpai-wakaru-man
mahjong/hand.go
GO
apache-2.0
3,584
/* * 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. */ package org.apache.geode.internal.logging.log4j; import static org.apache.geode.test.util.ResourceUtils.createFileFromResource; import static org.apache.geode.test.util.ResourceUtils.getResource; import static org.assertj.core.api.Assertions.assertThat; import java.net.URL; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.LogEvent; import org.apache.logging.log4j.junit.LoggerContextRule; import org.apache.logging.log4j.test.appender.ListAppender; import org.junit.Before; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.rules.TemporaryFolder; import org.apache.geode.internal.logging.LogService; import org.apache.geode.test.junit.categories.LoggingTest; @Category(LoggingTest.class) public class GemfireVerboseMarkerFilterAcceptIntegrationTest { private static final String APPENDER_NAME = "LIST"; private static String configFilePath; private Logger logger; private String logMessage; private ListAppender listAppender; @ClassRule public static TemporaryFolder temporaryFolder = new TemporaryFolder(); @Rule public LoggerContextRule loggerContextRule = new LoggerContextRule(configFilePath); @BeforeClass public static void setUpLogConfigFile() throws Exception { String configFileName = GemfireVerboseMarkerFilterAcceptIntegrationTest.class.getSimpleName() + "_log4j2.xml"; URL resource = getResource(configFileName); configFilePath = createFileFromResource(resource, temporaryFolder.getRoot(), configFileName) .getAbsolutePath(); } @Before public void setUp() throws Exception { logger = LogService.getLogger(); logMessage = "this is a log statement"; assertThat(LogService.isUsingGemFireDefaultConfig()).as(LogService.getConfigurationInfo()) .isFalse(); listAppender = loggerContextRule.getListAppender(APPENDER_NAME); } @Test public void gemfireVerboseShouldLogIfGemfireVerboseIsAccept() { logger.info(LogMarker.GEMFIRE_VERBOSE, logMessage); LogEvent logEvent = listAppender.getEvents().get(0); assertThat(logEvent.getLoggerName()).isEqualTo(logger.getName()); assertThat(logEvent.getLevel()).isEqualTo(Level.INFO); assertThat(logEvent.getMessage().getFormattedMessage()).isEqualTo(logMessage); } @Test public void geodeVerboseShouldLogIfGemfireVerboseIsAccept() { logger.info(LogMarker.GEODE_VERBOSE, logMessage); LogEvent logEvent = listAppender.getEvents().get(0); assertThat(logEvent.getLoggerName()).isEqualTo(logger.getName()); assertThat(logEvent.getLevel()).isEqualTo(Level.INFO); assertThat(logEvent.getMessage().getFormattedMessage()).isEqualTo(logMessage); } }
pdxrunner/geode
geode-core/src/integrationTest/java/org/apache/geode/internal/logging/log4j/GemfireVerboseMarkerFilterAcceptIntegrationTest.java
Java
apache-2.0
3,615
/* ** Stack.cpp for cpp_abstractvm in /var/projects/cpp_abstractvm/Stack.cpp ** ** Made by kevin labbe ** Login <[email protected]> ** ** Started on Mar 1, 2014 2:15:13 AM 2014 kevin labbe ** Last update Mar 1, 2014 2:15:13 AM 2014 kevin labbe */ #include "EmptyStackException.hpp" #include "AssertFailedException.hpp" #include "WrongParameterException.hpp" #include "Stack.hpp" namespace Arithmetic { Stack::Stack() { _funcs["add"] = &Stack::add; _funcs["sub"] = &Stack::sub; _funcs["mul"] = &Stack::mul; _funcs["div"] = &Stack::div; _funcs["mod"] = &Stack::mod; _funcs["pop"] = &Stack::pop; _funcs["dump"] = &Stack::dump; _funcs["print"] = &Stack::print; } Stack::~Stack() { } void Stack::execFunc(const std::string& name) { if (_funcs[name.c_str()]) (this->*_funcs[name.c_str()])(); } void Stack::push(IOperand* op) { _stack.push_front(op); } void Stack::pop() { if (_stack.empty()) throw Exception::EmptyStackException("pop"); delete _stack.front(); _stack.pop_front(); } void Stack::assert(IOperand* op) { if (_stack.empty()) throw Exception::AssertFailedException("Stack empty"); if (_stack.front()->getPrecision() != op->getPrecision() || _stack.front()->getType() != op->getType() || _stack.front()->toString() != op->toString()) throw Exception::AssertFailedException("Operand different at the top of the stack"); } void Stack::dump() { for (std::deque<IOperand*>::iterator it = _stack.begin(); it != _stack.end(); it++) std::cout << (*it)->toString() << std::endl; } void Stack::print() { std::stringstream stream; char chr; int nbr; if (_stack.empty()) throw Exception::EmptyStackException("print"); if (_stack.front()->getType() != INT8) throw Exception::WrongParameterException("print expects an int8 at the top of the stack"); stream << _stack.front()->toString(); stream >> nbr; chr = nbr; std::cout << chr << std::endl; } void Stack::add() { _loadOperands(); _pushResult(*_op1 + *_op2); } void Stack::sub() { _loadOperands(); _pushResult(*_op1 - *_op2); } void Stack::mul() { _loadOperands(); _pushResult(*_op1 * *_op2); } void Stack::div() { _loadOperands(); _pushResult(*_op1 / *_op2); } void Stack::mod() { _loadOperands(); _pushResult(*_op1 % *_op2); } void Stack::_loadOperands() { if (_stack.size() < 2) throw Exception::EmptyStackException("Calc"); _op1 = _stack.front(); _stack.pop_front(); _op2 = _stack.front(); _stack.pop_front(); } void Stack::_pushResult(IOperand* result) { _stack.push_front(result); delete _op1; delete _op2; } } /* namespace Arithmetic */
Kael95/Epitech
Virtual Machine/src/Arithmetic/Stack.cpp
C++
apache-2.0
2,906
# Di Roccia | Di Luce Website of the exibition [Di Roccia | Di Luce](http://www.dirocciadiluce.it) ## Credits * Theme by [Grayscale](http://startbootstrap.com/template-overviews/grayscale/) * Gallery by [Bootstrap Lightbox](http://ashleydw.github.io/lightbox/)
pbmolini/drdl
README.md
Markdown
apache-2.0
263
# Tomodon Rafinesque, 1838 GENUS #### Status ACCEPTED #### According to IRMNG Homonym List #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Amaryllidaceae/Tomodon/README.md
Markdown
apache-2.0
159
# Misgomyces perigonae Thaxt. SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in Mem. Amer. Acad. Arts 16: 294 (1931) #### Original name Misgomyces perigonae Thaxt. ### Remarks null
mdoering/backbone
life/Fungi/Ascomycota/Laboulbeniomycetes/Laboulbeniales/Laboulbeniaceae/Misgomyces/Misgomyces perigonae/README.md
Markdown
apache-2.0
215
# Tilletiopsis Derx, 1948 GENUS #### Status ACCEPTED #### According to Interim Register of Marine and Nonmarine Genera #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Fungi/Basidiomycota/Exobasidiomycetes/Tilletiopsis/README.md
Markdown
apache-2.0
187
# Oleispira Yakimov, Giuliano, Gentile, Crisafi, Chernikova, Abraham, Lunsdorf, Timmis & Golyshin, 2003 GENUS #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Bacteria/Proteobacteria/Gammaproteobacteria/Oceanospirillales/Oceanospirillaceae/Oleispira/README.md
Markdown
apache-2.0
257
# Solidago caesia var. paniculata A.Gray VARIETY #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Solidago/Solidago caesia/ Syn. Solidago caesia paniculata/README.md
Markdown
apache-2.0
195
# Oncocalyx glabratus (Engl.) M.G.Gilbert SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Santalales/Loranthaceae/Oncocalyx/Oncocalyx glabratus/README.md
Markdown
apache-2.0
189
# Listrostachys whytei Rolfe SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Cyrtorchis/Cyrtorchis arcuata/ Syn. Listrostachys whytei/README.md
Markdown
apache-2.0
183
import { Upload } from './../models/upload/upload.model'; import { SUPController } from './sup.server.controller'; const yellow = '\x1b[33m%s\x1b[0m: '; export class SUP { constructor(private io: SocketIOClient.Manager) { } registerIO() { this.io.on('connection', (socket: SocketIOClient.Socket) => { console.log(yellow, 'Socket connected!'); socket.on('NextChunk', (data) => { console.log(yellow, 'Receiving data.'); SUPController.nextChunk(data, socket); }); socket.on('NextFile', (data) => { console.log(yellow, 'Receiving next File.'); SUPController.nextFile(data, socket); }); }); } static handshake(data, cb): void { SUPController.handshake(data, cb); } static pause(data, cb): void { SUPController.pause(data, cb); } static continue(data, cb): void { SUPController.continue(data, cb); } static abort(data, cb): void { SUPController.abort(data, cb); } }
Stejnar/compressor-angular2
src/server/protocols/sup.server.protocol.ts
TypeScript
apache-2.0
1,052
package com.yueny.demo.job.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.yueny.demo.common.example.bo.ModifyDemoBo; import com.yueny.demo.common.example.service.IDataPrecipitationService; import lombok.extern.slf4j.Slf4j; /** * @author yueny09 <[email protected]> * * @DATE 2016年2月16日 下午8:23:11 * */ @Controller @Slf4j public class DemoController { @Autowired private IDataPrecipitationService dataPrecipitationService; /** * */ @RequestMapping(value = { "/", "welcome" }, method = RequestMethod.GET) @ResponseBody public List<ModifyDemoBo> bar() { try { return dataPrecipitationService.queryAll(); } catch (final Exception e) { log.error("exception:", e); } return null; } @RequestMapping(value = "/healthy", method = RequestMethod.GET) @ResponseBody public String healthy() { return "OK"; } }
yueny/pra
job/job_elastic/src/main/java/com/yueny/demo/job/controller/DemoController.java
Java
apache-2.0
1,201
/* * Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. * * 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. */ #pragma once #include "plugin_common.hpp" #include "serialize.hpp" #include "onnx2trt_common.hpp" #include <NvInferPlugin.h> #include <memory> #include <vector> namespace onnx2trt { // A convenient base class for plugins. Provides default implementations of // some methods. // Adapts a plugin so that its type is automatically serialized, enabling it // to be identified when deserializing. class Plugin : public nvinfer1::IPluginExt, public IOwnable { public: virtual const char* getPluginType() const = 0; nvinfer1::Dims const& getInputDims(int index) const { return _input_dims.at(index); } size_t getMaxBatchSize() const { return _max_batch_size; } nvinfer1::DataType getDataType() const { return _data_type; } nvinfer1::PluginFormat getDataFormat() const { return _data_format; } size_t getWorkspaceSize(int) const override { return 0; } int initialize() override { return 0;} void terminate() override {} bool supportsFormat(nvinfer1::DataType type, nvinfer1::PluginFormat format) const override; void configureWithFormat(const nvinfer1::Dims* inputDims, int nbInputs, const nvinfer1::Dims* outputDims, int nbOutputs, nvinfer1::DataType type, nvinfer1::PluginFormat format, int maxBatchSize) override; void destroy() override { delete this; } protected: void deserializeBase(void const*& serialData, size_t& serialLength); size_t getBaseSerializationSize(); void serializeBase(void*& buffer); std::vector<nvinfer1::Dims> _input_dims; size_t _max_batch_size; nvinfer1::DataType _data_type; nvinfer1::PluginFormat _data_format; virtual ~Plugin() {} }; class PluginAdapter : public Plugin { protected: nvinfer1::IPlugin* _plugin; nvinfer1::IPluginExt* _ext; public: PluginAdapter(nvinfer1::IPlugin* plugin) : _plugin(plugin), _ext(dynamic_cast<IPluginExt*>(plugin)) {} virtual int getNbOutputs() const override; virtual nvinfer1::Dims getOutputDimensions(int index, const nvinfer1::Dims *inputDims, int nbInputs) override ; virtual void serialize(void* buffer) override; virtual size_t getSerializationSize() override; virtual int initialize() override; virtual void terminate() override; virtual bool supportsFormat(nvinfer1::DataType type, nvinfer1::PluginFormat format) const override; virtual void configureWithFormat(const nvinfer1::Dims *inputDims, int nbInputs, const nvinfer1::Dims *outputDims, int nbOutputs, nvinfer1::DataType type, nvinfer1::PluginFormat format, int maxBatchSize); virtual size_t getWorkspaceSize(int maxBatchSize) const override; virtual int enqueue(int batchSize, const void *const *inputs, void **outputs, void *workspace, cudaStream_t stream) override; }; // This makes a plugin compatible with onnx2trt::PluginFactory by serializing // its plugin type. class TypeSerializingPlugin : public PluginAdapter { UniqueOwnable _owned_plugin; Plugin* _plugin; public: TypeSerializingPlugin(Plugin* plugin) : PluginAdapter(plugin), _owned_plugin(plugin), _plugin(plugin) {} void serialize(void* buffer) override { const char* plugin_type = _plugin->getPluginType(); serialize_value(&buffer, (const char*)REGISTERABLE_PLUGIN_MAGIC_STRING); serialize_value(&buffer, plugin_type); return _plugin->serialize(buffer); } size_t getSerializationSize() override { const char* plugin_type = _plugin->getPluginType(); // Note: +1 for NULL-terminated string return (sizeof(REGISTERABLE_PLUGIN_MAGIC_STRING) + 1 + strlen(plugin_type) + _plugin->getSerializationSize()); } const char* getPluginType() const override { return _plugin->getPluginType(); } void destroy() override { delete this; } }; // Adapts nvinfer1::plugin::INvPlugin into onnx2trt::Plugin // (This enables existing NV plugins to be used in this plugin infrastructure) class NvPlugin : public PluginAdapter { nvinfer1::plugin::INvPlugin* _plugin; public: NvPlugin(nvinfer1::plugin::INvPlugin* plugin) : PluginAdapter(plugin), _plugin(plugin) {} virtual const char* getPluginType() const override; virtual void destroy() override; }; } // namespace onnx2trt
mlperf/training_results_v0.6
Fujitsu/benchmarks/resnet/implementations/mxnet/3rdparty/onnx-tensorrt/plugin.hpp
C++
apache-2.0
5,795
<html> <head></head> <body> <!-- output should be the same in Client/Server rendering --> <div class="dotvvm-upload" data-bind="with: Files"> <span class="dotvvm-upload-button" data-bind="visible: !IsBusy()"> <a href="javascript:;" onclick="dotvvm.fileUpload.showUploadDialog(this); return false;">Upload</a> </span> <input data-bind="dotvvm-FileUpload: {&quot;url&quot;:&quot;/dotvvmFileUpload?multiple=true&quot;}" multiple="multiple" style="display:none" type="file"> <span class="dotvvm-upload-files" data-bind="html: dotvvm.globalize.format(&quot;{0} files&quot;, Files().length)"></span> <span class="dotvvm-upload-progress-wrapper" data-bind="visible: IsBusy"> <span class="dotvvm-upload-progress" data-bind="style: { 'width': (Progress() == -1 ? '50' : Progress()) + '%' }"></span> </span> <span class="dotvvm-upload-result" data-bind="html: Error() ? &quot;Error occurred.&quot; : &quot;The files were uploaded successfully.&quot;, attr: { title: Error }, css: { 'dotvvm-upload-result-success': !Error(), 'dotvvm-upload-result-error': Error }, visible: !IsBusy() &amp;&amp; Files().length > 0"></span> </div> </body> </html>
riganti/dotvvm
src/Tests/ControlTests/testoutputs/SimpleControlTests.FileUpload.html
HTML
apache-2.0
1,175
--- layout: base title: 'Statistics of root in UD_Kurmanji-MG' udver: '2' --- ## Treebank Statistics: UD_Kurmanji-MG: Relations: `root` This relation is universal. 754 nodes (7%) are attached to their parents as `root`. 754 instances of `root` (100%) are left-to-right (parent precedes child). Average distance between parent and child is 7.41246684350133. The following 12 pairs of parts of speech are connected with `root`: -<tt><a href="kmr_mg-pos-VERB.html">VERB</a></tt> (490; 65% instances), -<tt><a href="kmr_mg-pos-NOUN.html">NOUN</a></tt> (120; 16% instances), -<tt><a href="kmr_mg-pos-PROPN.html">PROPN</a></tt> (44; 6% instances), -<tt><a href="kmr_mg-pos-AUX.html">AUX</a></tt> (41; 5% instances), -<tt><a href="kmr_mg-pos-ADJ.html">ADJ</a></tt> (31; 4% instances), -<tt><a href="kmr_mg-pos-NUM.html">NUM</a></tt> (13; 2% instances), -<tt><a href="kmr_mg-pos-PRON.html">PRON</a></tt> (8; 1% instances), -<tt><a href="kmr_mg-pos-ADP.html">ADP</a></tt> (2; 0% instances), -<tt><a href="kmr_mg-pos-ADV.html">ADV</a></tt> (2; 0% instances), -<tt><a href="kmr_mg-pos-CCONJ.html">CCONJ</a></tt> (1; 0% instances), -<tt><a href="kmr_mg-pos-INTJ.html">INTJ</a></tt> (1; 0% instances), -<tt><a href="kmr_mg-pos-SCONJ.html">SCONJ</a></tt> (1; 0% instances). ~~~ conllu # visual-style 6 bgColor:blue # visual-style 6 fgColor:white # visual-style 0 bgColor:blue # visual-style 0 fgColor:white # visual-style 0 6 root color:blue 1 Bi bi ADP pr AdpType=Prep 2 case _ _ 2 spêdê spêde NOUN n Case=Acc|Gender=Fem|Number=Sing|PronType=Ind 6 nmod _ _ 3 ve ve ADP post AdpType=Post 2 case _ _ 4 ez ez PRON prn Case=Nom|Gender=Fem,Masc|Number=Sing|Person=1|PronType=Prs 6 nsubj _ _ 5 hişyar hişyar X x _ 6 dep _ _ 6 bû bûn VERB vblex Tense=Past|VerbForm=Part 0 root _ _ 7 bûm bûn AUX vaux Mood=Ind|Number=Sing|Person=3|Tense=Past|VerbForm=Fin 6 aux _ SpaceAfter=No 8 . . PUNCT sent _ 6 punct _ _ ~~~ ~~~ conllu # visual-style 1 bgColor:blue # visual-style 1 fgColor:white # visual-style 0 bgColor:blue # visual-style 0 fgColor:white # visual-style 0 1 root color:blue 1 Meheke meh NOUN n Case=Con|Gender=Fem|Number=Sing|PronType=Ind 0 root _ _ 2 Nîsanê nîsan NOUN n Case=Acc|Definite=Def|Gender=Fem|Number=Sing 1 nmod:poss _ _ 3 bû bûn AUX vbcop Mood=Ind|Number=Sing|Person=3|Tense=Past|VerbForm=Fin 1 cop _ SpaceAfter=No 4 . . PUNCT sent _ 1 punct _ _ ~~~ ~~~ conllu # visual-style 1 bgColor:blue # visual-style 1 fgColor:white # visual-style 0 bgColor:blue # visual-style 0 fgColor:white # visual-style 0 1 root color:blue 1 Holmes Holmes PROPN np Case=Nom|Gender=Masc|Number=Sing 0 root _ SpaceAfter=No 2 : : PUNCT sent _ 7 punct _ _ 3 Xanimeke xanim NOUN n Case=Acc|Gender=Fem|Number=Sing|PronType=Ind 7 nsubj _ _ 4 ciwan ciwan ADJ adj Degree=Pos 3 amod _ _ 5 desta dest NOUN n Case=Con|Definite=Def|Gender=Fem|Number=Sing 7 obj _ _ 6 me em PRON prn Case=Acc|Gender=Fem,Masc|Number=Plur|Person=1|PronType=Prs 5 nmod:poss _ _ 7 kiriye kirin VERB vblex Evident=Nfh|Mood=Ind|Number=Sing|Person=3|Tense=Past|VerbForm=Fin 1 parataxis _ SpaceAfter=No 8 . . PUNCT sent _ 7 punct _ _ ~~~
UniversalDependencies/docs
treebanks/kmr_mg/kmr_mg-dep-root.md
Markdown
apache-2.0
3,106
/** * Copyright (C) 2009-2014 Typesafe Inc. <http://www.typesafe.com> */ package docs.extension; //#imports import akka.actor.Extension; import akka.actor.AbstractExtensionId; import akka.actor.ExtensionIdProvider; import akka.actor.ActorSystem; import akka.actor.ExtendedActorSystem; import scala.concurrent.duration.Duration; import com.typesafe.config.Config; import java.util.concurrent.TimeUnit; //#imports import akka.actor.UntypedActor; import org.junit.Test; public class SettingsExtensionDocTest { static //#extension public class SettingsImpl implements Extension { public final String DB_URI; public final Duration CIRCUIT_BREAKER_TIMEOUT; public SettingsImpl(Config config) { DB_URI = config.getString("myapp.db.uri"); CIRCUIT_BREAKER_TIMEOUT = Duration.create(config.getDuration("myapp.circuit-breaker.timeout", TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS); } } //#extension static //#extensionid public class Settings extends AbstractExtensionId<SettingsImpl> implements ExtensionIdProvider { public final static Settings SettingsProvider = new Settings(); private Settings() {} public Settings lookup() { return Settings.SettingsProvider; } public SettingsImpl createExtension(ExtendedActorSystem system) { return new SettingsImpl(system.settings().config()); } } //#extensionid static //#extension-usage-actor public class MyActor extends UntypedActor { // typically you would use static import of the Settings.SettingsProvider field final SettingsImpl settings = Settings.SettingsProvider.get(getContext().system()); Connection connection = connect(settings.DB_URI, settings.CIRCUIT_BREAKER_TIMEOUT); //#extension-usage-actor public Connection connect(String dbUri, Duration circuitBreakerTimeout) { return new Connection(); } public void onReceive(Object msg) { } //#extension-usage-actor } //#extension-usage-actor public static class Connection { } @Test public void demonstrateHowToCreateAndUseAnAkkaExtensionInJava() { final ActorSystem system = null; try { //#extension-usage // typically you would use static import of the Settings.SettingsProvider field String dbUri = Settings.SettingsProvider.get(system).DB_URI; //#extension-usage } catch (Exception e) { //do nothing } } }
Horusiath/akka.net
Documentation/csharp/code/docs/extension/SettingsExtensionDocTest.java
Java
apache-2.0
2,450
/** * Copyright 2011-2016 GatlingCorp (http://gatling.io) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.gatling.jms.integration import javax.jms.{ Message, MessageListener } import scala.concurrent.duration._ import io.gatling.core.CoreComponents import io.gatling.core.action.{ Action, ActorDelegatingAction } import io.gatling.core.config.GatlingConfiguration import io.gatling.core.controller.throttle.Throttler import io.gatling.core.pause.Constant import io.gatling.core.protocol.{ ProtocolComponentsRegistry, Protocols } import io.gatling.core.session.Session import io.gatling.core.stats.StatsEngine import io.gatling.core.structure.{ ScenarioBuilder, ScenarioContext } import io.gatling.jms._ import io.gatling.jms.client.{ BrokerBasedSpec, SimpleJmsClient } import io.gatling.jms.request.JmsDestination import akka.actor.ActorRef import org.apache.activemq.jndi.ActiveMQInitialContextFactory class JmsMockCustomer(client: SimpleJmsClient, mockResponse: PartialFunction[Message, String]) extends MessageListener { val producer = client.session.createProducer(null) client.createReplyConsumer().setMessageListener(this) override def onMessage(request: Message): Unit = { if (mockResponse.isDefinedAt(request)) { val response = client.session.createTextMessage(mockResponse(request)) response.setJMSCorrelationID(request.getJMSMessageID) producer.send(request.getJMSReplyTo, response) } } def close(): Unit = { producer.close() client.close() } } trait JmsMockingSpec extends BrokerBasedSpec with JmsDsl { def jmsProtocol = jms .connectionFactoryName("ConnectionFactory") .url("vm://gatling?broker.persistent=false&broker.useJmx=false") .contextFactory(classOf[ActiveMQInitialContextFactory].getName) .listenerCount(1) def runScenario(sb: ScenarioBuilder, timeout: FiniteDuration = 10.seconds, protocols: Protocols = Protocols(jmsProtocol))(implicit configuration: GatlingConfiguration) = { val coreComponents = CoreComponents(mock[ActorRef], mock[Throttler], mock[StatsEngine], mock[Action], configuration) val next = new ActorDelegatingAction("next", self) val actor = sb.build(ScenarioContext(system, coreComponents, new ProtocolComponentsRegistry(system, coreComponents, protocols), Constant, throttled = false), next) actor ! Session("TestSession", 0) val session = expectMsgClass(timeout, classOf[Session]) session } def jmsMock(queue: JmsDestination, f: PartialFunction[Message, String]): Unit = { val processor = new JmsMockCustomer(createClient(queue), f) registerCleanUpAction(() => processor.close()) } }
ryez/gatling
gatling-jms/src/test/scala/io/gatling/jms/integration/JmsMockingSpec.scala
Scala
apache-2.0
3,164
/** * Copyright Intellectual Reserve, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gedcomx.build.enunciate; import org.codehaus.enunciate.main.ClasspathHandler; import org.codehaus.enunciate.main.ClasspathResource; import org.codehaus.enunciate.main.Enunciate; import org.gedcomx.test.Recipe; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import java.io.File; import java.util.ArrayList; import java.util.List; /** * @author Ryan Heaton */ public class RecipeClasspathHandler implements ClasspathHandler { private final Enunciate enunciate; private final List<Recipe> recipes = new ArrayList<Recipe>(); private final Unmarshaller unmarshaller; public RecipeClasspathHandler(Enunciate enunciate) { this.enunciate = enunciate; try { unmarshaller = JAXBContext.newInstance(Recipe.class).createUnmarshaller(); } catch (JAXBException e) { throw new RuntimeException(e); } } public List<Recipe> getRecipes() { return recipes; } @Override public void startPathEntry(File pathEntry) { } @Override public void handleResource(ClasspathResource resource) { if (resource.getPath().endsWith(".recipe.xml")) { try { this.recipes.add((Recipe) unmarshaller.unmarshal(resource.read())); } catch (Exception e) { this.enunciate.error("Unable to unmarshal recipe %s: %s.", resource.getPath(), e.getMessage()); } } } @Override public boolean endPathEntry(File pathEntry) { return false; } }
brenthale/gedcomx-java
enunciate-gedcomx-support/src/main/java/org/gedcomx/build/enunciate/RecipeClasspathHandler.java
Java
apache-2.0
2,169
// Generated from /POI/java/org/apache/poi/hssf/record/BoundSheetRecord.java #include <org/apache/poi/hssf/record/BoundSheetRecord.hpp> #include <java/lang/ArrayStoreException.hpp> #include <java/lang/NullPointerException.hpp> #include <java/lang/String.hpp> #include <java/lang/StringBuffer.hpp> #include <java/util/Arrays.hpp> #include <java/util/Comparator.hpp> #include <java/util/List.hpp> #include <org/apache/poi/hssf/record/BoundSheetRecord_1.hpp> #include <org/apache/poi/hssf/record/Record.hpp> #include <org/apache/poi/hssf/record/RecordBase.hpp> #include <org/apache/poi/hssf/record/RecordInputStream.hpp> #include <org/apache/poi/hssf/record/StandardRecord.hpp> #include <org/apache/poi/ss/util/WorkbookUtil.hpp> #include <org/apache/poi/util/BitField.hpp> #include <org/apache/poi/util/BitFieldFactory.hpp> #include <org/apache/poi/util/HexDump.hpp> #include <org/apache/poi/util/LittleEndian.hpp> #include <org/apache/poi/util/LittleEndianConsts.hpp> #include <org/apache/poi/util/LittleEndianOutput.hpp> #include <org/apache/poi/util/StringUtil.hpp> #include <Array.hpp> #include <ObjectArray.hpp> #include <SubArray.hpp> template<typename ComponentType, typename... Bases> struct SubArray; namespace poi { namespace hssf { namespace record { typedef ::SubArray< ::poi::hssf::record::RecordBase, ::java::lang::ObjectArray > RecordBaseArray; typedef ::SubArray< ::poi::hssf::record::Record, RecordBaseArray > RecordArray; typedef ::SubArray< ::poi::hssf::record::StandardRecord, RecordArray > StandardRecordArray; typedef ::SubArray< ::poi::hssf::record::BoundSheetRecord, StandardRecordArray > BoundSheetRecordArray; } // record } // hssf } // poi template<typename T> static T* npc(T* t) { if(!t) throw new ::java::lang::NullPointerException(); return t; } poi::hssf::record::BoundSheetRecord::BoundSheetRecord(const ::default_init_tag&) : super(*static_cast< ::default_init_tag* >(0)) { clinit(); } poi::hssf::record::BoundSheetRecord::BoundSheetRecord(::java::lang::String* sheetname) : BoundSheetRecord(*static_cast< ::default_init_tag* >(0)) { ctor(sheetname); } poi::hssf::record::BoundSheetRecord::BoundSheetRecord(RecordInputStream* in) : BoundSheetRecord(*static_cast< ::default_init_tag* >(0)) { ctor(in); } constexpr int16_t poi::hssf::record::BoundSheetRecord::sid; poi::util::BitField*& poi::hssf::record::BoundSheetRecord::hiddenFlag() { clinit(); return hiddenFlag_; } poi::util::BitField* poi::hssf::record::BoundSheetRecord::hiddenFlag_; poi::util::BitField*& poi::hssf::record::BoundSheetRecord::veryHiddenFlag() { clinit(); return veryHiddenFlag_; } poi::util::BitField* poi::hssf::record::BoundSheetRecord::veryHiddenFlag_; void poi::hssf::record::BoundSheetRecord::ctor(::java::lang::String* sheetname) { super::ctor(); field_2_option_flags = 0; setSheetname(sheetname); } void poi::hssf::record::BoundSheetRecord::ctor(RecordInputStream* in) { super::ctor(); auto buf = new ::int8_tArray(::poi::util::LittleEndianConsts::INT_SIZE); npc(in)->readPlain(buf, int32_t(0), npc(buf)->length); field_1_position_of_BOF = ::poi::util::LittleEndian::getInt(buf); field_2_option_flags = npc(in)->readUShort(); auto field_3_sheetname_length = npc(in)->readUByte(); field_4_isMultibyteUnicode = npc(in)->readByte(); if(isMultibyte()) { field_5_sheetname = npc(in)->readUnicodeLEString(field_3_sheetname_length); } else { field_5_sheetname = npc(in)->readCompressedUnicode(field_3_sheetname_length); } } void poi::hssf::record::BoundSheetRecord::setPositionOfBof(int32_t pos) { field_1_position_of_BOF = pos; } void poi::hssf::record::BoundSheetRecord::setSheetname(::java::lang::String* sheetName) { ::poi::ss::util::WorkbookUtil::validateSheetName(sheetName); field_5_sheetname = sheetName; field_4_isMultibyteUnicode = ::poi::util::StringUtil::hasMultibyte(sheetName) ? int32_t(1) : int32_t(0); } int32_t poi::hssf::record::BoundSheetRecord::getPositionOfBof() { return field_1_position_of_BOF; } bool poi::hssf::record::BoundSheetRecord::isMultibyte() { return (field_4_isMultibyteUnicode & int32_t(1)) != 0; } java::lang::String* poi::hssf::record::BoundSheetRecord::getSheetname() { return field_5_sheetname; } java::lang::String* poi::hssf::record::BoundSheetRecord::toString() { auto buffer = new ::java::lang::StringBuffer(); npc(buffer)->append(u"[BOUNDSHEET]\n"_j); npc(npc(npc(buffer)->append(u" .bof = "_j))->append(::poi::util::HexDump::intToHex(getPositionOfBof())))->append(u"\n"_j); npc(npc(npc(buffer)->append(u" .options = "_j))->append(::poi::util::HexDump::shortToHex(field_2_option_flags)))->append(u"\n"_j); npc(npc(npc(buffer)->append(u" .unicodeflag= "_j))->append(::poi::util::HexDump::byteToHex(field_4_isMultibyteUnicode)))->append(u"\n"_j); npc(npc(npc(buffer)->append(u" .sheetname = "_j))->append(field_5_sheetname))->append(u"\n"_j); npc(buffer)->append(u"[/BOUNDSHEET]\n"_j); return npc(buffer)->toString(); } int32_t poi::hssf::record::BoundSheetRecord::getDataSize() { return int32_t(8) + npc(field_5_sheetname)->length() * (isMultibyte() ? int32_t(2) : int32_t(1)); } void poi::hssf::record::BoundSheetRecord::serialize(::poi::util::LittleEndianOutput* out) { npc(out)->writeInt(getPositionOfBof()); npc(out)->writeShort(field_2_option_flags); auto name = field_5_sheetname; npc(out)->writeByte(npc(name)->length()); npc(out)->writeByte(field_4_isMultibyteUnicode); if(isMultibyte()) { ::poi::util::StringUtil::putUnicodeLE(name, out); } else { ::poi::util::StringUtil::putCompressedUnicode(name, out); } } int16_t poi::hssf::record::BoundSheetRecord::getSid() { return sid; } bool poi::hssf::record::BoundSheetRecord::isHidden() { return npc(hiddenFlag_)->isSet(field_2_option_flags); } void poi::hssf::record::BoundSheetRecord::setHidden(bool hidden) { field_2_option_flags = npc(hiddenFlag_)->setBoolean(field_2_option_flags, hidden); } bool poi::hssf::record::BoundSheetRecord::isVeryHidden() { return npc(veryHiddenFlag_)->isSet(field_2_option_flags); } void poi::hssf::record::BoundSheetRecord::setVeryHidden(bool veryHidden) { field_2_option_flags = npc(veryHiddenFlag_)->setBoolean(field_2_option_flags, veryHidden); } poi::hssf::record::BoundSheetRecordArray* poi::hssf::record::BoundSheetRecord::orderByBofPosition(::java::util::List* boundSheetRecords) { clinit(); auto bsrs = new BoundSheetRecordArray(npc(boundSheetRecords)->size()); npc(boundSheetRecords)->toArray_(static_cast< ::java::lang::ObjectArray* >(bsrs)); ::java::util::Arrays::sort(bsrs, BOFComparator_); return bsrs; } java::util::Comparator*& poi::hssf::record::BoundSheetRecord::BOFComparator() { clinit(); return BOFComparator_; } java::util::Comparator* poi::hssf::record::BoundSheetRecord::BOFComparator_; extern java::lang::Class *class_(const char16_t *c, int n); java::lang::Class* poi::hssf::record::BoundSheetRecord::class_() { static ::java::lang::Class* c = ::class_(u"org.apache.poi.hssf.record.BoundSheetRecord", 43); return c; } void poi::hssf::record::BoundSheetRecord::clinit() { super::clinit(); static bool in_cl_init = false; struct clinit_ { clinit_() { in_cl_init = true; hiddenFlag_ = ::poi::util::BitFieldFactory::getInstance(1); veryHiddenFlag_ = ::poi::util::BitFieldFactory::getInstance(2); BOFComparator_ = new BoundSheetRecord_1(); } }; if(!in_cl_init) { static clinit_ clinit_instance; } } int32_t poi::hssf::record::BoundSheetRecord::serialize(int32_t offset, ::int8_tArray* data) { return super::serialize(offset, data); } int8_tArray* poi::hssf::record::BoundSheetRecord::serialize() { return super::serialize(); } java::lang::Class* poi::hssf::record::BoundSheetRecord::getClass0() { return class_(); }
pebble2015/cpoi
src/org/apache/poi/hssf/record/BoundSheetRecord.cpp
C++
apache-2.0
8,028
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.devicefarm.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * Represents a specific warning or failure. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/Problem" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class Problem implements Serializable, Cloneable, StructuredPojo { /** * <p> * Information about the associated run. * </p> */ private ProblemDetail run; /** * <p> * Information about the associated job. * </p> */ private ProblemDetail job; /** * <p> * Information about the associated suite. * </p> */ private ProblemDetail suite; /** * <p> * Information about the associated test. * </p> */ private ProblemDetail test; /** * <p> * Information about the associated device. * </p> */ private Device device; /** * <p> * The problem's result. * </p> * <p> * Allowed values include: * </p> * <ul> * <li> * <p> * PENDING * </p> * </li> * <li> * <p> * PASSED * </p> * </li> * <li> * <p> * WARNED * </p> * </li> * <li> * <p> * FAILED * </p> * </li> * <li> * <p> * SKIPPED * </p> * </li> * <li> * <p> * ERRORED * </p> * </li> * <li> * <p> * STOPPED * </p> * </li> * </ul> */ private String result; /** * <p> * A message about the problem's result. * </p> */ private String message; /** * <p> * Information about the associated run. * </p> * * @param run * Information about the associated run. */ public void setRun(ProblemDetail run) { this.run = run; } /** * <p> * Information about the associated run. * </p> * * @return Information about the associated run. */ public ProblemDetail getRun() { return this.run; } /** * <p> * Information about the associated run. * </p> * * @param run * Information about the associated run. * @return Returns a reference to this object so that method calls can be chained together. */ public Problem withRun(ProblemDetail run) { setRun(run); return this; } /** * <p> * Information about the associated job. * </p> * * @param job * Information about the associated job. */ public void setJob(ProblemDetail job) { this.job = job; } /** * <p> * Information about the associated job. * </p> * * @return Information about the associated job. */ public ProblemDetail getJob() { return this.job; } /** * <p> * Information about the associated job. * </p> * * @param job * Information about the associated job. * @return Returns a reference to this object so that method calls can be chained together. */ public Problem withJob(ProblemDetail job) { setJob(job); return this; } /** * <p> * Information about the associated suite. * </p> * * @param suite * Information about the associated suite. */ public void setSuite(ProblemDetail suite) { this.suite = suite; } /** * <p> * Information about the associated suite. * </p> * * @return Information about the associated suite. */ public ProblemDetail getSuite() { return this.suite; } /** * <p> * Information about the associated suite. * </p> * * @param suite * Information about the associated suite. * @return Returns a reference to this object so that method calls can be chained together. */ public Problem withSuite(ProblemDetail suite) { setSuite(suite); return this; } /** * <p> * Information about the associated test. * </p> * * @param test * Information about the associated test. */ public void setTest(ProblemDetail test) { this.test = test; } /** * <p> * Information about the associated test. * </p> * * @return Information about the associated test. */ public ProblemDetail getTest() { return this.test; } /** * <p> * Information about the associated test. * </p> * * @param test * Information about the associated test. * @return Returns a reference to this object so that method calls can be chained together. */ public Problem withTest(ProblemDetail test) { setTest(test); return this; } /** * <p> * Information about the associated device. * </p> * * @param device * Information about the associated device. */ public void setDevice(Device device) { this.device = device; } /** * <p> * Information about the associated device. * </p> * * @return Information about the associated device. */ public Device getDevice() { return this.device; } /** * <p> * Information about the associated device. * </p> * * @param device * Information about the associated device. * @return Returns a reference to this object so that method calls can be chained together. */ public Problem withDevice(Device device) { setDevice(device); return this; } /** * <p> * The problem's result. * </p> * <p> * Allowed values include: * </p> * <ul> * <li> * <p> * PENDING * </p> * </li> * <li> * <p> * PASSED * </p> * </li> * <li> * <p> * WARNED * </p> * </li> * <li> * <p> * FAILED * </p> * </li> * <li> * <p> * SKIPPED * </p> * </li> * <li> * <p> * ERRORED * </p> * </li> * <li> * <p> * STOPPED * </p> * </li> * </ul> * * @param result * The problem's result.</p> * <p> * Allowed values include: * </p> * <ul> * <li> * <p> * PENDING * </p> * </li> * <li> * <p> * PASSED * </p> * </li> * <li> * <p> * WARNED * </p> * </li> * <li> * <p> * FAILED * </p> * </li> * <li> * <p> * SKIPPED * </p> * </li> * <li> * <p> * ERRORED * </p> * </li> * <li> * <p> * STOPPED * </p> * </li> * @see ExecutionResult */ public void setResult(String result) { this.result = result; } /** * <p> * The problem's result. * </p> * <p> * Allowed values include: * </p> * <ul> * <li> * <p> * PENDING * </p> * </li> * <li> * <p> * PASSED * </p> * </li> * <li> * <p> * WARNED * </p> * </li> * <li> * <p> * FAILED * </p> * </li> * <li> * <p> * SKIPPED * </p> * </li> * <li> * <p> * ERRORED * </p> * </li> * <li> * <p> * STOPPED * </p> * </li> * </ul> * * @return The problem's result.</p> * <p> * Allowed values include: * </p> * <ul> * <li> * <p> * PENDING * </p> * </li> * <li> * <p> * PASSED * </p> * </li> * <li> * <p> * WARNED * </p> * </li> * <li> * <p> * FAILED * </p> * </li> * <li> * <p> * SKIPPED * </p> * </li> * <li> * <p> * ERRORED * </p> * </li> * <li> * <p> * STOPPED * </p> * </li> * @see ExecutionResult */ public String getResult() { return this.result; } /** * <p> * The problem's result. * </p> * <p> * Allowed values include: * </p> * <ul> * <li> * <p> * PENDING * </p> * </li> * <li> * <p> * PASSED * </p> * </li> * <li> * <p> * WARNED * </p> * </li> * <li> * <p> * FAILED * </p> * </li> * <li> * <p> * SKIPPED * </p> * </li> * <li> * <p> * ERRORED * </p> * </li> * <li> * <p> * STOPPED * </p> * </li> * </ul> * * @param result * The problem's result.</p> * <p> * Allowed values include: * </p> * <ul> * <li> * <p> * PENDING * </p> * </li> * <li> * <p> * PASSED * </p> * </li> * <li> * <p> * WARNED * </p> * </li> * <li> * <p> * FAILED * </p> * </li> * <li> * <p> * SKIPPED * </p> * </li> * <li> * <p> * ERRORED * </p> * </li> * <li> * <p> * STOPPED * </p> * </li> * @return Returns a reference to this object so that method calls can be chained together. * @see ExecutionResult */ public Problem withResult(String result) { setResult(result); return this; } /** * <p> * The problem's result. * </p> * <p> * Allowed values include: * </p> * <ul> * <li> * <p> * PENDING * </p> * </li> * <li> * <p> * PASSED * </p> * </li> * <li> * <p> * WARNED * </p> * </li> * <li> * <p> * FAILED * </p> * </li> * <li> * <p> * SKIPPED * </p> * </li> * <li> * <p> * ERRORED * </p> * </li> * <li> * <p> * STOPPED * </p> * </li> * </ul> * * @param result * The problem's result.</p> * <p> * Allowed values include: * </p> * <ul> * <li> * <p> * PENDING * </p> * </li> * <li> * <p> * PASSED * </p> * </li> * <li> * <p> * WARNED * </p> * </li> * <li> * <p> * FAILED * </p> * </li> * <li> * <p> * SKIPPED * </p> * </li> * <li> * <p> * ERRORED * </p> * </li> * <li> * <p> * STOPPED * </p> * </li> * @see ExecutionResult */ public void setResult(ExecutionResult result) { withResult(result); } /** * <p> * The problem's result. * </p> * <p> * Allowed values include: * </p> * <ul> * <li> * <p> * PENDING * </p> * </li> * <li> * <p> * PASSED * </p> * </li> * <li> * <p> * WARNED * </p> * </li> * <li> * <p> * FAILED * </p> * </li> * <li> * <p> * SKIPPED * </p> * </li> * <li> * <p> * ERRORED * </p> * </li> * <li> * <p> * STOPPED * </p> * </li> * </ul> * * @param result * The problem's result.</p> * <p> * Allowed values include: * </p> * <ul> * <li> * <p> * PENDING * </p> * </li> * <li> * <p> * PASSED * </p> * </li> * <li> * <p> * WARNED * </p> * </li> * <li> * <p> * FAILED * </p> * </li> * <li> * <p> * SKIPPED * </p> * </li> * <li> * <p> * ERRORED * </p> * </li> * <li> * <p> * STOPPED * </p> * </li> * @return Returns a reference to this object so that method calls can be chained together. * @see ExecutionResult */ public Problem withResult(ExecutionResult result) { this.result = result.toString(); return this; } /** * <p> * A message about the problem's result. * </p> * * @param message * A message about the problem's result. */ public void setMessage(String message) { this.message = message; } /** * <p> * A message about the problem's result. * </p> * * @return A message about the problem's result. */ public String getMessage() { return this.message; } /** * <p> * A message about the problem's result. * </p> * * @param message * A message about the problem's result. * @return Returns a reference to this object so that method calls can be chained together. */ public Problem withMessage(String message) { setMessage(message); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getRun() != null) sb.append("Run: ").append(getRun()).append(","); if (getJob() != null) sb.append("Job: ").append(getJob()).append(","); if (getSuite() != null) sb.append("Suite: ").append(getSuite()).append(","); if (getTest() != null) sb.append("Test: ").append(getTest()).append(","); if (getDevice() != null) sb.append("Device: ").append(getDevice()).append(","); if (getResult() != null) sb.append("Result: ").append(getResult()).append(","); if (getMessage() != null) sb.append("Message: ").append(getMessage()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof Problem == false) return false; Problem other = (Problem) obj; if (other.getRun() == null ^ this.getRun() == null) return false; if (other.getRun() != null && other.getRun().equals(this.getRun()) == false) return false; if (other.getJob() == null ^ this.getJob() == null) return false; if (other.getJob() != null && other.getJob().equals(this.getJob()) == false) return false; if (other.getSuite() == null ^ this.getSuite() == null) return false; if (other.getSuite() != null && other.getSuite().equals(this.getSuite()) == false) return false; if (other.getTest() == null ^ this.getTest() == null) return false; if (other.getTest() != null && other.getTest().equals(this.getTest()) == false) return false; if (other.getDevice() == null ^ this.getDevice() == null) return false; if (other.getDevice() != null && other.getDevice().equals(this.getDevice()) == false) return false; if (other.getResult() == null ^ this.getResult() == null) return false; if (other.getResult() != null && other.getResult().equals(this.getResult()) == false) return false; if (other.getMessage() == null ^ this.getMessage() == null) return false; if (other.getMessage() != null && other.getMessage().equals(this.getMessage()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getRun() == null) ? 0 : getRun().hashCode()); hashCode = prime * hashCode + ((getJob() == null) ? 0 : getJob().hashCode()); hashCode = prime * hashCode + ((getSuite() == null) ? 0 : getSuite().hashCode()); hashCode = prime * hashCode + ((getTest() == null) ? 0 : getTest().hashCode()); hashCode = prime * hashCode + ((getDevice() == null) ? 0 : getDevice().hashCode()); hashCode = prime * hashCode + ((getResult() == null) ? 0 : getResult().hashCode()); hashCode = prime * hashCode + ((getMessage() == null) ? 0 : getMessage().hashCode()); return hashCode; } @Override public Problem clone() { try { return (Problem) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.devicefarm.model.transform.ProblemMarshaller.getInstance().marshall(this, protocolMarshaller); } }
aws/aws-sdk-java
aws-java-sdk-devicefarm/src/main/java/com/amazonaws/services/devicefarm/model/Problem.java
Java
apache-2.0
19,577
var logger = require('../logging').getLogger(__LOGGER__); var {PAGE_CSS_NODE_ID} = require('../constants'); var Q = require('q'); var PageUtil = require('./PageUtil') var loadedCss = {}; module.exports = { registerPageLoad: function registerPageLoad() { if (SERVER_SIDE) { throw new Error("ClientCssHelper.registerPageLoad can't be called server-side"); } // for each css node in the head that the react-server server wrote to the response, note it down in the cache, so that // we can remove it on a page to page transition. var serverWrittenLinkNodes = document.head.querySelectorAll(`link[${PAGE_CSS_NODE_ID}],style[${PAGE_CSS_NODE_ID}]`); for (var i = 0; i < serverWrittenLinkNodes.length; i++) { var key, styleNode = serverWrittenLinkNodes[i]; if (styleNode.href) { key = normalizeLocalUrl(styleNode.href); } else { key = styleNode.innerHTML; } loadedCss[key] = styleNode; } }, ensureCss: function ensureCss(routeName, pageObject) { if (SERVER_SIDE) { throw new Error("ClientCssHelper.registerPageLoad can't be called server-side"); } return Q.all(PageUtil.standardizeStyles(pageObject.getHeadStylesheets())).then(newCss => { var newCssByKey = {}; newCss .filter(style => !!style) .forEach(style => {newCssByKey[this._keyFromStyleSheet(style)] = style}); // first, remove the unneeded CSS link elements. Object.keys(loadedCss).forEach(loadedCssKey => { if (!newCssByKey[loadedCssKey]) { // remove the corresponding node from the DOM. logger.debug("Removing stylesheet: " + loadedCssKey); var node = loadedCss[loadedCssKey]; node.parentNode.removeChild(node); delete loadedCss[loadedCssKey]; } }); // next add the style URLs that weren't already loaded. return Q.all(Object.keys(newCssByKey).map(newCssKey => { var retval; if (!loadedCss[newCssKey]) { // this means that the CSS is not currently present in the // document, so we need to add it. logger.debug("Adding stylesheet: " + newCssKey); var style = newCssByKey[newCssKey]; var styleTag; if (style.href) { styleTag = document.createElement('link'); styleTag.rel = 'stylesheet'; styleTag.href = style.href; // If we _can_ wait for the CSS to be loaded before // proceeding, let's do so. if ('onload' in styleTag) { var dfd = Q.defer(); styleTag.onload = dfd.resolve; retval = dfd.promise; } } else { styleTag = document.createElement('style'); styleTag.innerHTML = style.text; } styleTag.type = style.type; styleTag.media = style.media; loadedCss[newCssKey] = styleTag; document.head.appendChild(styleTag); } else { logger.debug(`Stylesheet already loaded (no-op): ${newCssKey}`); } return retval; })); }); }, _keyFromStyleSheet: function(style) { return normalizeLocalUrl(style.href) || style.text; }, } function normalizeLocalUrl(url) { // Step 1: make the url protocol less first. This helps recognizing http://0.0.0.0:3001/common.css // and //0.0.0.0:3001/common.css as the same file. // Step 2: The browser will give us a full URL even if we only put a // path in on the server. So, if we're comparing against just // a path here we need to strip the base off to avoid a flash // of unstyled content. if (typeof url === 'string') { url = url .replace(/^http[s]?:/, '') .replace(new RegExp("^//" + location.host), ''); } return url; }
redfin/react-server
packages/react-server/core/util/ClientCssHelper.js
JavaScript
apache-2.0
3,519
package lesson.types; public class Classes { public static void main(String[] args) { JustClass one = new JustClass(); JustClass two = new JustClass(123, "sdf"); System.out.println(one); System.out.println(two); } } class JustClass { private int number; private String name; public JustClass() { } public JustClass(int number, String name) { this.number = number; this.name = name; } @Override public String toString() { return String .format("JustClass {%s, %d}", name,number); } }
nesterione/JavaTrainings
src/lesson/types/Classes.java
Java
apache-2.0
602
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_CONTEXT_H_ #define TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_CONTEXT_H_ #include <algorithm> #include <cstddef> #include <map> #include <memory> #include <queue> #include <string> #include <vector> #include "tensorflow/core/common_runtime/device_factory.h" #include "tensorflow/core/common_runtime/device_mgr.h" #include "tensorflow/core/common_runtime/eager/eager_executor.h" #include "tensorflow/core/common_runtime/eager/kernel_and_device.h" #include "tensorflow/core/common_runtime/function.h" #include "tensorflow/core/common_runtime/rendezvous_mgr.h" #ifndef __ANDROID__ #include "tensorflow/core/distributed_runtime/eager/eager_client.h" #include "tensorflow/core/distributed_runtime/server_lib.h" #endif #include "tensorflow/core/framework/log_memory.h" #include "tensorflow/core/framework/rendezvous.h" #include "tensorflow/core/lib/core/stringpiece.h" #include "tensorflow/core/lib/core/threadpool.h" #include "tensorflow/core/lib/gtl/flatmap.h" #include "tensorflow/core/lib/gtl/flatset.h" #include "tensorflow/core/lib/gtl/inlined_vector.h" #include "tensorflow/core/lib/gtl/map_util.h" #include "tensorflow/core/lib/gtl/stl_util.h" #include "tensorflow/core/platform/fingerprint.h" #include "tensorflow/core/platform/mutex.h" #include "tensorflow/core/platform/thread_annotations.h" #include "tensorflow/core/public/session_options.h" #include "tensorflow/core/public/version.h" namespace tensorflow { // Note: there's a copy enum in eager/c_api.h. It should be kept in sync. enum ContextDevicePlacementPolicy { // Running operations with input tensors on the wrong device will fail. DEVICE_PLACEMENT_EXPLICIT = 0, // Copy the tensor to the right device but log a warning. DEVICE_PLACEMENT_WARN = 1, // Silently copy the tensor, which has a performance cost since the operation // will be blocked till the copy completes. This is the default policy. DEVICE_PLACEMENT_SILENT = 2, // Default placement policy which silently copies int32 tensors but not other // dtypes. DEVICE_PLACEMENT_SILENT_FOR_INT32 = 3, }; class EagerContext { public: // TODO: remove this constructor once we migrate all callers to the next one. EagerContext(const SessionOptions& opts, ContextDevicePlacementPolicy default_policy, bool async, std::unique_ptr<const DeviceMgr> device_mgr, Rendezvous* rendezvous); EagerContext(const SessionOptions& opts, ContextDevicePlacementPolicy default_policy, bool async, const DeviceMgr* device_mgr, bool device_mgr_owned, Rendezvous* rendezvous); ~EagerContext(); // Returns the function library runtime for the given device. FunctionLibraryRuntime* func_lib(Device* d) const { return pflr_->GetFLR(d->name()); } // True if running in asynchronous mode. bool Async() const; EagerExecutor* Executor() { return &executor_; } std::function<void(std::function<void()>)>* runner() { return &runner_; } // Sets whether this thread should run in synchronous or asynchronous mode. Status SetAsyncForThread(bool async); // TODO(apassos) make this return a constant reference gtl::FlatMap<string, Device*, StringPieceHasher>* device_map() { return &devices_map_; } // TODO(apassos) make this return a constant reference std::vector<Device*>* devices() { return &devices_; } const std::vector<DeviceType>& prioritized_device_type_list() { return prioritized_device_type_list_; } // Clears the kernel caches. void ClearCaches(); // Sets the device placement policy for the current thread. void SetThreadLocalDevicePlacementPolicy(ContextDevicePlacementPolicy policy); // Returns the device placement policy for the current thread. ContextDevicePlacementPolicy GetDevicePlacementPolicy(); Status AsyncWait() { return executor_.WaitForAllPendingNodes(); } Status GetStatus() { return executor_.status(); } void ClearAsyncError() { executor_.ClearError(); } bool FindFunctionByName(const string& name); Status FindFunctionOpData(const string& name, const tensorflow::OpRegistrationData** op_data); const FunctionDef* FindFunctionDef(const string& name); Status FindDeviceByName(const string& name, Device** result); Device* HostCPU() { return devices_[0]; } GraphCollector* GetGraphCollector() { return &graph_collector_; } uint64 NextId() { return executor_.NextId(); } void ExecutorAdd(EagerNode* node) { executor_.Add(node); } Status AddFunctionDef(const FunctionDef& fdef); KernelAndDevice* GetCachedKernel(Fprint128 cache_key); void AddKernelToCache(Fprint128 cache_key, KernelAndDevice* kernel); bool LogDevicePlacement() { return log_device_placement_; } bool LogMemory() { return log_memory_; } Rendezvous* GetRendezvous() { return rendezvous_; } const tensorflow::DeviceMgr* local_device_mgr() const { return (local_device_manager_ != nullptr) ? local_device_manager_.get() : local_unowned_device_manager_; } const tensorflow::DeviceMgr* remote_device_mgr() { return remote_device_manager_.get(); } // TODO(apassos) remove the need for this void ReleaseDeviceMgr() { local_device_manager_.release(); } // TODO(apassos) clean up RunMetadata storage. mutex* MetadataMu() { return &metadata_mu_; } bool ShouldStoreMetadata() { return should_store_metadata_.load(); } void SetShouldStoreMetadata(bool value); RunMetadata* RunMetadataProto() { return &run_metadata_; } void StartStep(); void EndStep(); ScopedStepContainer* StepContainer(); FunctionLibraryDefinition* FuncLibDef() { return &func_lib_def_; } #ifndef __ANDROID__ Status GetClientAndContextID(Device* device, eager::EagerClient** client, uint64* context_id); // TODO(nareshmodi): Encapsulate remote state into a separate // class/struct. // // Enables the eager context to communicate with remote devices. // // - server: A ServerInterface that exports the tensorflow.WorkerService. // Note that this class expects the server to already have been started. // - remote_eager_workers: A cache from which we can get "EagerClient"s to // communicate with remote eager services. // - remote_device_mgr: A DeviceMgr* which contains all remote devices // (should contain no local devices). // - remote_contexts: A map containing task name to remote context ID. void InitializeRemote( std::unique_ptr<ServerInterface> server, std::unique_ptr<eager::EagerClientCache> remote_eager_workers, std::unique_ptr<DeviceMgr> remote_device_manager, const gtl::FlatMap<string, uint64>& remote_contexts, Rendezvous* r, DeviceMgr* local_device_mgr, int keep_alive_secs); bool HasActiveRemoteContext(uint64 context_id) { return active_remote_contexts_.find(context_id) != active_remote_contexts_.end(); } #endif // If true, then tensors should be shipped across processes via the // EagerService.SendTensor RPC. If false, _Send/_Recv ops should be used // instead (which in-turn use WorkerService.RecvTensor RPCs). bool UseSendTensorRPC() { return use_send_tensor_rpc_; } bool PinSmallOpsToCPU() { return pin_small_ops_to_cpu_; } tensorflow::Env* TFEnv() const { return env_; } private: void InitDeviceMapAndAsync(); Status MaybeRegisterFunctionRemotely(const FunctionDef& fdef); const ContextDevicePlacementPolicy policy_; // Note: we cannot use C++11 thread_local here as there is no concept of a // thread-local-object-local variable in C++11. mutex policy_map_mu_; std::unordered_map<std::thread::id, ContextDevicePlacementPolicy> thread_local_policies_ GUARDED_BY(policy_map_mu_); // Only one of the below is set. std::unique_ptr<const DeviceMgr> local_device_manager_; const DeviceMgr* local_unowned_device_manager_; std::unique_ptr<DeviceMgr> remote_device_manager_; // Devices owned by device_manager std::vector<Device*> devices_; std::vector<DeviceType> prioritized_device_type_list_; // All devices are not owned. gtl::FlatMap<string, Device*, StringPieceHasher> devices_map_; Rendezvous* rendezvous_; mutex functions_mu_; FunctionLibraryDefinition func_lib_def_ GUARDED_BY(functions_mu_){ OpRegistry::Global(), {}}; std::unique_ptr<thread::ThreadPool> thread_pool_; // One FunctionLibraryRuntime per device. // func_libs[i] is the FunctionLibraryRuntime corresponding to // session->devices[i]. std::unique_ptr<ProcessFunctionLibraryRuntime> pflr_; std::function<void(std::function<void()>)> runner_; mutex cache_mu_; std::unordered_map<Fprint128, KernelAndDevice*, Fprint128Hasher> kernel_cache_ GUARDED_BY(cache_mu_); // Whether we should compute RunMetadata. std::atomic<bool> should_store_metadata_{false}; mutex metadata_mu_; RunMetadata run_metadata_ GUARDED_BY(metadata_mu_); GraphCollector graph_collector_; const bool log_device_placement_; // EagerExecutor for async execution. EagerExecutor executor_; // Information related to step containers. std::atomic<int> num_active_steps_; std::unique_ptr<ScopedStepContainer> step_container_ GUARDED_BY(metadata_mu_); // True if the default value for execution mode is async. Note that this value // can be overridden per thread based on `thread_local_async` overrides. const bool async_default_; mutable mutex async_map_mu_; std::unordered_map<std::thread::id, bool> thread_local_async_ GUARDED_BY(async_map_mu_); const bool log_memory_; Env* const env_; #ifndef __ANDROID__ void CloseRemoteContexts(); // The server_ is not const since we release it when the context is destroyed. // Therefore the server_ object is not marked as const (even though it should // be). std::unique_ptr<ServerInterface> server_; std::unique_ptr<eager::EagerClientCache> remote_eager_workers_; mutex remote_state_mu_; gtl::FlatMap<string, uint64> remote_contexts_; gtl::FlatSet<uint64> active_remote_contexts_; gtl::FlatMap<Device*, std::pair<eager::EagerClient*, uint64>> device_to_client_cache_; int keep_alive_secs_ GUARDED_BY(remote_state_mu_); std::atomic<int> sleep_for_secs_; std::unique_ptr<Thread> keep_alive_thread_; mutex keep_alive_thread_shutdown_mu_; condition_variable keep_alive_thread_cv_; bool shutting_down_ GUARDED_BY(keep_alive_thread_shutdown_mu_) = false; #endif bool use_send_tensor_rpc_; const bool pin_small_ops_to_cpu_; }; } // namespace tensorflow #endif // TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_CONTEXT_H_
hehongliang/tensorflow
tensorflow/core/common_runtime/eager/context.h
C
apache-2.0
11,313
using GeneticCreatures.Classes.UtilityClasses; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Tester.classes; namespace GeneticCreatures.Classes.Objects.InanimateObjects { class Wall : Selectable { public Wall(Position pos) : base(pos, defaultColour) { allWalls.Add(this); } public Wall(Position pos, Colour col) : base(pos, col) { allWalls.Add(this); } public static List<Wall> allWalls = new List<Wall>(); private static Colour defaultColour = new Colour(100, 100, 100); private static Colour selectedColour = Colour.White; public override void Draw() { if (GameState.GetState() != GameStates.CreatingNet) { Colour chosenCol = colour; if (this.isSelected) chosenCol = selectedColour; ShapeDrawer.DrawCircle(position.Location, DrawRadius, chosenCol); } } protected override void DestroyWorldObject() { allWalls.Remove(this); base.DestroyWorldObject(); } } }
joeeyles/geneticcreatures
GeneticCreatures/GeneticCreatures/Classes/Objects/InanimateObjects/Wall.cs
C#
apache-2.0
1,296