code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
namespace SoukeyNetget { partial class frmAddPlanTask { /// <summary> /// 必需的设计器变量。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 清理所有正在使用的资源。 /// </summary> /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows 窗体设计器生成的代码 /// <summary> /// 设计器支持所需的方法 - 不要 /// 使用代码编辑器修改此方法的内容。 /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmAddPlanTask)); this.raSoukeyTask = new System.Windows.Forms.RadioButton(); this.raOtherTask = new System.Windows.Forms.RadioButton(); this.panel1 = new System.Windows.Forms.Panel(); this.listTask = new System.Windows.Forms.ListView(); this.columnHeader1 = new System.Windows.Forms.ColumnHeader(); this.columnHeader2 = new System.Windows.Forms.ColumnHeader(); this.columnHeader3 = new System.Windows.Forms.ColumnHeader(); this.columnHeader4 = new System.Windows.Forms.ColumnHeader(); this.label1 = new System.Windows.Forms.Label(); this.comTaskClass = new System.Windows.Forms.ComboBox(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.panel3 = new System.Windows.Forms.Panel(); this.comTableName = new System.Windows.Forms.ComboBox(); this.button12 = new System.Windows.Forms.Button(); this.txtDataSource = new System.Windows.Forms.TextBox(); this.raMySqlTask = new System.Windows.Forms.RadioButton(); this.raMSSQLTask = new System.Windows.Forms.RadioButton(); this.raAccessTask = new System.Windows.Forms.RadioButton(); this.label8 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.panel2 = new System.Windows.Forms.Panel(); this.txtPara = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.button1 = new System.Windows.Forms.Button(); this.txtFileName = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog(); this.raDataTask = new System.Windows.Forms.RadioButton(); this.cmdCancel = new System.Windows.Forms.Button(); this.cmdOK = new System.Windows.Forms.Button(); this.panel1.SuspendLayout(); this.groupBox1.SuspendLayout(); this.panel3.SuspendLayout(); this.panel2.SuspendLayout(); this.SuspendLayout(); // // raSoukeyTask // this.raSoukeyTask.AccessibleDescription = null; this.raSoukeyTask.AccessibleName = null; resources.ApplyResources(this.raSoukeyTask, "raSoukeyTask"); this.raSoukeyTask.BackgroundImage = null; this.raSoukeyTask.Checked = true; this.raSoukeyTask.Font = null; this.raSoukeyTask.Name = "raSoukeyTask"; this.raSoukeyTask.TabStop = true; this.raSoukeyTask.UseVisualStyleBackColor = true; this.raSoukeyTask.CheckedChanged += new System.EventHandler(this.raSoukeyTask_CheckedChanged); // // raOtherTask // this.raOtherTask.AccessibleDescription = null; this.raOtherTask.AccessibleName = null; resources.ApplyResources(this.raOtherTask, "raOtherTask"); this.raOtherTask.BackgroundImage = null; this.raOtherTask.Font = null; this.raOtherTask.Name = "raOtherTask"; this.raOtherTask.UseVisualStyleBackColor = true; this.raOtherTask.CheckedChanged += new System.EventHandler(this.raOtherTask_CheckedChanged); // // panel1 // this.panel1.AccessibleDescription = null; this.panel1.AccessibleName = null; resources.ApplyResources(this.panel1, "panel1"); this.panel1.BackgroundImage = null; this.panel1.Controls.Add(this.listTask); this.panel1.Controls.Add(this.label1); this.panel1.Controls.Add(this.comTaskClass); this.panel1.Font = null; this.panel1.Name = "panel1"; // // listTask // this.listTask.AccessibleDescription = null; this.listTask.AccessibleName = null; resources.ApplyResources(this.listTask, "listTask"); this.listTask.BackgroundImage = null; this.listTask.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeader1, this.columnHeader2, this.columnHeader3, this.columnHeader4}); this.listTask.Font = null; this.listTask.FullRowSelect = true; this.listTask.MultiSelect = false; this.listTask.Name = "listTask"; this.listTask.UseCompatibleStateImageBehavior = false; this.listTask.View = System.Windows.Forms.View.Details; this.listTask.DoubleClick += new System.EventHandler(this.listTask_DoubleClick); // // columnHeader1 // resources.ApplyResources(this.columnHeader1, "columnHeader1"); // // columnHeader2 // resources.ApplyResources(this.columnHeader2, "columnHeader2"); // // columnHeader3 // resources.ApplyResources(this.columnHeader3, "columnHeader3"); // // columnHeader4 // resources.ApplyResources(this.columnHeader4, "columnHeader4"); // // label1 // this.label1.AccessibleDescription = null; this.label1.AccessibleName = null; resources.ApplyResources(this.label1, "label1"); this.label1.Font = null; this.label1.Name = "label1"; // // comTaskClass // this.comTaskClass.AccessibleDescription = null; this.comTaskClass.AccessibleName = null; resources.ApplyResources(this.comTaskClass, "comTaskClass"); this.comTaskClass.BackgroundImage = null; this.comTaskClass.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comTaskClass.Font = null; this.comTaskClass.FormattingEnabled = true; this.comTaskClass.Name = "comTaskClass"; this.comTaskClass.SelectedIndexChanged += new System.EventHandler(this.comTaskClass_SelectedIndexChanged); // // groupBox1 // this.groupBox1.AccessibleDescription = null; this.groupBox1.AccessibleName = null; resources.ApplyResources(this.groupBox1, "groupBox1"); this.groupBox1.BackgroundImage = null; this.groupBox1.Controls.Add(this.panel2); this.groupBox1.Controls.Add(this.panel1); this.groupBox1.Controls.Add(this.panel3); this.groupBox1.Font = null; this.groupBox1.Name = "groupBox1"; this.groupBox1.TabStop = false; // // panel3 // this.panel3.AccessibleDescription = null; this.panel3.AccessibleName = null; resources.ApplyResources(this.panel3, "panel3"); this.panel3.BackgroundImage = null; this.panel3.Controls.Add(this.comTableName); this.panel3.Controls.Add(this.button12); this.panel3.Controls.Add(this.txtDataSource); this.panel3.Controls.Add(this.raMySqlTask); this.panel3.Controls.Add(this.raMSSQLTask); this.panel3.Controls.Add(this.raAccessTask); this.panel3.Controls.Add(this.label8); this.panel3.Controls.Add(this.label6); this.panel3.Font = null; this.panel3.Name = "panel3"; // // comTableName // this.comTableName.AccessibleDescription = null; this.comTableName.AccessibleName = null; resources.ApplyResources(this.comTableName, "comTableName"); this.comTableName.BackgroundImage = null; this.comTableName.Font = null; this.comTableName.FormattingEnabled = true; this.comTableName.Name = "comTableName"; this.comTableName.DropDown += new System.EventHandler(this.comTableName_DropDown); // // button12 // this.button12.AccessibleDescription = null; this.button12.AccessibleName = null; resources.ApplyResources(this.button12, "button12"); this.button12.BackgroundImage = null; this.button12.Font = null; this.button12.Name = "button12"; this.button12.UseVisualStyleBackColor = true; this.button12.Click += new System.EventHandler(this.button12_Click); // // txtDataSource // this.txtDataSource.AccessibleDescription = null; this.txtDataSource.AccessibleName = null; resources.ApplyResources(this.txtDataSource, "txtDataSource"); this.txtDataSource.BackgroundImage = null; this.txtDataSource.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtDataSource.Font = null; this.txtDataSource.Name = "txtDataSource"; // // raMySqlTask // this.raMySqlTask.AccessibleDescription = null; this.raMySqlTask.AccessibleName = null; resources.ApplyResources(this.raMySqlTask, "raMySqlTask"); this.raMySqlTask.BackgroundImage = null; this.raMySqlTask.Font = null; this.raMySqlTask.Name = "raMySqlTask"; this.raMySqlTask.UseVisualStyleBackColor = true; // // raMSSQLTask // this.raMSSQLTask.AccessibleDescription = null; this.raMSSQLTask.AccessibleName = null; resources.ApplyResources(this.raMSSQLTask, "raMSSQLTask"); this.raMSSQLTask.BackgroundImage = null; this.raMSSQLTask.Font = null; this.raMSSQLTask.Name = "raMSSQLTask"; this.raMSSQLTask.UseVisualStyleBackColor = true; // // raAccessTask // this.raAccessTask.AccessibleDescription = null; this.raAccessTask.AccessibleName = null; resources.ApplyResources(this.raAccessTask, "raAccessTask"); this.raAccessTask.BackgroundImage = null; this.raAccessTask.Checked = true; this.raAccessTask.Font = null; this.raAccessTask.Name = "raAccessTask"; this.raAccessTask.TabStop = true; this.raAccessTask.UseVisualStyleBackColor = true; // // label8 // this.label8.AccessibleDescription = null; this.label8.AccessibleName = null; resources.ApplyResources(this.label8, "label8"); this.label8.Font = null; this.label8.Name = "label8"; // // label6 // this.label6.AccessibleDescription = null; this.label6.AccessibleName = null; resources.ApplyResources(this.label6, "label6"); this.label6.Font = null; this.label6.Name = "label6"; // // panel2 // this.panel2.AccessibleDescription = null; this.panel2.AccessibleName = null; resources.ApplyResources(this.panel2, "panel2"); this.panel2.BackgroundImage = null; this.panel2.Controls.Add(this.txtPara); this.panel2.Controls.Add(this.label3); this.panel2.Controls.Add(this.button1); this.panel2.Controls.Add(this.txtFileName); this.panel2.Controls.Add(this.label2); this.panel2.Font = null; this.panel2.Name = "panel2"; // // txtPara // this.txtPara.AccessibleDescription = null; this.txtPara.AccessibleName = null; resources.ApplyResources(this.txtPara, "txtPara"); this.txtPara.BackgroundImage = null; this.txtPara.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtPara.Font = null; this.txtPara.Name = "txtPara"; // // label3 // this.label3.AccessibleDescription = null; this.label3.AccessibleName = null; resources.ApplyResources(this.label3, "label3"); this.label3.Font = null; this.label3.Name = "label3"; // // button1 // this.button1.AccessibleDescription = null; this.button1.AccessibleName = null; resources.ApplyResources(this.button1, "button1"); this.button1.BackgroundImage = null; this.button1.Font = null; this.button1.Name = "button1"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // txtFileName // this.txtFileName.AccessibleDescription = null; this.txtFileName.AccessibleName = null; resources.ApplyResources(this.txtFileName, "txtFileName"); this.txtFileName.BackgroundImage = null; this.txtFileName.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtFileName.Font = null; this.txtFileName.Name = "txtFileName"; // // label2 // this.label2.AccessibleDescription = null; this.label2.AccessibleName = null; resources.ApplyResources(this.label2, "label2"); this.label2.Font = null; this.label2.Name = "label2"; // // groupBox2 // this.groupBox2.AccessibleDescription = null; this.groupBox2.AccessibleName = null; resources.ApplyResources(this.groupBox2, "groupBox2"); this.groupBox2.BackgroundImage = null; this.groupBox2.Font = null; this.groupBox2.Name = "groupBox2"; this.groupBox2.TabStop = false; // // openFileDialog1 // resources.ApplyResources(this.openFileDialog1, "openFileDialog1"); // // raDataTask // this.raDataTask.AccessibleDescription = null; this.raDataTask.AccessibleName = null; resources.ApplyResources(this.raDataTask, "raDataTask"); this.raDataTask.BackgroundImage = null; this.raDataTask.Font = null; this.raDataTask.Name = "raDataTask"; this.raDataTask.TabStop = true; this.raDataTask.UseVisualStyleBackColor = true; this.raDataTask.CheckedChanged += new System.EventHandler(this.raDataTask_CheckedChanged); // // cmdCancel // this.cmdCancel.AccessibleDescription = null; this.cmdCancel.AccessibleName = null; resources.ApplyResources(this.cmdCancel, "cmdCancel"); this.cmdCancel.BackgroundImage = null; this.cmdCancel.Font = null; this.cmdCancel.Name = "cmdCancel"; this.cmdCancel.UseVisualStyleBackColor = true; this.cmdCancel.Click += new System.EventHandler(this.cmdCancel_Click); // // cmdOK // this.cmdOK.AccessibleDescription = null; this.cmdOK.AccessibleName = null; resources.ApplyResources(this.cmdOK, "cmdOK"); this.cmdOK.BackgroundImage = null; this.cmdOK.Font = null; this.cmdOK.Name = "cmdOK"; this.cmdOK.UseVisualStyleBackColor = true; this.cmdOK.Click += new System.EventHandler(this.cmdOK_Click); // // frmAddPlanTask // this.AccessibleDescription = null; this.AccessibleName = null; resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackgroundImage = null; this.Controls.Add(this.raDataTask); this.Controls.Add(this.cmdCancel); this.Controls.Add(this.cmdOK); this.Controls.Add(this.groupBox2); this.Controls.Add(this.groupBox1); this.Controls.Add(this.raOtherTask); this.Controls.Add(this.raSoukeyTask); this.Font = null; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "frmAddPlanTask"; this.Load += new System.EventHandler(this.frmAddPlanTask_Load); this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.frmAddPlanTask_FormClosed); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); this.groupBox1.ResumeLayout(false); this.panel3.ResumeLayout(false); this.panel3.PerformLayout(); this.panel2.ResumeLayout(false); this.panel2.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.RadioButton raSoukeyTask; private System.Windows.Forms.RadioButton raOtherTask; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.ListView listTask; private System.Windows.Forms.ColumnHeader columnHeader1; private System.Windows.Forms.ColumnHeader columnHeader2; private System.Windows.Forms.ColumnHeader columnHeader3; private System.Windows.Forms.ColumnHeader columnHeader4; private System.Windows.Forms.Label label1; private System.Windows.Forms.ComboBox comTaskClass; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.Button cmdCancel; private System.Windows.Forms.Button cmdOK; private System.Windows.Forms.Panel panel2; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox txtPara; private System.Windows.Forms.Label label3; private System.Windows.Forms.Button button1; private System.Windows.Forms.TextBox txtFileName; private System.Windows.Forms.OpenFileDialog openFileDialog1; private System.Windows.Forms.RadioButton raDataTask; private System.Windows.Forms.Panel panel3; private System.Windows.Forms.ComboBox comTableName; private System.Windows.Forms.Button button12; private System.Windows.Forms.TextBox txtDataSource; private System.Windows.Forms.RadioButton raMySqlTask; private System.Windows.Forms.RadioButton raMSSQLTask; private System.Windows.Forms.RadioButton raAccessTask; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label label6; } }
zhouweiaccp/code
SoukeyNetget/frmAddPlanTask.Designer.cs
C#
apache-2.0
20,352
import os from ..libs import xlrd_tools HERE = os.path.dirname(os.path.abspath(__file__)) def test_xlsx_xlrd(): with open(os.path.join(HERE, 'fixtures', 'test.xlsx')) as fp: headers, data = xlrd_tools.xlsx_xlrd(fp) assert headers[0] == {'field': 'one', 'id': 'one', 'name': 'one'} assert data[0] == {'one': 'a', 'two': 'b', 'three': 'c'}
chrisseto/modular-file-renderer
mfr/ext/tabular/tests/test_xlsx_tools.py
Python
apache-2.0
362
package com.ecas.base; import com.ecas.domain.User; import java.util.Date; import javax.persistence.Column; import javax.persistence.MappedSuperclass; @MappedSuperclass public abstract class BaseDomain extends AbstractDomain { private User updateUser; @Column(name = "update_time") private Date updateTime; public User getUpdateUser() { return updateUser; } public void setUpdateUser(User updateUser) { this.updateUser = updateUser; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } }
mrhailua/ecas
domain/src/main/java/com/ecas/base/BaseDomain.java
Java
apache-2.0
682
package ru.nivanov; import org.json.simple.JSONObject; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.io.PrintWriter; /** * Created by Nikolay Ivanov on 27.03.2018. */ public class UserFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; HttpSession session = request.getSession(false); String role = (String) session.getAttribute("rolename"); if (role.equals("admin")) { filterChain.doFilter(request, response); } else { JSONObject object = new JSONObject(); object.put("result", "cannot perform operation, you are not admin"); response.setContentType("application/json"); PrintWriter out = response.getWriter(); out.println(object); out.flush(); } } @Override public void destroy() { } }
Piterski72/Java-a-to-z
chapter_009/Task08/src/main/java/ru/nivanov/UserFilter.java
Java
apache-2.0
1,401
package org.apereo.cas.configuration.model.support.cookie; import org.apereo.cas.configuration.support.RequiresModule; import com.fasterxml.jackson.annotation.JsonFilter; import lombok.Getter; import lombok.Setter; import lombok.experimental.Accessors; import org.apache.commons.lang3.StringUtils; import java.io.Serializable; /** * Common properties for all cookie configs. * * @author Dmitriy Kopylenko * @since 5.0.0 */ @RequiresModule(name = "cas-server-core-cookie", automated = true) @Getter @Setter @Accessors(chain = true) @JsonFilter("CookieProperties") public class CookieProperties implements Serializable { private static final long serialVersionUID = 6804770601645126835L; /** * Cookie name. Constructs a cookie with a specified name and value. * The name must conform to RFC 2965. That means it can contain only ASCII alphanumeric characters and * cannot contain commas, semicolons, or white space or begin with a $ character. * The cookie's name cannot be changed after creation. * By default, cookies are created according to the RFC 2965 cookie specification. */ private String name; /** * Cookie path. * Specifies a path for the cookie to which the client should return the cookie. * The cookie is visible to all the pages in the directory you specify, and all the pages in that directory's * subdirectories. A cookie's path must include the servlet that set the cookie, for example, /catalog, * which makes the cookie visible to all directories on the server under /catalog. * Consult RFC 2965 (available on the Internet) for more information on setting path names for cookies. */ private String path = StringUtils.EMPTY; /** * Cookie domain. Specifies the domain within which this cookie should be presented. * The form of the domain name is specified by RFC 2965. A domain name begins with a dot (.foo.com) * and means that the cookie is visible to servers in a * specified Domain Name System (DNS) zone (for example, www.foo.com, but not a.b.foo.com). * By default, cookies are only returned to the server that sent them. */ private String domain = StringUtils.EMPTY; /** * CAS Cookie comment, describes the cookie's usage and purpose. */ private String comment = "CAS Cookie"; /** * True if sending this cookie should be restricted to a secure protocol, or * false if the it can be sent using any protocol. */ private boolean secure = true; /** * true if this cookie contains the HttpOnly attribute. This means that the cookie should * not be accessible to scripting engines, like javascript. */ private boolean httpOnly = true; /** * The maximum age of the cookie, specified in seconds. By default, -1 indicating the cookie will persist until browser shutdown. * A positive value indicates that the cookie will expire after that many seconds have passed. Note that the value is * the maximum age when the cookie will expire, not the cookie's current age. * A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits. * A zero value causes the cookie to be deleted. */ private int maxAge = -1; /** * When generating cookie values, determine whether the value * should be compounded and signed with the properties of * the current session, such as IP address, user-agent, etc. */ private boolean pinToSession = true; /** * If a cookie is only intended to be accessed in a first party context, the * developer has the option to apply one of settings * {@code SameSite=Lax or SameSite=Strict or SameSite=None} to prevent external access. * <p> * To safeguard more websites and their users, the new secure-by-default model * assumes all cookies should be protected from external access unless otherwise * specified. Developers must use a new cookie setting, {@code SameSite=None}, to designate * cookies for cross-site access. When the {@code SameSite=None} attribute is present, an additional * {@code Secure} attribute is used so cross-site cookies can only be accessed over HTTPS * connections. * </p> * <p>Accepted values are: {@code Lax}, {@code Strict}, {@code None}.</p> */ private String sameSitePolicy = StringUtils.EMPTY; }
pdrados/cas
api/cas-server-core-api-configuration-model/src/main/java/org/apereo/cas/configuration/model/support/cookie/CookieProperties.java
Java
apache-2.0
4,453
#include "OI.h" #include "WPILib.h" #include "RobotMap.h" #include "Commands/Elevator/Lift.h" #include "Commands/Elevator/Lower.h" #include "Commands/Grabber/OpenArms.h" #include "Commands/Grabber/CloseArms.h" #include "Commands/Chassis/Drive.h" #include "Commands/PutToSmartDashboard.h" OI::OI() { this->stick = new Joystick(JOYSTICK_CHANNEL); for (int i = 0; i < 10; i++) { this->buttons[i] = new JoystickButton(this->stick, i + 1); } this->autoSwitch1 = new DigitalInput(AUTONOMOUS_SWITCH1); this->autoSwitch2 = new DigitalInput(AUTONOMOUS_SWITCH2); this->buttons[0]->WhenPressed(new OpenArms()); // 'A' Button this->buttons[1]->WhenPressed(new CloseArms()); // 'B' Button this->buttons[3]->WhileHeld(new Drive(0.3, 0)); // 'Y' Button this->buttons[4]->WhileHeld(new Lower()); // 'LB' Button this->buttons[5]->WhileHeld(new Lift()); // 'RB' Button Scheduler::GetInstance()->AddCommand(new PutToSmartDashboard()); } Joystick* OI::getJoystick() { return this->stick; } JoystickButton** OI::GetButtons() { return this->buttons; } DigitalInput* OI::GetAutonomousSwitch1() { return this->autoSwitch1; } DigitalInput* OI::GetAutonomousSwitch2() { return this->autoSwitch2; }
NeatTeam1943/Slifer
src/OI.cpp
C++
apache-2.0
1,198
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # Copyright 2011 Justin Santa Barbara # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import functools import json from oslo_config import cfg from oslo_log import log as logging from conveyor.clone.drivers import driver from conveyor.clone.resources import common from conveyor.conveyoragentclient.v1 import client as birdiegatewayclient from conveyor.i18n import _LE from conveyor.i18n import _LW from conveyor import exception from conveyor import utils CONF = cfg.CONF LOG = logging.getLogger(__name__) class OpenstackDriver(driver.BaseDriver): def __init__(self): super(OpenstackDriver, self).__init__() def handle_resources(self, context, plan_id, resource_map, sys_clone, copy_data): LOG.debug('Begin handle resources') undo_mgr = utils.UndoManager() try: self._add_extra_properties(context, resource_map, sys_clone, copy_data, undo_mgr) # self._set_resources_state(context, resource_map) return undo_mgr except Exception as e: LOG.error(_LE('Generate template of plan failed, err:%s'), str(e)) undo_mgr._rollback() raise exception.ExportTemplateFailed(id=plan_id, msg=str(e)) def _set_resources_state(self, context, resource_map): for key, value in resource_map.items(): resource_type = value.type resource_id = value.id if resource_type == 'OS::Nova::Server': self.compute_api.reset_state(context, resource_id, 'cloning') elif resource_type == 'OS::Cinder::Volume': self.volume_api.reset_state(context, resource_id, 'cloning') elif resource_type == 'OS::Heat::Stack': self._set_resources_state_for_stack(context, value) def _set_resources_state_for_stack(self, context, resource): template_str = resource.properties.get('template') template = json.loads(template_str) def _set_state(template): temp_res = template.get('resources') for key, value in temp_res.items(): res_type = value.get('type') if res_type == 'OS::Cinder::Volume': vid = value.get('extra_properties', {}).get('id') if vid: self.volume_api.reset_state(context, vid, 'cloning') elif res_type == 'OS::Nova::Server': sid = value.get('extra_properties', {}).get('id') if sid: self.compute_api.reset_state(context, sid, 'cloning') elif res_type and res_type.startswith('file://'): son_template = value.get('content') son_template = json.loads(son_template) _set_state(son_template) _set_state(template) def add_extra_properties_for_server(self, context, resource, resource_map, sys_clone, copy_data, undo_mgr): migrate_net_map = CONF.migrate_net_map server_properties = resource.properties server_id = resource.id server_extra_properties = resource.extra_properties server_az = server_properties.get('availability_zone') vm_state = server_extra_properties.get('vm_state') gw_url = server_extra_properties.get('gw_url') if not gw_url: if vm_state == 'stopped': gw_id, gw_ip = utils.get_next_vgw(server_az) if not gw_id or not gw_ip: raise exception.V2vException(message='no vgw host found') gw_url = gw_ip + ':' + str(CONF.v2vgateway_api_listen_port) resource.extra_properties.update({"gw_url": gw_url, "gw_id": gw_id}) resource.extra_properties['sys_clone'] = sys_clone resource.extra_properties['is_deacidized'] = True block_device_mapping = server_properties.get( 'block_device_mapping_v2') if block_device_mapping: for block_device in block_device_mapping: volume_name = block_device.get('volume_id').get( 'get_resource') volume_resource = resource_map.get(volume_name) volume_resource.extra_properties['gw_url'] = gw_url volume_resource.extra_properties['is_deacidized'] = \ True boot_index = block_device.get('boot_index') dev_name = block_device.get('device_name') if boot_index == 0 or boot_index == '0': volume_resource.extra_properties['sys_clone'] = \ sys_clone if sys_clone: self._handle_dv_for_svm(context, volume_resource, server_id, dev_name, gw_id, gw_ip, undo_mgr) else: d_copy = copy_data and volume_resource. \ extra_properties['copy_data'] volume_resource.extra_properties['copy_data'] = \ d_copy if not d_copy: continue self._handle_dv_for_svm(context, volume_resource, server_id, dev_name, gw_id, gw_ip, undo_mgr) else: if migrate_net_map: # get the availability_zone of server server_az = server_properties.get('availability_zone') if not server_az: LOG.error(_LE('Not get the availability_zone' 'of server %s') % resource.id) raise exception.AvailabilityZoneNotFound( server_uuid=resource.id) migrate_net_id = migrate_net_map.get(server_az) if not migrate_net_id: LOG.error(_LE('Not get the migrate net of server %s') % resource.id) raise exception.NoMigrateNetProvided( server_uuid=resource.id) # attach interface LOG.debug('Attach a port of net %s to server %s', migrate_net_id, server_id) obj = self.compute_api.interface_attach(context, server_id, migrate_net_id, None, None) interface_attachment = obj._info if interface_attachment: LOG.debug('The interface attachment info is %s ' % str(interface_attachment)) migrate_fix_ip = interface_attachment.get('fixed_ips')[0] \ .get('ip_address') migrate_port_id = interface_attachment.get('port_id') undo_mgr.undo_with(functools.partial (self.compute_api.interface_detach, context, server_id, migrate_port_id)) gw_url = migrate_fix_ip + ':' + str( CONF.v2vgateway_api_listen_port) extra_properties = {} extra_properties['gw_url'] = gw_url extra_properties['is_deacidized'] = True extra_properties['migrate_port_id'] = migrate_port_id extra_properties['sys_clone'] = sys_clone resource.extra_properties.update(extra_properties) # waiting port attach finished, and can ping this vm self._await_port_status(context, migrate_port_id, migrate_fix_ip) # else: # interfaces = self.neutron_api.port_list( # context, device_id=server_id) # host_ip = None # for infa in interfaces: # if host_ip: # break # binding_profile = infa.get("binding:profile", []) # if binding_profile: # host_ip = binding_profile.get('host_ip') # if not host_ip: # LOG.error(_LE('Not find the clone data # ip for server')) # raise exception.NoMigrateNetProvided( # server_uuid=resource.id # ) # gw_url = host_ip + ':' + str( # CONF.v2vgateway_api_listen_port) # extra_properties = {} # extra_properties['gw_url'] = gw_url # extra_properties['sys_clone'] = sys_clone # resource.extra_properties.update(extra_properties) block_device_mapping = server_properties.get( 'block_device_mapping_v2') if block_device_mapping: client = None if gw_url: gw_urls = gw_url.split(':') client = birdiegatewayclient.get_birdiegateway_client( gw_urls[0], gw_urls[1]) for block_device in block_device_mapping: device_name = block_device.get('device_name') volume_name = block_device.get('volume_id').get( 'get_resource') volume_resource = resource_map.get(volume_name) boot_index = block_device.get('boot_index') if boot_index == 0 or boot_index == '0': volume_resource.extra_properties['sys_clone'] = \ sys_clone if not sys_clone: continue else: d_copy = copy_data and volume_resource. \ extra_properties['copy_data'] volume_resource.extra_properties['copy_data'] = \ d_copy if not d_copy: continue # need to check the vm disk name if not client: continue src_dev_format = client.vservices. \ get_disk_format(device_name).get('disk_format') src_mount_point = client. \ vservices.get_disk_mount_point(device_name). \ get('mount_point') volume_resource.extra_properties['guest_format'] = \ src_dev_format volume_resource.extra_properties['mount_point'] = \ src_mount_point volume_resource.extra_properties['gw_url'] = gw_url volume_resource.extra_properties['is_deacidized'] = \ True sys_dev_name = client. \ vservices.get_disk_name(volume_resource.id). \ get('dev_name') if not sys_dev_name: sys_dev_name = device_name volume_resource.extra_properties['sys_dev_name'] = \ sys_dev_name def _handle_sv_for_svm(self, context, vol_res, gw_id, gw_ip, undo_mgr): volume_id = vol_res.id LOG.debug('Set the volume %s shareable', volume_id) self.volume_api.set_volume_shareable(context, volume_id, True) undo_mgr.undo_with(functools.partial(self._set_volume_shareable, context, volume_id, False)) client = birdiegatewayclient.get_birdiegateway_client( gw_ip, str(CONF.v2vgateway_api_listen_port) ) disks = set(client.vservices.get_disk_name().get('dev_name')) self.compute_api.attach_volume(context, gw_id, volume_id, None) LOG.debug('Attach the volume %s to gw host %s ', volume_id, gw_id) undo_mgr.undo_with(functools.partial(self._detach_volume, context, gw_id, volume_id)) self._wait_for_volume_status(context, volume_id, gw_id, 'in-use') n_disks = set(client.vservices.get_disk_name().get('dev_name')) diff_disk = n_disks - disks LOG.debug('Begin get info for volume,the vgw ip %s' % gw_ip) client = birdiegatewayclient.get_birdiegateway_client( gw_ip, str(CONF.v2vgateway_api_listen_port)) # sys_dev_name = client.vservices.get_disk_name(volume_id).get( # 'dev_name') # sys_dev_name = device_name # sys_dev_name = attach_resp._info.get('device') sys_dev_name = list(diff_disk)[0] if len(diff_disk) >= 1 else None LOG.debug("dev_name = %s", sys_dev_name) vol_res.extra_properties['sys_dev_name'] = sys_dev_name guest_format = client.vservices.get_disk_format(sys_dev_name) \ .get('disk_format') if guest_format: vol_res.extra_properties['guest_format'] = guest_format mount_point = client.vservices.force_mount_disk( sys_dev_name, "/opt/" + volume_id) vol_res.extra_properties['mount_point'] = mount_point.get( 'mount_disk') def add_extra_properties_for_stack(self, context, resource, sys_clone, copy_data, undo_mgr): res_prop = resource.properties stack_id = resource.id template = json.loads(res_prop.get('template')) def _add_extra_prop(template, stack_id): temp_res = template.get('resources') for key, value in temp_res.items(): res_type = value.get('type') if res_type == 'OS::Cinder::Volume': # v_prop = value.get('properties') v_exra_prop = value.get('extra_properties', {}) d_copy = copy_data and v_exra_prop['copy_data'] v_exra_prop['copy_data'] = d_copy if not d_copy: continue if not v_exra_prop or not v_exra_prop.get('gw_url'): phy_id = v_exra_prop.get('id') res_info = self.volume_api.get(context, phy_id) az = res_info.get('availability_zone') gw_id, gw_ip = utils.get_next_vgw(az) if not gw_id or not gw_ip: raise exception.V2vException( message='no vgw host found') gw_url = gw_ip + ':' + str( CONF.v2vgateway_api_listen_port) v_exra_prop.update({"gw_url": gw_url, "gw_id": gw_id}) volume_status = res_info['status'] v_exra_prop['status'] = volume_status value['extra_properties'] = v_exra_prop value['id'] = phy_id self._handle_volume_for_stack(context, value, gw_id, gw_ip, undo_mgr) elif res_type == 'OS::Nova::Server': v_exra_prop = value.get('extra_properties', {}) phy_id = v_exra_prop.get('id') server_info = self.compute_api.get_server(context, phy_id) vm_state = server_info.get('OS-EXT-STS:vm_state', None) v_exra_prop['vm_state'] = vm_state value['extra_properties'] = v_exra_prop _add_extra_prop(template, stack_id) res_prop['template'] = json.dumps(template) def _handle_volume_for_stack(self, context, vol_res, gw_id, gw_ip, undo_mgr): volume_id = vol_res.get('id') volume_info = self.volume_api.get(context, volume_id) volume_status = volume_info['status'] v_shareable = volume_info['shareable'] if not v_shareable and volume_status == 'in-use': volume_attachments = volume_info.get('attachments', []) vol_res.get('extra_properties')['attachments'] = volume_attachments for attachment in volume_attachments: server_id = attachment.get('server_id') server_info = self.compute_api.get_server(context, server_id) vm_state = server_info.get('OS-EXT-STS:vm_state', None) if vm_state != 'stopped': _msg = 'the server %s not stopped' % server_id raise exception.V2vException(message=_msg) device = attachment.get('device') self.compute_api.detach_volume(context, server_id, volume_id) self._wait_for_volume_status(context, volume_id, server_id, 'available') undo_mgr.undo_with(functools.partial(self._attach_volume, context, server_id, volume_id, device)) client = birdiegatewayclient.get_birdiegateway_client( gw_ip, str(CONF.v2vgateway_api_listen_port) ) disks = set(client.vservices.get_disk_name().get('dev_name')) LOG.debug('Attach volume %s to gw host %s', volume_id, gw_id) attach_resp = self.compute_api.attach_volume(context, gw_id, volume_id, None) LOG.debug('The volume attachment info is %s ' % str(attach_resp)) undo_mgr.undo_with(functools.partial(self._detach_volume, context, gw_id, volume_id)) self._wait_for_volume_status(context, volume_id, gw_id, 'in-use') n_disks = set(client.vservices.get_disk_name().get('dev_name')) diff_disk = n_disks - disks vol_res.get('extra_properties')['status'] = 'in-use' LOG.debug('Begin get info for volume,the vgw ip %s' % gw_ip) sys_dev_name = list(diff_disk)[0] if len(diff_disk) >= 1 else None LOG.debug("dev_name = %s", sys_dev_name) # device_name = attach_resp._info.get('device') # sys_dev_name = client.vservices.get_disk_name(volume_id).get( # 'dev_name') # sys_dev_name = device_name vol_res.get('extra_properties')['sys_dev_name'] = sys_dev_name guest_format = client.vservices.get_disk_format(sys_dev_name) \ .get('disk_format') if guest_format: vol_res.get('extra_properties')['guest_format'] = guest_format mount_point = client.vservices.force_mount_disk( sys_dev_name, "/opt/" + volume_id) vol_res.get('extra_properties')['mount_point'] = mount_point.get( 'mount_disk') def reset_resources(self, context, resources): # self._reset_resources_state(context, resources) self._handle_resources_after_clone(context, resources) def _reset_resources_state(self, context, resources): for key, value in resources.items(): try: resource_type = value.get('type') resource_id = value.get('extra_properties', {}).get('id') if resource_type == 'OS::Nova::Server': vm_state = value.get('extra_properties', {}) \ .get('vm_state') self.compute_api.reset_state(context, resource_id, vm_state) elif resource_type == 'OS::Cinder::Volume': volume_state = value.get('extra_properties', {}) \ .get('status') self.volume_api.reset_state(context, resource_id, volume_state) elif resource_type == 'OS::Heat::Stack': self._reset_resources_state_for_stack(context, value) except Exception as e: LOG.warn(_LW('Reset resource state error, Error=%(e)s'), {'e': e}) def _reset_resources_state_for_stack(self, context, stack_res): template_str = stack_res.get('properties', {}).get('template') template = json.loads(template_str) def _reset_state(template): temp_res = template.get('resources') for key, value in temp_res.items(): res_type = value.get('type') if res_type == 'OS::Cinder::Volume': vid = value.get('extra_properties', {}).get('id') v_state = value.get('extra_properties', {}).get('status') if vid: self.volume_api.reset_state(context, vid, v_state) elif res_type == 'OS::Nova::Server': sid = value.get('extra_properties', {}).get('id') s_state = value.get('extra_properties', {}).get('vm_state') if sid: self.compute_api.reset_state(context, sid, s_state) elif res_type and res_type.startswith('file://'): son_template = value.get('content') son_template = json.loads(son_template) _reset_state(son_template) _reset_state(template) def handle_server_after_clone(self, context, resource, resources): self._detach_server_temporary_port(context, resource) extra_properties = resource.get('extra_properties', {}) vm_state = extra_properties.get('vm_state') if vm_state == 'stopped': self._handle_volume_for_svm_after_clone(context, resource, resources) def handle_stack_after_clone(self, context, resource, resources): template_str = resource.get('properties', {}).get('template') template = json.loads(template_str) self._handle_volume_for_stack_after_clone(context, template) def _handle_volume_for_stack_after_clone(self, context, template): try: resources = template.get('resources') for key, res in resources.items(): res_type = res.get('type') if res_type == 'OS::Cinder::Volume': try: copy_data = res.get('extra_properties', {}). \ get('copy_data') if not copy_data: continue attachments = res.get('extra_properties', {}) \ .get('attachments') volume_id = res.get('extra_properties', {}) \ .get('id') vgw_id = res.get('extra_properties').get('gw_id') self._detach_volume(context, vgw_id, volume_id) if attachments: for attachment in attachments: server_id = attachment.get('server_id') device = attachment.get('device') self.compute_api.attach_volume(context, server_id, volume_id, device) except Exception as e: LOG.error(_LE('Error from handle volume of stack after' ' clone.' 'Error=%(e)s'), {'e': e}) except Exception as e: LOG.warn('detach the volume %s from vgw %s error,' 'the volume not attached to vgw', volume_id, vgw_id) def _handle_volume_for_svm_after_clone(self, context, server_resource, resources): bdms = server_resource['properties'].get('block_device_mapping_v2', []) vgw_id = server_resource.get('extra_properties', {}).get('gw_id') for bdm in bdms: volume_key = bdm.get('volume_id', {}).get('get_resource') boot_index = bdm.get('boot_index') device_name = bdm.get('device_name') volume_res = resources.get(volume_key) try: if volume_res.get('extra_properties', {}).get('is_deacidized'): volume_id = volume_res.get('extra_properties', {}) \ .get('id') vgw_url = volume_res.get('extra_properties', {}) \ .get('gw_url') sys_clone = volume_res.get('extra_properties', {}) \ .get('sys_clone') copy_data = volume_res.get('extra_properties', {}). \ get('copy_data') if (boot_index in ['0', 0] and not sys_clone) or \ not copy_data: continue vgw_ip = vgw_url.split(':')[0] client = birdiegatewayclient.get_birdiegateway_client( vgw_ip, str(CONF.v2vgateway_api_listen_port)) if boot_index not in ['0', 0] or sys_clone: client.vservices._force_umount_disk( "/opt/" + volume_id) # if provider cloud can not detcah volume in active status if not CONF.is_active_detach_volume: resouce_common = common.ResourceCommon() self.compute_api.stop_server(context, vgw_id) resouce_common._await_instance_status(context, vgw_id, 'SHUTOFF') self.compute_api.detach_volume(context, vgw_id, volume_id) self._wait_for_volume_status(context, volume_id, vgw_id, 'available') server_id = server_resource.get('extra_properties', {}) \ .get('id') self.compute_api.attach_volume(context, server_id, volume_id, device_name) self._wait_for_volume_status(context, volume_id, server_id, 'in-use') if not CONF.is_active_detach_volume: self.compute_api.start_server(context, vgw_id) resouce_common._await_instance_status(context, vgw_id, 'ACTIVE') except Exception as e: LOG.error(_LE('Error from handle volume of vm after' ' clone.' 'Error=%(e)s'), {'e': e}) def _detach_server_temporary_port(self, context, server_res): # Read template file of this plan server_id = server_res.get('extra_properties', {}).get('id') migrate_port = server_res.get('extra_properties', {}) \ .get('migrate_port_id') if server_res.get('extra_properties', {}).get('is_deacidized'): if not server_id or not migrate_port: return try: self.compute_api.migrate_interface_detach(context, server_id, migrate_port) LOG.debug("Detach migrate port of server <%s> succeed.", server_id) except Exception as e: LOG.error("Fail to detach migrate port of server <%s>. %s", server_id, unicode(e))
Hybrid-Cloud/conveyor
conveyor/clone/drivers/openstack/driver.py
Python
apache-2.0
31,506
/* * Copyright 2015 Ayuget * * 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.ayuget.redface.ui; import com.ayuget.redface.RedfaceApp; import com.ayuget.redface.account.AccountModule; import com.ayuget.redface.account.UserManager; import com.ayuget.redface.image.ImageModule; import com.ayuget.redface.settings.RedfaceSettings; import com.ayuget.redface.ui.activity.AccountActivity; import com.ayuget.redface.ui.activity.EditPostActivity; import com.ayuget.redface.ui.activity.ExifDetailsActivity; import com.ayuget.redface.ui.activity.ImageSharingActivity; import com.ayuget.redface.ui.activity.PrivateMessagesActivity; import com.ayuget.redface.ui.activity.ReplyActivity; import com.ayuget.redface.ui.activity.SettingsActivity; import com.ayuget.redface.ui.activity.TopicsActivity; import com.ayuget.redface.ui.activity.WritePrivateMessageActivity; import com.ayuget.redface.ui.fragment.DefaultFragment; import com.ayuget.redface.ui.fragment.DetailsDefaultFragment; import com.ayuget.redface.ui.fragment.HomePreferenceFragment; import com.ayuget.redface.ui.fragment.MetaPageFragment; import com.ayuget.redface.ui.fragment.NestedPreferenceFragment; import com.ayuget.redface.ui.fragment.PostsFragment; import com.ayuget.redface.ui.fragment.PrivateMessageListFragment; import com.ayuget.redface.ui.fragment.TopicFragment; import com.ayuget.redface.ui.fragment.TopicListFragment; import com.ayuget.redface.ui.misc.ImageMenuHandler; import com.ayuget.redface.ui.misc.ThemeManager; import com.ayuget.redface.ui.template.AvatarTemplate; import com.ayuget.redface.ui.template.PostActionsTemplate; import com.ayuget.redface.ui.template.PostExtraDetailsTemplate; import com.ayuget.redface.ui.template.PostTemplate; import com.ayuget.redface.ui.template.PostsTemplate; import com.ayuget.redface.ui.template.QuickActionsTemplate; import com.ayuget.redface.ui.template.SmileyTemplate; import com.ayuget.redface.ui.template.SmileysTemplate; import com.ayuget.redface.ui.view.SmileySelectorView; import com.ayuget.redface.ui.view.TopicPageView; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; @Module( includes = { AccountModule.class, ImageModule.class }, injects = { TopicsActivity.class, TopicListFragment.class, TopicPageView.class, PostsFragment.class, TopicFragment.class, DefaultFragment.class, DetailsDefaultFragment.class, AccountActivity.class, ReplyActivity.class, SmileySelectorView.class, NestedPreferenceFragment.class, HomePreferenceFragment.class, SettingsActivity.class, EditPostActivity.class, MetaPageFragment.class, PrivateMessagesActivity.class, PrivateMessageListFragment.class, WritePrivateMessageActivity.class, ExifDetailsActivity.class, ImageSharingActivity.class }, library = true, complete = false ) public class UIModule { @Provides @Singleton AvatarTemplate provideAvatarTemplate(RedfaceApp app) { return new AvatarTemplate(app.getApplicationContext()); } @Provides @Singleton SmileyTemplate provideSmileyTemplate(RedfaceApp app) { return new SmileyTemplate(app.getApplicationContext()); } @Provides @Singleton QuickActionsTemplate provideQuickActions(RedfaceApp app, UserManager userManager) { return new QuickActionsTemplate(app.getApplicationContext(), userManager); } @Provides @Singleton PostTemplate providePostTemplate(RedfaceApp app, UserManager userManager, AvatarTemplate avatarTemplate, PostExtraDetailsTemplate extraDetailsTemplate, PostActionsTemplate postActionsTemplate, QuickActionsTemplate quickActionsTemplate, RedfaceSettings appSettings) { return new PostTemplate(app.getApplicationContext(), userManager, avatarTemplate, extraDetailsTemplate, postActionsTemplate, quickActionsTemplate, appSettings); } @Provides @Singleton PostsTemplate providePostsTemplate(RedfaceApp app, PostTemplate postTemplate, ThemeManager themeManager) { return new PostsTemplate(app.getApplicationContext(), postTemplate, themeManager); } @Provides @Singleton SmileysTemplate provideSmileysTemplate(RedfaceApp app, SmileyTemplate smileyTemplate, ThemeManager themeManager) { return new SmileysTemplate(app.getApplicationContext(), smileyTemplate, themeManager); } @Provides @Singleton PostActionsTemplate providePostActionsTemplate(RedfaceApp app, UserManager userManager) { return new PostActionsTemplate(app.getApplicationContext(), userManager); } @Provides @Singleton PostExtraDetailsTemplate providePostExtraDetailsTemplate(RedfaceApp app) { return new PostExtraDetailsTemplate(app.getApplicationContext()); } @Provides @Singleton ThemeManager provideThemeManager(RedfaceSettings settings) { return new ThemeManager(settings); } }
nbonnec/Redface
app/src/main/java/com/ayuget/redface/ui/UIModule.java
Java
apache-2.0
5,666
using System; namespace NuGet { public interface IPackageManager { IFileSystem FileSystem { get; set; } IPackageRepository LocalRepository { get; } ILogger Logger { get; set; } IPackageRepository SourceRepository { get; } event EventHandler<PackageOperationEventArgs> PackageInstalled; event EventHandler<PackageOperationEventArgs> PackageInstalling; event EventHandler<PackageOperationEventArgs> PackageUninstalled; event EventHandler<PackageOperationEventArgs> PackageUninstalling; void InstallPackage(IPackage package, bool ignoreDependencies); void InstallPackage(string packageId, Version version, bool ignoreDependencies); void UpdatePackage(IPackage oldPackage, IPackage newPackage, bool updateDependencies); void UpdatePackage(string packageId, Version version, bool updateDependencies); void UninstallPackage(IPackage package, bool forceRemove, bool removeDependencies); void UninstallPackage(string packageId, Version version, bool forceRemove, bool removeDependencies); } }
grendello/nuget
src/Core/IPackageManager.cs
C#
apache-2.0
1,128
package de.tomjanke.lost.game.action; import de.tomjanke.lost.game.world.WorldObject; /** * Created by Tom on 28.05.2016. */ public class WorldObjectAction extends Action { public WorldObject Object; public WorldObjectAction(WorldObject o, float d, Runnable r) { super(d, r); Object = o; } public WorldObjectAction(WorldObject o, float d) { super(d); Object = o; } }
Tom7353/Lost
core/src/de/tomjanke/lost/game/action/WorldObjectAction.java
Java
apache-2.0
427
package org.peace.savingtracker.ui.home; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.View; import butterknife.OnClick; import org.peace.savingtracker.MyApp; import org.peace.savingtracker.R; import org.peace.savingtracker.ui.AddExpenseActivity; import org.peace.savingtracker.ui.accountbook.AddAccountBookActivity; import org.peace.savingtracker.ui.accountbook.SelectAccountBookActivity; import org.peace.savingtracker.ui.user.FriendListActivity; import org.peace.savingtracker.ui.user.MessageCenterActivity; import org.peace.savingtracker.ui.user.SearchUserActivity; import org.peace.savingtracker.ui.user.UserActivity; import org.peace.savingtracker.utils.ResUtil; /** * Created by peacepassion on 15/12/19. */ public class HomeUserCenterFragment extends BaseHomeFragment { public static HomeUserCenterFragment newInstance() { return new HomeUserCenterFragment(); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); } @OnClick({ R.id.user_center, R.id.add_account_book, R.id.select_account_book, R.id.search_user, R.id.message_center, R.id.friend_list }) public void onClick(View v) { int id = v.getId(); switch (id) { case R.id.user_center: startActivity(new Intent(activity, UserActivity.class)); break; case R.id.add_account_book: startActivity(new Intent(activity, AddAccountBookActivity.class)); break; case R.id.select_account_book: startActivity(new Intent(activity, SelectAccountBookActivity.class)); break; case R.id.search_user: startActivity(new Intent(activity, SearchUserActivity.class)); break; case R.id.message_center: startActivity(new Intent(activity, MessageCenterActivity.class)); break; case R.id.friend_list: startActivity(new Intent(activity, FriendListActivity.class)); break; default: break; } } @Override protected int getLayoutRes() { return R.layout.fragment_home_user_center; } @Override public String getTitle() { return ResUtil.getString(R.string.user_center); } }
peacepassion/SavingTracker
app/src/main/java/org/peace/savingtracker/ui/home/HomeUserCenterFragment.java
Java
apache-2.0
2,275
/* * Copyright 2015 Open Networking Laboratory * * 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.onosproject.rest; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.collect.Lists; import org.onosproject.net.ConnectPoint; import org.onosproject.net.DeviceId; import org.onosproject.net.Link; import org.onosproject.net.PortNumber; import org.onosproject.net.topology.ClusterId; import org.onosproject.net.topology.Topology; import org.onosproject.net.topology.TopologyCluster; import org.onosproject.net.topology.TopologyService; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.List; import static org.onlab.util.Tools.nullIsNotFound; /** * REST resource for interacting with the inventory of clusters. */ @Path("topology") public class TopologyWebResource extends AbstractWebResource { public static final String CLUSTER_NOT_FOUND = "Cluster is not found"; /** * Gets the topology overview for a REST GET operation. * * @return topology overview */ @GET @Produces(MediaType.APPLICATION_JSON) public Response getTopology() { Topology topology = get(TopologyService.class).currentTopology(); ObjectNode root = codec(Topology.class).encode(topology, this); return ok(root).build(); } /** * Gets the topology clusters overview for a REST GET operation. * * @return topology clusters overview */ @GET @Produces(MediaType.APPLICATION_JSON) @Path("clusters") public Response getClusters() { TopologyService service = get(TopologyService.class); Topology topology = service.currentTopology(); Iterable<TopologyCluster> clusters = service.getClusters(topology); ObjectNode root = encodeArray(TopologyCluster.class, "clusters", clusters); return ok(root).build(); } /** * Gets details for a topology cluster for a REST GET operation. * * @param clusterId id of the cluster to query * @return topology cluster details */ @GET @Produces(MediaType.APPLICATION_JSON) @Path("clusters/{id}") public Response getCluster(@PathParam("id") int clusterId) { Topology topology = get(TopologyService.class).currentTopology(); TopologyCluster cluster = getTopologyCluster(clusterId, topology); ObjectNode root = codec(TopologyCluster.class).encode(cluster, this); return ok(root).build(); } private TopologyCluster getTopologyCluster(int clusterId, Topology topology) { return nullIsNotFound( get(TopologyService.class) .getCluster(topology, ClusterId.clusterId(clusterId)), CLUSTER_NOT_FOUND); } /** * Gets devices for a topology cluster for a REST GET operation. * * @param clusterId id of the cluster to query * @return topology cluster devices */ @GET @Produces(MediaType.APPLICATION_JSON) @Path("clusters/{id}/devices") public Response getClusterDevices(@PathParam("id") int clusterId) { TopologyService service = get(TopologyService.class); Topology topology = service.currentTopology(); TopologyCluster cluster = getTopologyCluster(clusterId, topology); List<DeviceId> deviceIds = Lists.newArrayList(service.getClusterDevices(topology, cluster)); ObjectNode root = mapper().createObjectNode(); ArrayNode devicesNode = root.putArray("devices"); deviceIds.forEach(id -> devicesNode.add(id.toString())); return ok(root).build(); } /** * Gets links for a topology cluster for a REST GET operation. * * @param clusterId id of the cluster to query * @return topology cluster links */ @GET @Produces(MediaType.APPLICATION_JSON) @Path("clusters/{id}/links") public Response getClusterLinks(@PathParam("id") int clusterId) { Topology topology = get(TopologyService.class).currentTopology(); TopologyCluster cluster = getTopologyCluster(clusterId, topology); List<Link> links = Lists.newArrayList(get(TopologyService.class) .getClusterLinks(topology, cluster)); return ok(encodeArray(Link.class, "links", links)).build(); } /** * Extracts the port number portion of the ConnectPoint. * * @param deviceString string representing the device/port * @return port number as a string, empty string if the port is not found */ private static String getPortNumber(String deviceString) { int separator = deviceString.lastIndexOf(':'); if (separator <= 0) { return ""; } return deviceString.substring(separator + 1, deviceString.length()); } /** * Extracts the device ID portion of the ConnectPoint. * * @param deviceString string representing the device/port * @return device ID string */ private static String getDeviceId(String deviceString) { int separator = deviceString.lastIndexOf(':'); if (separator <= 0) { return ""; } return deviceString.substring(0, separator); } /** * Gets the broadcast flag of a connect point for a REST GET operation. * * @param connectPointString string representation of the connect point to query. * Format is deviceid:portnumber * @return JSON representation of true if the connect point is broadcast, * false otherwise */ @GET @Produces(MediaType.APPLICATION_JSON) @Path("broadcast/{connectPoint}") public Response getConnectPointBroadcast( @PathParam("connectPoint") String connectPointString) { Topology topology = get(TopologyService.class).currentTopology(); DeviceId deviceId = DeviceId.deviceId(getDeviceId(connectPointString)); PortNumber portNumber = PortNumber.portNumber(getPortNumber(connectPointString)); ConnectPoint connectPoint = new ConnectPoint(deviceId, portNumber); boolean isBroadcast = get(TopologyService.class).isBroadcastPoint(topology, connectPoint); return ok(mapper() .createObjectNode() .put("broadcast", isBroadcast)) .build(); } /** * Gets the infrastructure flag of a connect point for a REST GET operation. * * @param connectPointString string representation of the connect point to query. * Format is deviceid:portnumber * @return JSON representation of true if the connect point is broadcast, * false otherwise */ @GET @Produces(MediaType.APPLICATION_JSON) @Path("infrastructure/{connectPoint}") public Response getConnectPointInfrastructure( @PathParam("connectPoint") String connectPointString) { Topology topology = get(TopologyService.class).currentTopology(); DeviceId deviceId = DeviceId.deviceId(getDeviceId(connectPointString)); PortNumber portNumber = PortNumber.portNumber(getPortNumber(connectPointString)); ConnectPoint connectPoint = new ConnectPoint(deviceId, portNumber); boolean isInfrastructure = get(TopologyService.class).isInfrastructure(topology, connectPoint); return ok(mapper() .createObjectNode() .put("infrastructure", isInfrastructure)) .build(); } }
ravikumaran2015/ravikumaran201504
web/api/src/main/java/org/onosproject/rest/TopologyWebResource.java
Java
apache-2.0
8,214
/** * * No descripton provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: 1.6.0 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. * * 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.gatebuzz.oxfordapi.model; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; import java.util.List; import java.util.Objects; /** * Schema for the &#39;sentences&#39; endpoint */ public class SentencesResults { @SerializedName("metadata") private Object metadata = null; @SerializedName("results") private List<SentencesEntry> results = new ArrayList<SentencesEntry>(); public SentencesResults metadata(Object metadata) { this.metadata = metadata; return this; } /** * Additional Information provided by OUP * @return metadata **/ public Object getMetadata() { return metadata; } public void setMetadata(Object metadata) { this.metadata = metadata; } public SentencesResults results(List<SentencesEntry> results) { this.results = results; return this; } public SentencesResults addResultsItem(SentencesEntry resultsItem) { this.results.add(resultsItem); return this; } /** * A list of entries and all the data related to them * @return results **/ public List<SentencesEntry> getResults() { return results; } public void setResults(List<SentencesEntry> results) { this.results = results; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SentencesResults sentencesResults = (SentencesResults) o; return Objects.equals(this.metadata, sentencesResults.metadata) && Objects.equals(this.results, sentencesResults.results); } @Override public int hashCode() { return Objects.hash(metadata, results); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class SentencesResults {\n"); sb.append(" metadata: ").append(toIndentedString(metadata)).append("\n"); sb.append(" results: ").append(toIndentedString(results)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
psh/OxfordDictionarySample
app/src/main/java/com/gatebuzz/oxfordapi/model/SentencesResults.java
Java
apache-2.0
3,199
/** @file @brief Implementation @date 2015 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2015 Sensics, 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. // Internal Includes #include "JointClientContext.h" #include <osvr/Common/SystemComponent.h> #include <osvr/Common/CreateDevice.h> #include <osvr/Common/PathTreeFull.h> #include <osvr/Common/PathElementTools.h> #include <osvr/Common/PathElementTypes.h> #include <osvr/Common/ClientInterface.h> #include <osvr/Util/Verbosity.h> #include <osvr/Common/DeduplicatingFunctionWrapper.h> #include <osvr/Connection/Connection.h> #include <osvr/Server/Server.h> // Library/third-party includes #include <json/value.h> // Standard includes #include <unordered_set> #include <thread> namespace osvr { namespace client { static const auto HOST = "localhost"; static const std::chrono::milliseconds STARTUP_CONNECT_TIMEOUT(200); static const std::chrono::milliseconds STARTUP_TREE_TIMEOUT(1000); static const std::chrono::milliseconds STARTUP_LOOP_SLEEP(1); JointClientContext::JointClientContext(const char appId[], common::ClientContextDeleter del) : ::OSVR_ClientContextObject(appId, del), m_ifaceMgr(m_pathTreeOwner, m_factory, *static_cast<common::ClientContext *>(this)) { /// Create all the remote handler factories. populateRemoteHandlerFactory(m_factory, m_vrpnConns); /// creates the OSVR connection with its nested VRPN connection auto conn = connection::Connection::createLoopbackConnection(); /// Get the VRPN connection out and use it. m_mainConn = static_cast<vrpn_Connection *>(std::get<0>(conn)); m_vrpnConns.addConnection(m_mainConn, HOST); BOOST_ASSERT(!m_vrpnConns.empty()); /// Get the OSVR connection out and use it to make a server. m_server = server::Server::createNonListening(std::get<1>(conn)); std::string sysDeviceName = std::string(common::SystemComponent::deviceName()) + "@" + HOST; /// Create the system client device. m_systemDevice = common::createClientDevice(sysDeviceName, m_mainConn); m_systemComponent = m_systemDevice->addComponent(common::SystemComponent::create()); typedef common::DeduplicatingFunctionWrapper<Json::Value const &> DedupJsonFunction; using DedupJsonFunction = common::DeduplicatingFunctionWrapper<Json::Value const &>; m_systemComponent->registerReplaceTreeHandler( DedupJsonFunction([&](Json::Value nodes) { OSVR_DEV_VERBOSE("Got updated path tree, processing"); // Tree observers will handle destruction/creation of remote // handlers. m_pathTreeOwner.replaceTree(nodes); })); } JointClientContext::~JointClientContext() {} void JointClientContext::m_update() { /// Run the server m_server->update(); /// Mainloop connections m_vrpnConns.updateAll(); /// Update system device m_systemDevice->update(); /// Update handlers. m_ifaceMgr.updateHandlers(); } void JointClientContext::m_sendRoute(std::string const &route) { m_systemComponent->sendClientRouteUpdate(route); m_update(); } void JointClientContext::m_handleNewInterface( common::ClientInterfacePtr const &iface) { m_ifaceMgr.addInterface(iface); } void JointClientContext::m_handleReleasingInterface( common::ClientInterfacePtr const &iface) { m_ifaceMgr.releaseInterface(iface); } bool JointClientContext::m_getStatus() const { /// Always connected, but don't always have a path tree. return bool(m_pathTreeOwner); } common::PathTree const &JointClientContext::m_getPathTree() const { return m_pathTreeOwner.get(); } } // namespace client } // namespace osvr
leemichaelRazer/OSVR-Core
src/osvr/JointClientKit/JointClientContext.cpp
C++
apache-2.0
4,568
/* * Implementation of scanner for rational number calculator * CSE 374, 17wi, HP */ #include "token.h" #include "scan.h" #include <string> #include <cctype> #include <cstdlib> using namespace std; // Next unprocessed token on current input line. // Undefined if set_input has not been called. token next_tok; // Current input line. // line[pos..line.size()-1] is the unprocessed part of the line string line = ""; string::size_type pos = 0; // Advance next_tok to next token on current input line, if any. // If next_tok.kind == EOL, then return and leave next_tok unaltered. // pre: set_input has been called. void scan() { string::size_type nextpos; // declared here to get rid of a g++ warning if (next_tok.kind ==EOL) { return; } // Skip whitespace. while (pos < line.size() && isspace(line[pos])) { pos++; } // Skipped leading whitespace. Either past end of line, or // next character is not blank. Return if past end of line. if (pos >= line.size()) { next_tok.kind = EOL; return; } // next character is not blank. classify and return next token. switch(line[pos]) { // single-character tokens case '+': next_tok.kind = PLUS; pos++; return; case '-': next_tok.kind = MINUS; pos++; return; case '*': next_tok.kind = TIMES; pos++; return; case '%': next_tok.kind = DIV; pos++; return; case '/': next_tok.kind = SLASH; pos++; return; case '(': next_tok.kind = LPAREN; pos++; return; case ')': next_tok.kind = RPAREN; pos++; return; // integer tokens case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': // line[pos] is a digit. // Find last digit in the integer. nextpos = pos+1; while (nextpos < line.size() && isdigit(line[nextpos])) { nextpos++; } // line[pos..nextpos-1] holds the integer characters next_tok.kind = INT; next_tok.ival = atoi(line.substr(pos, nextpos-pos).c_str()); pos = nextpos; return; // unknown character in input default: next_tok.kind = UNKNOWN; pos++; return; } } // Set input line to new_line and advance next_tok to the first token // in that new line (which might be EOL if the line is empty). void set_input(string new_line) { line = new_line; pos = 0; next_tok.kind = UNKNOWN; scan(); }
zachcwillson/uw-cse
cse-374/project-7/scan.cpp
C++
apache-2.0
2,365
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.AspNetCore.SignalR.Internal { internal class HubContext<THub, T> : IHubContext<THub, T> where THub : Hub<T> where T : class { private readonly HubLifetimeManager<THub> _lifetimeManager; private readonly IHubClients<T> _clients; public HubContext(HubLifetimeManager<THub> lifetimeManager) { _lifetimeManager = lifetimeManager; _clients = new HubClients<THub, T>(_lifetimeManager); Groups = new GroupManager<THub>(lifetimeManager); } public IHubClients<T> Clients => _clients; public virtual IGroupManager Groups { get; } } }
aspnet/AspNetCore
src/SignalR/server/Core/src/Internal/HubContext`T.cs
C#
apache-2.0
802
<?php /** * bloodstone community V1.0.0 * @link https://www.facebook.com/Mazn.touati * @author Mazen Touati * @version 1.0.0 */ class Application { protected $controller = 'home', $method = 'index', $params = []; static $prefix = URL; /** * */ public function __construct() { //parse the URL to get the Controller, methods and params $url = $this->parseUrl(); if (isset($url)) { //if the controller exist if (file_exists('../application/controllers/'.$url[0].'.php')) { $this->controller = $url[0]; unset($url[0]); } else { //or show 404 error $this->controller = 'error'; } } //require the Controller require_once '../application/controllers/'.$this->controller.'.php'; //make an instance for controller $this->controller = new $this->controller; //if there's a method in the url if (isset($url[1])) { if (method_exists($this->controller, $url[1])) { //put the method in the holder $this->method = $url[1]; unset($url[1]); } } //if there's params $this->params = $url ? array_values($url) : []; //if the given method is wrong show 404 error if (!method_exists($this->controller, $this->method)) header('Location: ' . URL . 'error'); //call the controller method from the holders and pass the params call_user_func_array([$this->controller, $this->method], $this->params); } /** * @return array */ public function parseUrl() { if (isset($_GET['url'])) return explode('/',filter_var(rtrim($_GET['url'],'/'), FILTER_SANITIZE_URL)); } }
MazenDesigns/bscommunity
application/core/application.php
PHP
apache-2.0
1,928
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/compute/v1/compute.proto package com.google.cloud.compute.v1; /** * * * <pre> * </pre> * * Protobuf type {@code google.cloud.compute.v1.ManagedInstanceLastAttempt} */ public final class ManagedInstanceLastAttempt extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.compute.v1.ManagedInstanceLastAttempt) ManagedInstanceLastAttemptOrBuilder { private static final long serialVersionUID = 0L; // Use ManagedInstanceLastAttempt.newBuilder() to construct. private ManagedInstanceLastAttempt(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ManagedInstanceLastAttempt() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ManagedInstanceLastAttempt(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private ManagedInstanceLastAttempt( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case -1767146662: { com.google.cloud.compute.v1.Errors.Builder subBuilder = null; if (((bitField0_ & 0x00000001) != 0)) { subBuilder = errors_.toBuilder(); } errors_ = input.readMessage(com.google.cloud.compute.v1.Errors.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(errors_); errors_ = subBuilder.buildPartial(); } bitField0_ |= 0x00000001; break; } default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_ManagedInstanceLastAttempt_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_ManagedInstanceLastAttempt_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.compute.v1.ManagedInstanceLastAttempt.class, com.google.cloud.compute.v1.ManagedInstanceLastAttempt.Builder.class); } private int bitField0_; public static final int ERRORS_FIELD_NUMBER = 315977579; private com.google.cloud.compute.v1.Errors errors_; /** * * * <pre> * [Output Only] Encountered errors during the last attempt to create or delete the instance. * </pre> * * <code>optional .google.cloud.compute.v1.Errors errors = 315977579;</code> * * @return Whether the errors field is set. */ @java.lang.Override public boolean hasErrors() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * [Output Only] Encountered errors during the last attempt to create or delete the instance. * </pre> * * <code>optional .google.cloud.compute.v1.Errors errors = 315977579;</code> * * @return The errors. */ @java.lang.Override public com.google.cloud.compute.v1.Errors getErrors() { return errors_ == null ? com.google.cloud.compute.v1.Errors.getDefaultInstance() : errors_; } /** * * * <pre> * [Output Only] Encountered errors during the last attempt to create or delete the instance. * </pre> * * <code>optional .google.cloud.compute.v1.Errors errors = 315977579;</code> */ @java.lang.Override public com.google.cloud.compute.v1.ErrorsOrBuilder getErrorsOrBuilder() { return errors_ == null ? com.google.cloud.compute.v1.Errors.getDefaultInstance() : errors_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(315977579, getErrors()); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(315977579, getErrors()); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.compute.v1.ManagedInstanceLastAttempt)) { return super.equals(obj); } com.google.cloud.compute.v1.ManagedInstanceLastAttempt other = (com.google.cloud.compute.v1.ManagedInstanceLastAttempt) obj; if (hasErrors() != other.hasErrors()) return false; if (hasErrors()) { if (!getErrors().equals(other.getErrors())) return false; } if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasErrors()) { hash = (37 * hash) + ERRORS_FIELD_NUMBER; hash = (53 * hash) + getErrors().hashCode(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.compute.v1.ManagedInstanceLastAttempt parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.ManagedInstanceLastAttempt parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.compute.v1.ManagedInstanceLastAttempt parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.ManagedInstanceLastAttempt parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.compute.v1.ManagedInstanceLastAttempt parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.ManagedInstanceLastAttempt parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.compute.v1.ManagedInstanceLastAttempt parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.ManagedInstanceLastAttempt parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.compute.v1.ManagedInstanceLastAttempt parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.ManagedInstanceLastAttempt parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.compute.v1.ManagedInstanceLastAttempt parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.ManagedInstanceLastAttempt parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.compute.v1.ManagedInstanceLastAttempt prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * </pre> * * Protobuf type {@code google.cloud.compute.v1.ManagedInstanceLastAttempt} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.compute.v1.ManagedInstanceLastAttempt) com.google.cloud.compute.v1.ManagedInstanceLastAttemptOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_ManagedInstanceLastAttempt_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_ManagedInstanceLastAttempt_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.compute.v1.ManagedInstanceLastAttempt.class, com.google.cloud.compute.v1.ManagedInstanceLastAttempt.Builder.class); } // Construct using com.google.cloud.compute.v1.ManagedInstanceLastAttempt.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getErrorsFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); if (errorsBuilder_ == null) { errors_ = null; } else { errorsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_ManagedInstanceLastAttempt_descriptor; } @java.lang.Override public com.google.cloud.compute.v1.ManagedInstanceLastAttempt getDefaultInstanceForType() { return com.google.cloud.compute.v1.ManagedInstanceLastAttempt.getDefaultInstance(); } @java.lang.Override public com.google.cloud.compute.v1.ManagedInstanceLastAttempt build() { com.google.cloud.compute.v1.ManagedInstanceLastAttempt result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.compute.v1.ManagedInstanceLastAttempt buildPartial() { com.google.cloud.compute.v1.ManagedInstanceLastAttempt result = new com.google.cloud.compute.v1.ManagedInstanceLastAttempt(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { if (errorsBuilder_ == null) { result.errors_ = errors_; } else { result.errors_ = errorsBuilder_.build(); } to_bitField0_ |= 0x00000001; } result.bitField0_ = to_bitField0_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.compute.v1.ManagedInstanceLastAttempt) { return mergeFrom((com.google.cloud.compute.v1.ManagedInstanceLastAttempt) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.compute.v1.ManagedInstanceLastAttempt other) { if (other == com.google.cloud.compute.v1.ManagedInstanceLastAttempt.getDefaultInstance()) return this; if (other.hasErrors()) { mergeErrors(other.getErrors()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.cloud.compute.v1.ManagedInstanceLastAttempt parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.cloud.compute.v1.ManagedInstanceLastAttempt) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private com.google.cloud.compute.v1.Errors errors_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.compute.v1.Errors, com.google.cloud.compute.v1.Errors.Builder, com.google.cloud.compute.v1.ErrorsOrBuilder> errorsBuilder_; /** * * * <pre> * [Output Only] Encountered errors during the last attempt to create or delete the instance. * </pre> * * <code>optional .google.cloud.compute.v1.Errors errors = 315977579;</code> * * @return Whether the errors field is set. */ public boolean hasErrors() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * [Output Only] Encountered errors during the last attempt to create or delete the instance. * </pre> * * <code>optional .google.cloud.compute.v1.Errors errors = 315977579;</code> * * @return The errors. */ public com.google.cloud.compute.v1.Errors getErrors() { if (errorsBuilder_ == null) { return errors_ == null ? com.google.cloud.compute.v1.Errors.getDefaultInstance() : errors_; } else { return errorsBuilder_.getMessage(); } } /** * * * <pre> * [Output Only] Encountered errors during the last attempt to create or delete the instance. * </pre> * * <code>optional .google.cloud.compute.v1.Errors errors = 315977579;</code> */ public Builder setErrors(com.google.cloud.compute.v1.Errors value) { if (errorsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } errors_ = value; onChanged(); } else { errorsBuilder_.setMessage(value); } bitField0_ |= 0x00000001; return this; } /** * * * <pre> * [Output Only] Encountered errors during the last attempt to create or delete the instance. * </pre> * * <code>optional .google.cloud.compute.v1.Errors errors = 315977579;</code> */ public Builder setErrors(com.google.cloud.compute.v1.Errors.Builder builderForValue) { if (errorsBuilder_ == null) { errors_ = builderForValue.build(); onChanged(); } else { errorsBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; return this; } /** * * * <pre> * [Output Only] Encountered errors during the last attempt to create or delete the instance. * </pre> * * <code>optional .google.cloud.compute.v1.Errors errors = 315977579;</code> */ public Builder mergeErrors(com.google.cloud.compute.v1.Errors value) { if (errorsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && errors_ != null && errors_ != com.google.cloud.compute.v1.Errors.getDefaultInstance()) { errors_ = com.google.cloud.compute.v1.Errors.newBuilder(errors_) .mergeFrom(value) .buildPartial(); } else { errors_ = value; } onChanged(); } else { errorsBuilder_.mergeFrom(value); } bitField0_ |= 0x00000001; return this; } /** * * * <pre> * [Output Only] Encountered errors during the last attempt to create or delete the instance. * </pre> * * <code>optional .google.cloud.compute.v1.Errors errors = 315977579;</code> */ public Builder clearErrors() { if (errorsBuilder_ == null) { errors_ = null; onChanged(); } else { errorsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); return this; } /** * * * <pre> * [Output Only] Encountered errors during the last attempt to create or delete the instance. * </pre> * * <code>optional .google.cloud.compute.v1.Errors errors = 315977579;</code> */ public com.google.cloud.compute.v1.Errors.Builder getErrorsBuilder() { bitField0_ |= 0x00000001; onChanged(); return getErrorsFieldBuilder().getBuilder(); } /** * * * <pre> * [Output Only] Encountered errors during the last attempt to create or delete the instance. * </pre> * * <code>optional .google.cloud.compute.v1.Errors errors = 315977579;</code> */ public com.google.cloud.compute.v1.ErrorsOrBuilder getErrorsOrBuilder() { if (errorsBuilder_ != null) { return errorsBuilder_.getMessageOrBuilder(); } else { return errors_ == null ? com.google.cloud.compute.v1.Errors.getDefaultInstance() : errors_; } } /** * * * <pre> * [Output Only] Encountered errors during the last attempt to create or delete the instance. * </pre> * * <code>optional .google.cloud.compute.v1.Errors errors = 315977579;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.compute.v1.Errors, com.google.cloud.compute.v1.Errors.Builder, com.google.cloud.compute.v1.ErrorsOrBuilder> getErrorsFieldBuilder() { if (errorsBuilder_ == null) { errorsBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.compute.v1.Errors, com.google.cloud.compute.v1.Errors.Builder, com.google.cloud.compute.v1.ErrorsOrBuilder>( getErrors(), getParentForChildren(), isClean()); errors_ = null; } return errorsBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.compute.v1.ManagedInstanceLastAttempt) } // @@protoc_insertion_point(class_scope:google.cloud.compute.v1.ManagedInstanceLastAttempt) private static final com.google.cloud.compute.v1.ManagedInstanceLastAttempt DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.compute.v1.ManagedInstanceLastAttempt(); } public static com.google.cloud.compute.v1.ManagedInstanceLastAttempt getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ManagedInstanceLastAttempt> PARSER = new com.google.protobuf.AbstractParser<ManagedInstanceLastAttempt>() { @java.lang.Override public ManagedInstanceLastAttempt parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new ManagedInstanceLastAttempt(input, extensionRegistry); } }; public static com.google.protobuf.Parser<ManagedInstanceLastAttempt> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ManagedInstanceLastAttempt> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.compute.v1.ManagedInstanceLastAttempt getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/java-compute
proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/ManagedInstanceLastAttempt.java
Java
apache-2.0
25,027
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/compute/v1/compute.proto package com.google.cloud.compute.v1; public interface VpnGatewayStatusTunnelOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.compute.v1.VpnGatewayStatusTunnel) com.google.protobuf.MessageOrBuilder { /** * * * <pre> * The VPN gateway interface this VPN tunnel is associated with. * </pre> * * <code>optional uint32 local_gateway_interface = 158764330;</code> * * @return Whether the localGatewayInterface field is set. */ boolean hasLocalGatewayInterface(); /** * * * <pre> * The VPN gateway interface this VPN tunnel is associated with. * </pre> * * <code>optional uint32 local_gateway_interface = 158764330;</code> * * @return The localGatewayInterface. */ int getLocalGatewayInterface(); /** * * * <pre> * The peer gateway interface this VPN tunnel is connected to, the peer gateway could either be an external VPN gateway or GCP VPN gateway. * </pre> * * <code>optional uint32 peer_gateway_interface = 214380385;</code> * * @return Whether the peerGatewayInterface field is set. */ boolean hasPeerGatewayInterface(); /** * * * <pre> * The peer gateway interface this VPN tunnel is connected to, the peer gateway could either be an external VPN gateway or GCP VPN gateway. * </pre> * * <code>optional uint32 peer_gateway_interface = 214380385;</code> * * @return The peerGatewayInterface. */ int getPeerGatewayInterface(); /** * * * <pre> * URL reference to the VPN tunnel. * </pre> * * <code>optional string tunnel_url = 78975256;</code> * * @return Whether the tunnelUrl field is set. */ boolean hasTunnelUrl(); /** * * * <pre> * URL reference to the VPN tunnel. * </pre> * * <code>optional string tunnel_url = 78975256;</code> * * @return The tunnelUrl. */ java.lang.String getTunnelUrl(); /** * * * <pre> * URL reference to the VPN tunnel. * </pre> * * <code>optional string tunnel_url = 78975256;</code> * * @return The bytes for tunnelUrl. */ com.google.protobuf.ByteString getTunnelUrlBytes(); }
googleapis/java-compute
proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/VpnGatewayStatusTunnelOrBuilder.java
Java
apache-2.0
2,892
using System; using System.Threading.Tasks; using InsurgenceServerCore.ClientHandler; namespace InsurgenceServerCore.Battles { public class Battle { public Guid Id; public string Username1; public string Username2; public Client Client1; public Client Client2; public string Trainer1; public string Trainer2; public bool Activated { get; private set; } public DateTime StartTime; public DateTime LastMessageTime; public int Seed; public Battle(Client client, string username, string trainer) { Id = Guid.NewGuid(); Username1 = client.Username.ToLowerInvariant(); Username2 = username.ToLowerInvariant(); Client1 = client; Trainer1 = trainer; StartTime = DateTime.UtcNow; LastMessageTime = DateTime.UtcNow; BattleHandler.ActiveBattles.TryAdd(Id, this); Seed = new Random().Next(int.MinValue, int.MaxValue); } public async Task JoinBattle(Client client, string trainer) { Activated = true; Client2 = client; Trainer2 = trainer; LastMessageTime = DateTime.UtcNow; await SendMessage(1, $"<BAT user={Username2} result=4 trainer={Trainer2}>"); await SendMessage(2, $"<BAT user={Username1} result=4 trainer={Trainer1}>"); } public async Task SendMessage(int clientId, string message) { if (clientId == 1) { if (!Client1.IsConnected) { await Client2.SendMessage("<TRA dead>"); return; } await Client1.SendMessage(message); } else { if (!Client2.IsConnected) { await Client1.SendMessage("<TRA dead>"); return; } await Client2.SendMessage(message); } } public async Task GetRandomSeed(Client client, string turnString) { LastMessageTime = DateTime.UtcNow; int turn; if (!int.TryParse(turnString, out turn)) return; var s = (Seed << turn | Seed >> 31); if (client.UserId == Client1.UserId) await SendMessage(1, $"<BAT seed={s}>"); else await SendMessage(2, $"<BAT seed={s}>"); } public async Task SendChoice(string username, string choice, string m, string rseed) { LastMessageTime = DateTime.UtcNow; if (username == Username1) { await SendMessage(2, $"<BAT choices={choice} m={m} rseed={rseed}>"); } else { await SendMessage(1, $"<BAT choices={choice} m={m} rseed={rseed}>"); } } public async Task NewPokemon(string username, string New) { LastMessageTime = DateTime.UtcNow; if (username == Username1) { await SendMessage(2, $"<BAT new={New}>"); } else { await SendMessage(1, $"<BAT new={New}>"); } } public async Task Damage(string username, string damage, string state) { LastMessageTime = DateTime.UtcNow; if (username == Username1) { await SendMessage(2, $"<BAT damage={damage} state={state}>"); } else { await SendMessage(1, $"<BAT damage={damage} state={state}>"); } } public async Task Kill(string reason) { Logger.Logger.Log($"Killing battle between {Username1} and {Username2} because of {reason}"); if (Client1 != null && Client1.Connected) await Client1.SendMessage("<TRA dead>"); if (Client2 != null && Client2.Connected) await Client2.SendMessage("<TRA dead>"); if (Client1 != null) Client1.ActiveBattle = null; if (Client2 != null) Client2.ActiveBattle = null; BattleHandler.DeleteBattle(this); } } }
Deukhoofd/InsurgenceServer
InsurgenceServerCore/Battles/Battle.cs
C#
apache-2.0
4,347
package com.github.randomcodeorg.ppplugin.data.gradle; import java.io.File; import org.gradle.api.tasks.SourceSetContainer; public class JavaSourceSetProvider implements SourceSetProvider { private final SourceSetContainer container; public JavaSourceSetProvider(SourceSetContainer container) { this.container = container; } @Override public SourceSet getByName(String name) { org.gradle.api.tasks.SourceSet set = container.getByName(name); return new SourceSet() { @Override public Iterable<File> getCompileClasspath() { return set.getCompileClasspath(); } }; } @Override public Iterable<String> getNames() { return container.getNames(); } @Override public int size() { return container.size(); } }
RandomCodeOrg/PPPluginGradle
plugin/src/main/java/com/github/randomcodeorg/ppplugin/data/gradle/JavaSourceSetProvider.java
Java
apache-2.0
751
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("GDGSPCheckIn")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Alefe Souza")] [assembly: AssemblyProduct("GDGSPCheckIn")] [assembly: AssemblyCopyright("Copyright © 2016 Alefe Souza")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
alefesouza/gdg-sp
Desktop/GDGSPCheckIn/Properties/AssemblyInfo.cs
C#
apache-2.0
2,406
using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class demonStateSwallow : StateMachineBehaviour { private Image blackscreen; private UnityStandardAssets.Characters.FirstPerson.MouseLook ml; private Transform pcamera; private Transform player; // OnStateEnter is called when a transition starts and the state machine starts to evaluate this state override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { player = GameObject.FindGameObjectWithTag("Player").transform; GameObject stomach = GameObject.FindGameObjectWithTag("Finish"); pcamera = player.GetComponentInChildren<Camera>().transform; player.position = stomach.transform.position; blackscreen = GameObject.FindGameObjectWithTag("blackscreen").GetComponent<Image>(); ml = new UnityStandardAssets.Characters.FirstPerson.MouseLook(); ml.Init(player, pcamera); } // OnStateUpdate is called on each Update frame between OnStateEnter and OnStateExit callbacks override public void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { blackscreen.color = Color.Lerp(blackscreen.color, Color.black, Time.deltaTime); if(blackscreen.color.a >= .98f) { SceneManager.LoadScene("youlose"); } ml.LookRotation(player, pcamera); } // OnStateExit is called when a transition ends and the state machine finishes evaluating this state //override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { // //} // OnStateMove is called right after Animator.OnAnimatorMove(). Code that processes and affects root motion should be implemented here //override public void OnStateMove(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { // //} // OnStateIK is called right after Animator.OnAnimatorIK(). Code that sets up animation IK (inverse kinematics) should be implemented here. //override public void OnStateIK(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { // //} }
carlsc2/EGDHorrorGame
HeartbeatHorror/Assets/Scripts/Demon/demonStateSwallow.cs
C#
apache-2.0
2,038
package Manager; import Tweet.Tweet; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; import java.util.Arrays; import java.util.Properties; public class ServiceManager { public static void main(String[] args) throws Exception { Integer ngram = 5; if (args.length > 0) ngram = Integer.parseInt(args[0]); System.out.println("##RE##N_GRAM: " + ngram); Properties props = new Properties(); props.put("bootstrap.servers", "kafka:9092"); props.put("group.id", "group-1"); props.put("enable.auto.commit", "true"); props.put("auto.commit.interval.ms", "1000"); props.put("auto.offset.reset", "earliest"); props.put("session.timeout.ms", "30000"); props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<>(props); kafkaConsumer.subscribe(Arrays.asList("tweet")); while (true) { ConsumerRecords<String, String> records = kafkaConsumer.poll(100); for (ConsumerRecord<String, String> record : records) { ObjectMapper jsonParser=new ObjectMapper(); jsonParser.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); jsonParser.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT); jsonParser.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY); Tweet tweet = jsonParser.readValue(record.value(), Tweet.class); System.out.println("---------------------------------------------------------------------------------"); System.out.println("##RE##TWEETS: " + tweet.getText()); System.out.println("---------------------------------------------------------------------------------"); Runnable proceso1 = new Manager(tweet, 5); proceso1.run(); } } } }
eltitopera/TFM
manager/src/src/main/java/Manager/ServiceManager.java
Java
apache-2.0
2,338
package pl.npe.lpp.preprocessor.line; import java.util.Collections; import java.util.List; /** * Created by IntelliJ IDEA. * User: tomek * Date: 08.06.14 * Time: 15:01 */ public class DirectiveUsage { private String directive; private List<String> params; public DirectiveUsage(String directive, List<String> params) { this.directive = directive; this.params = params; } public String getDirective() { return directive; } public List<String> getParams() { return Collections.unmodifiableList(params); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DirectiveUsage usage = (DirectiveUsage) o; if (directive != null ? !directive.equals(usage.directive) : usage.directive != null) return false; if (params != null ? !params.equals(usage.params) : usage.params != null) return false; return true; } @Override public int hashCode() { int result = directive != null ? directive.hashCode() : 0; result = 31 * result + (params != null ? params.hashCode() : 0); return result; } @Override public String toString() { final StringBuilder sb = new StringBuilder("DirectiveUsage{"); sb.append("directive='").append(directive).append('\''); sb.append(", params=").append(params); sb.append('}'); return sb.toString(); } }
traczykowski/lpp
src/main/java/pl/npe/lpp/preprocessor/line/DirectiveUsage.java
Java
apache-2.0
1,523
/* Copyright 2007-2015 QReal Research Group * * 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. */ #include "drawRectBlock.h" #include "trikKit/robotModel/parts/trikDisplay.h" using namespace trik::blocks::details; DrawRectBlock::DrawRectBlock(kitBase::robotModel::RobotModelInterface &robotModel) : kitBase::blocksBase::common::DisplayBlock(robotModel) { } void DrawRectBlock::doJob(kitBase::robotModel::robotParts::Display &display) { auto trikDisplay = static_cast<robotModel::parts::TrikDisplay *>(&display); const int x = eval<int>("XCoordinateRect"); const int y = eval<int>("YCoordinateRect"); const int width = eval<int>("WidthRect"); const int height = eval<int>("HeightRect"); if (!errorsOccured()) { trikDisplay->drawRect(x, y, width, height); emit done(mNextBlockId); } }
dvvrd/qreal
plugins/robots/common/trikKit/src/blocks/details/drawRectBlock.cpp
C++
apache-2.0
1,307
using UnityEngine; using System.Collections; public class BasicSword : Weapon { public BasicSword () { damageMultiplier = 1.0; speed = 1.0; } }
jakebacker/UnityGame
Assets/Project/Scripts/BasicSword.cs
C#
apache-2.0
154
package oob import ( "context" "github.com/google/wire" "github.com/skygeario/skygear-server/pkg/auth/dependency/urlprefix" "github.com/skygeario/skygear-server/pkg/core/async" "github.com/skygeario/skygear-server/pkg/core/config" "github.com/skygeario/skygear-server/pkg/core/db" "github.com/skygeario/skygear-server/pkg/core/template" "github.com/skygeario/skygear-server/pkg/core/time" ) func ProvideProvider( ctx context.Context, c *config.TenantConfiguration, sqlb db.SQLBuilder, sqle db.SQLExecutor, t time.Provider, te *template.Engine, upp urlprefix.Provider, tq async.Queue, ) *Provider { return &Provider{ Context: ctx, LocalizationConfiguration: c.AppConfig.Localization, MetadataConfiguration: c.AppConfig.AuthUI.Metadata, Config: c.AppConfig.Authenticator.OOB, SMSMessageConfiguration: c.AppConfig.Messages.SMS, EmailMessageConfiguration: c.AppConfig.Messages.Email, Store: &Store{SQLBuilder: sqlb, SQLExecutor: sqle}, Time: t, TemplateEngine: te, URLPrefixProvider: upp, TaskQueue: tq, } } var DependencySet = wire.NewSet(ProvideProvider)
SkygearIO/skygear-server
pkg/auth/dependency/authenticator/oob/deps.go
GO
apache-2.0
1,217
package com.softwarelma.epe.p3.print; import java.util.ArrayList; import java.util.List; import com.softwarelma.epe.p1.app.EpeAppException; import com.softwarelma.epe.p1.app.EpeAppUtils; import com.softwarelma.epe.p2.exec.EpeExecContent; import com.softwarelma.epe.p2.exec.EpeExecContentInternal; import com.softwarelma.epe.p2.exec.EpeExecParams; import com.softwarelma.epe.p2.exec.EpeExecResult; public final class EpePrintFinalPrint_separator_smart extends EpePrintAbstract { public static final String PROP_COL_SUFFIX = "col_suffix"; @Override public EpeExecResult doFunc(EpeExecParams execParams, List<EpeExecResult> listExecResult) throws EpeAppException { @SuppressWarnings("unused") String postMessage = "print_separator_smart, expected a list with the param, external and internal separators " + "and the contents to print."; String sepParam = "\n";// "\n\n"; String sepExternal = "\n"; String colSuffix = retrievePropValueOrNull("print_separator_smart", listExecResult, PROP_COL_SUFFIX); String str = retrievePrintableStrWithSeparatorsSmart(sepParam, sepExternal, listExecResult, colSuffix); log(execParams, str); return createResult(str); } public static String retrievePrintableStrWithSeparatorsSmart(String sepParam, String sepExternal, List<EpeExecResult> listExecResult, String colSuffix) throws EpeAppException { EpeAppUtils.checkNull("listExecResult", listExecResult); StringBuilder sb = new StringBuilder(); String sepParam2 = ""; for (int i = 0; i < listExecResult.size(); i++) { EpeExecResult result = listExecResult.get(i); EpeAppUtils.checkNull("result", result); EpeExecContent content = result.getExecContent(); EpeAppUtils.checkNull("content", content); if (content.isProp()) { continue; } sb.append(sepParam2); sepParam2 = sepParam; List<Integer> listWidth = retrieveWidths(content); sb.append(content.toString(sepExternal, listWidth, colSuffix)); } return sb.toString(); } private static List<Integer> retrieveWidths(EpeExecContent content) throws EpeAppException { List<Integer> listWidth = new ArrayList<>(); if (content.getContentInternal() == null) { listWidth.add(4); return listWidth; } EpeExecContentInternal contentInternal = content.getContentInternal(); if (contentInternal.isString()) { listWidth.add(contentInternal.getStr().length()); return listWidth; } else if (contentInternal.isListString()) { for (String str : contentInternal.getListStr()) { listWidth.add((str + "").length()); } return listWidth; } else if (contentInternal.isListListString()) { for (List<String> listStr : contentInternal.getListListStr()) { retrieveWidths(listStr, listWidth); } return listWidth; } else { throw new EpeAppException("Unknown internal content type"); } } private static void retrieveWidths(List<String> listStr, List<Integer> listWidth) { if (listStr == null) { return; } int width; for (int i = 0; i < listStr.size(); i++) { String str = listStr.get(i); width = (str + "").length(); if (listWidth.size() < i + 1) { listWidth.add(width); } else { if (width > listWidth.get(i)) { listWidth.set(i, width); } } } } }
softwarelma/utils
src/main/java/com/softwarelma/epe/p3/print/EpePrintFinalPrint_separator_smart.java
Java
apache-2.0
3,797
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.api.ads.adwords.jaxws.v201809.cm; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * * Operations for adding/updating bidding strategies. * * * <p>Java class for BiddingStrategyOperation complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="BiddingStrategyOperation"> * &lt;complexContent> * &lt;extension base="{https://adwords.google.com/api/adwords/cm/v201809}Operation"> * &lt;sequence> * &lt;element name="operand" type="{https://adwords.google.com/api/adwords/cm/v201809}SharedBiddingStrategy" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "BiddingStrategyOperation", propOrder = { "operand" }) public class BiddingStrategyOperation extends Operation { protected SharedBiddingStrategy operand; /** * Gets the value of the operand property. * * @return * possible object is * {@link SharedBiddingStrategy } * */ public SharedBiddingStrategy getOperand() { return operand; } /** * Sets the value of the operand property. * * @param value * allowed object is * {@link SharedBiddingStrategy } * */ public void setOperand(SharedBiddingStrategy value) { this.operand = value; } }
googleads/googleads-java-lib
modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201809/cm/BiddingStrategyOperation.java
Java
apache-2.0
2,228
package ikube.action; import ikube.AbstractTest; import ikube.IConstants; import ikube.action.index.IndexManager; import ikube.model.IndexContext; import ikube.toolkit.FILE; import ikube.toolkit.THREAD; import org.apache.lucene.index.IndexWriter; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.File; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertTrue; /** * @author Michael Couck * @version 01.00 * @since 21-11-2010 */ @SuppressWarnings("deprecation") public class ReopenTest extends AbstractTest { private Reopen reopen; private IndexContext indexContext; @Before public void before() { reopen = new Reopen(); indexContext = new IndexContext(); indexContext.setDelta(Boolean.TRUE); indexContext.setName(IConstants.INDEX_CONTEXT); indexContext.setIndexDirectoryPath(indexDirectoryPath); indexContext.setIndexDirectoryPathBackup(indexDirectoryPath); indexContext.setBatchSize(1000); indexContext.setBufferedDocs(1000); indexContext.setBufferSize(128); indexContext.setCompoundFile(Boolean.TRUE); indexContext.setMergeFactor(1000); FILE.deleteFile(new File(indexDirectoryPath)); } @After public void after() throws Exception { FILE.deleteFile(new File(indexContext.getIndexDirectoryPath())); } @Test public void internalExecute() throws Exception { createIndexFileSystem(indexContext, "Hello world"); // First open the index new Open().execute(indexContext); IndexWriter[] indexWriters = IndexManager.openIndexWriterDelta(indexContext); indexContext.setIndexWriters(indexWriters); // Add some documents to the index and reopen addDocuments(indexWriters[0], IConstants.CONTENTS, "Michael Couck"); boolean opened = reopen.execute(indexContext); assertTrue("The index should be open : ", opened); int docs = indexContext.getMultiSearcher().getIndexReader().numDocs(); internalExecute(indexContext, docs); docs = indexContext.getMultiSearcher().getIndexReader().numDocs(); internalExecute(indexContext, docs); docs = indexContext.getMultiSearcher().getIndexReader().numDocs(); internalExecute(indexContext, docs); docs = indexContext.getMultiSearcher().getIndexReader().numDocs(); internalExecute(indexContext, docs); docs = indexContext.getMultiSearcher().getIndexReader().numDocs(); internalExecute(indexContext, docs); docs = indexContext.getMultiSearcher().getIndexReader().numDocs(); internalExecute(indexContext, docs); } private void internalExecute(final IndexContext indexContext, final int numDocsBefore) throws Exception { // Add some more documents to the index and reopen IndexWriter indexWriter = indexContext.getIndexWriters()[0]; addDocuments(indexWriter, IConstants.CONTENTS, "Michael Couck again"); commitIndexWriter(indexWriter); boolean opened = reopen.execute(indexContext); assertTrue("The index should be open : ", opened); int moreDocs = indexContext.getMultiSearcher().getIndexReader().numDocs(); assertNotSame("There should be more documents in the new multi searcher : ", numDocsBefore, moreDocs); } @Test public void memoryValidation() throws Exception { IndexWriter[] indexWriters = IndexManager.openIndexWriterDelta(indexContext); indexContext.setIndexWriters(indexWriters); // Now add documents and reopen again and again System.gc(); int iterations = 1000; long before = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / IConstants.MILLION; for (int i = iterations; i >= 0; i--) { if (i > 0 && i % 100 == 0) { indexWriters[0].commit(); indexWriters[0].forceMerge(10, Boolean.TRUE); new Reopen().execute(indexContext); printMemoryDelta(before); } addDocuments(indexWriters[0], IConstants.CONTENTS, "Michael Couck again"); THREAD.sleep(1); } printMemoryDelta(before); long after = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / IConstants.MILLION; long increase = (after - before); assertTrue(increase < 100); } }
michaelcouck/ikube
code/core/src/test/java/ikube/action/ReopenTest.java
Java
apache-2.0
4,627
/* * Copyright 2000-2017 JetBrains s.r.o. * * 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.intellij.application.options.schemes; import com.intellij.icons.AllIcons; import com.intellij.ide.HelpTooltip; import com.intellij.ide.actions.NonTrivialActionGroup; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationBundle; import com.intellij.openapi.options.Scheme; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.ui.MessageType; import com.intellij.openapi.ui.popup.Balloon; import com.intellij.openapi.ui.popup.BalloonBuilder; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.ui.popup.ListPopup; import com.intellij.openapi.util.Disposer; import com.intellij.ui.JBColor; import com.intellij.ui.awt.RelativePoint; import com.intellij.util.ui.JBDimension; import com.intellij.util.ui.JBUI; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.util.Collection; import java.util.function.BiConsumer; import java.util.function.Consumer; /** * Base panel for schemes combo box and related actions. When settings change, {@link #updateOnCurrentSettingsChange()} method must be * called to reflect the change in schemes panel. The method should be added to settings model listener. * * @param <T> The actual scheme type. * @see AbstractSchemeActions * @see SchemesModel */ public abstract class AbstractSchemesPanel<T extends Scheme, InfoComponent extends JComponent> extends JPanel { private EditableSchemesCombo<T> mySchemesCombo; private AbstractSchemeActions<T> myActions; private JComponent myToolbar; protected InfoComponent myInfoComponent; // region Colors (probably should be standard for platform UI) protected static final Color HINT_FOREGROUND = JBColor.GRAY; @SuppressWarnings("UseJBColor") protected static final Color ERROR_MESSAGE_FOREGROUND = Color.RED; protected static final int DEFAULT_VGAP = 8; // endregion public AbstractSchemesPanel() { this(DEFAULT_VGAP, null); } public AbstractSchemesPanel(int vGap) { this(vGap, null); } public AbstractSchemesPanel(int vGap, @Nullable JComponent rightCustomComponent) { setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); createUIComponents(vGap, rightCustomComponent); } private void createUIComponents(int vGap, @Nullable JComponent rightCustomComponent) { final JPanel verticalContainer = rightCustomComponent != null ? createVerticalContainer() : this; JPanel controlsPanel = createControlsPanel(); verticalContainer.add(controlsPanel); verticalContainer.add(Box.createRigidArea(new JBDimension(0, 12))); if (rightCustomComponent != null) { JPanel horizontalContainer = new JPanel(); horizontalContainer.setLayout(new BoxLayout(horizontalContainer, BoxLayout.X_AXIS)); horizontalContainer.add(verticalContainer); horizontalContainer.add(Box.createHorizontalGlue()); horizontalContainer.add(rightCustomComponent); add(horizontalContainer); } add(new JSeparator()); if (vGap > 0) { add(Box.createVerticalGlue()); add(Box.createRigidArea(new JBDimension(0, vGap))); } } private static JPanel createVerticalContainer() { JPanel container = new JPanel(); container.setLayout(new BoxLayout(container, BoxLayout.Y_AXIS)); return container; } private JPanel createControlsPanel() { JPanel controlsPanel = new JPanel(); controlsPanel.setLayout(new BoxLayout(controlsPanel, BoxLayout.LINE_AXIS)); String label = getComboBoxLabel(); if (label != null) { controlsPanel.add(new JLabel(label)); controlsPanel.add(Box.createRigidArea(new JBDimension(10, 0))); } myActions = createSchemeActions(); mySchemesCombo = new EditableSchemesCombo<>(this); controlsPanel.add(mySchemesCombo.getComponent()); myToolbar = createToolbar(); controlsPanel.add(Box.createRigidArea(new JBDimension(4, 0))); controlsPanel.add(myToolbar); controlsPanel.add(Box.createRigidArea(new JBDimension(9, 0))); myInfoComponent = createInfoComponent(); controlsPanel.add(myInfoComponent); controlsPanel.add(Box.createHorizontalGlue()); mySchemesCombo.getComponent().setMaximumSize(mySchemesCombo.getComponent().getPreferredSize()); int height = mySchemesCombo.getComponent().getPreferredSize().height; controlsPanel.setMaximumSize(new Dimension(controlsPanel.getMaximumSize().width, height)); return controlsPanel; } private JComponent createToolbar() { DefaultActionGroup group = new DefaultActionGroup(); group.add(new ShowSchemesActionsListAction(myActions.getActions())); ActionToolbar toolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.NAVIGATION_BAR_TOOLBAR, group, true); toolbar.setReservePlaceAutoPopupIcon(false); toolbar.setLayoutPolicy(ActionToolbar.NOWRAP_LAYOUT_POLICY); JComponent toolbarComponent = toolbar.getComponent(); toolbarComponent.setBorder(JBUI.Borders.empty(3)); return toolbarComponent; } public final JComponent getToolbar() { return myToolbar; } /** * Creates schemes actions. Used when panel UI components are created. * @return Scheme actions associated with the panel. * @see AbstractSchemeActions */ protected abstract AbstractSchemeActions<T> createSchemeActions(); public final T getSelectedScheme() { return mySchemesCombo.getSelectedScheme(); } public void selectScheme(@Nullable T scheme) { mySchemesCombo.selectScheme(scheme); } public final void resetSchemes(@NotNull Collection<T> schemes) { mySchemesCombo.resetSchemes(schemes); } public void disposeUIResources() { removeAll(); } public final void editCurrentSchemeName(@NotNull BiConsumer<T,String> newSchemeNameConsumer) { T currentScheme = getSelectedScheme(); if (currentScheme != null) { String currentName = currentScheme.getName(); mySchemesCombo.startEdit( currentName, getModel().isProjectScheme(currentScheme), newName -> { if (!newName.equals(currentName)) { newSchemeNameConsumer.accept(currentScheme, newName); } }); } } public final void editNewSchemeName(@NotNull String preferredName, boolean isProjectScheme, @NotNull Consumer<String> nameConsumer) { String name = SchemeNameGenerator.getUniqueName(preferredName, schemeName -> getModel().containsScheme(schemeName, isProjectScheme)); mySchemesCombo.startEdit(name, isProjectScheme, nameConsumer); } public final void cancelEdit() { mySchemesCombo.cancelEdit(); } public final void showInfo(@Nullable String message, @NotNull MessageType messageType) { myToolbar.setVisible(false); showMessage(message, messageType); } protected abstract void showMessage(@Nullable String message, @NotNull MessageType messageType); public final void clearInfo() { myToolbar.setVisible(true); clearMessage(); } protected abstract void clearMessage(); public final AbstractSchemeActions<T> getActions() { return myActions; } @NotNull protected abstract InfoComponent createInfoComponent(); /** * @return a string label to place before the combobox or {@code null} if it is not needed */ @Nullable protected String getComboBoxLabel() { return getSchemeTypeName() + ":"; } protected String getSchemeTypeName() { return ApplicationBundle.message("editbox.scheme.type.name"); } /** * @return Schemes model implementation. * @see SchemesModel */ @NotNull public abstract SchemesModel<T> getModel(); /** * Must be called when any settings are changed. */ public final void updateOnCurrentSettingsChange() { mySchemesCombo.updateSelected(); } /** * Returns an indent to calculate a left margin for the scheme name in the combo box. * By default, all names are aligned to the left. * * @param scheme the scheme to calculate its indent * @return an indent that shows a nesting level for the specified scheme */ protected int getIndent(@NotNull T scheme) { return 0; } /** * @return True if the panel supports project-level schemes along with IDE ones. In this case there will be * additional "Copy to Project" and "Copy to IDE" actions for IDE and project schemes respectively and Project/IDE schemes * separators. */ protected abstract boolean supportsProjectSchemes(); protected abstract boolean highlightNonDefaultSchemes(); protected boolean hideDeleteActionIfUnavailable() { return true; } public abstract boolean useBoldForNonRemovableSchemes(); public void showStatus(final String message, MessageType messageType) { BalloonBuilder balloonBuilder = JBPopupFactory.getInstance() .createHtmlTextBalloonBuilder(message, messageType.getDefaultIcon(), messageType.getPopupBackground(), null); balloonBuilder.setFadeoutTime(5000); final Balloon balloon = balloonBuilder.createBalloon(); Point pointOnComponent = new Point(myToolbar.getWidth() / 4, myToolbar.getHeight() / 4); balloon.show(new RelativePoint(myToolbar, pointOnComponent), Balloon.Position.above); Disposer.register(ProjectManager.getInstance().getDefaultProject(), balloon); } private static class ShowSchemesActionsListAction extends NonTrivialActionGroup { ShowSchemesActionsListAction(Collection<AnAction> actions) { setPopup(true); getTemplatePresentation().setIcon(AllIcons.General.GearPlain); getTemplatePresentation().setText("Show Scheme Actions"); getTemplatePresentation().setDescription("Show Scheme Actions"); addAll(actions); } @Override public boolean isDumbAware() { return true; } @Override public boolean canBePerformed(DataContext context) { return true; } @Override public void actionPerformed(AnActionEvent e) { ListPopup popup = JBPopupFactory.getInstance(). createActionGroupPopup(null, this, e.getDataContext(), true, null, Integer.MAX_VALUE); HelpTooltip.setMasterPopup(e.getInputEvent().getComponent(), popup); Component component = e.getInputEvent().getComponent(); if (component instanceof ActionButtonComponent) { popup.showUnderneathOf(component); } else { popup.showInCenterOf(component); } } } protected static void showMessage(@Nullable String message, @NotNull MessageType messageType, @NotNull JLabel infoComponent) { infoComponent.setText(message); Color foreground = messageType == MessageType.INFO ? HINT_FOREGROUND : messageType == MessageType.ERROR ? ERROR_MESSAGE_FOREGROUND : messageType.getTitleForeground(); infoComponent.setForeground(foreground); } }
sabi0/intellij-community
platform/platform-impl/src/com/intellij/application/options/schemes/AbstractSchemesPanel.java
Java
apache-2.0
11,570
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # 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. """Dataset utilities.""" import functools import pathlib from typing import Dict, Tuple from absl import logging from graph_nets import graphs as tf_graphs from graph_nets import utils_tf import numpy as np import scipy.sparse as sp import tensorflow as tf import tqdm # pylint: disable=g-bad-import-order import sub_sampler Path = pathlib.Path NUM_PAPERS = 121751666 NUM_AUTHORS = 122383112 NUM_INSTITUTIONS = 25721 EMBEDDING_SIZE = 768 NUM_CLASSES = 153 NUM_NODES = NUM_PAPERS + NUM_AUTHORS + NUM_INSTITUTIONS NUM_EDGES = 1_728_364_232 assert NUM_NODES == 244_160_499 NUM_K_FOLD_SPLITS = 10 OFFSETS = { "paper": 0, "author": NUM_PAPERS, "institution": NUM_PAPERS + NUM_AUTHORS, } SIZES = { "paper": NUM_PAPERS, "author": NUM_AUTHORS, "institution": NUM_INSTITUTIONS } RAW_DIR = Path("raw") PREPROCESSED_DIR = Path("preprocessed") RAW_NODE_FEATURES_FILENAME = RAW_DIR / "node_feat.npy" RAW_NODE_LABELS_FILENAME = RAW_DIR / "node_label.npy" RAW_NODE_YEAR_FILENAME = RAW_DIR / "node_year.npy" TRAIN_INDEX_FILENAME = RAW_DIR / "train_idx.npy" VALID_INDEX_FILENAME = RAW_DIR / "train_idx.npy" TEST_INDEX_FILENAME = RAW_DIR / "train_idx.npy" EDGES_PAPER_PAPER_B = PREPROCESSED_DIR / "paper_paper_b.npz" EDGES_PAPER_PAPER_B_T = PREPROCESSED_DIR / "paper_paper_b_t.npz" EDGES_AUTHOR_INSTITUTION = PREPROCESSED_DIR / "author_institution.npz" EDGES_INSTITUTION_AUTHOR = PREPROCESSED_DIR / "institution_author.npz" EDGES_AUTHOR_PAPER = PREPROCESSED_DIR / "author_paper.npz" EDGES_PAPER_AUTHOR = PREPROCESSED_DIR / "paper_author.npz" PCA_PAPER_FEATURES_FILENAME = PREPROCESSED_DIR / "paper_feat_pca_129.npy" PCA_AUTHOR_FEATURES_FILENAME = ( PREPROCESSED_DIR / "author_feat_from_paper_feat_pca_129.npy") PCA_INSTITUTION_FEATURES_FILENAME = ( PREPROCESSED_DIR / "institution_feat_from_paper_feat_pca_129.npy") PCA_MERGED_FEATURES_FILENAME = ( PREPROCESSED_DIR / "merged_feat_from_paper_feat_pca_129.npy") NEIGHBOR_INDICES_FILENAME = PREPROCESSED_DIR / "neighbor_indices.npy" NEIGHBOR_DISTANCES_FILENAME = PREPROCESSED_DIR / "neighbor_distances.npy" FUSED_NODE_LABELS_FILENAME = PREPROCESSED_DIR / "fused_node_labels.npy" FUSED_PAPER_EDGES_FILENAME = PREPROCESSED_DIR / "fused_paper_edges.npz" FUSED_PAPER_EDGES_T_FILENAME = PREPROCESSED_DIR / "fused_paper_edges_t.npz" K_FOLD_SPLITS_DIR = Path("k_fold_splits") def get_raw_directory(data_root): return Path(data_root) / "raw" def get_preprocessed_directory(data_root): return Path(data_root) / "preprocessed" def _log_path_decorator(fn): def _decorated_fn(path, **kwargs): logging.info("Loading %s", path) output = fn(path, **kwargs) logging.info("Finish loading %s", path) return output return _decorated_fn @_log_path_decorator def load_csr(path, debug=False): if debug: # Dummy matrix for debugging. return sp.csr_matrix(np.zeros([10, 10])) return sp.load_npz(str(path)) @_log_path_decorator def load_npy(path): return np.load(str(path)) @functools.lru_cache() def get_arrays(data_root="/data/", use_fused_node_labels=True, use_fused_node_adjacencies=True, return_pca_embeddings=True, k_fold_split_id=None, return_adjacencies=True, use_dummy_adjacencies=False): """Returns all arrays needed for training.""" logging.info("Starting to get files") data_root = Path(data_root) array_dict = {} array_dict["paper_year"] = load_npy(data_root / RAW_NODE_YEAR_FILENAME) if k_fold_split_id is None: train_indices = load_npy(data_root / TRAIN_INDEX_FILENAME) valid_indices = load_npy(data_root / VALID_INDEX_FILENAME) else: train_indices, valid_indices = get_train_and_valid_idx_for_split( k_fold_split_id, num_splits=NUM_K_FOLD_SPLITS, root_path=data_root / K_FOLD_SPLITS_DIR) array_dict["train_indices"] = train_indices array_dict["valid_indices"] = valid_indices array_dict["test_indices"] = load_npy(data_root / TEST_INDEX_FILENAME) if use_fused_node_labels: array_dict["paper_label"] = load_npy(data_root / FUSED_NODE_LABELS_FILENAME) else: array_dict["paper_label"] = load_npy(data_root / RAW_NODE_LABELS_FILENAME) if return_adjacencies: logging.info("Starting to get adjacencies.") if use_fused_node_adjacencies: paper_paper_index = load_csr( data_root / FUSED_PAPER_EDGES_FILENAME, debug=use_dummy_adjacencies) paper_paper_index_t = load_csr( data_root / FUSED_PAPER_EDGES_T_FILENAME, debug=use_dummy_adjacencies) else: paper_paper_index = load_csr( data_root / EDGES_PAPER_PAPER_B, debug=use_dummy_adjacencies) paper_paper_index_t = load_csr( data_root / EDGES_PAPER_PAPER_B_T, debug=use_dummy_adjacencies) array_dict.update( dict( author_institution_index=load_csr( data_root / EDGES_AUTHOR_INSTITUTION, debug=use_dummy_adjacencies), institution_author_index=load_csr( data_root / EDGES_INSTITUTION_AUTHOR, debug=use_dummy_adjacencies), author_paper_index=load_csr( data_root / EDGES_AUTHOR_PAPER, debug=use_dummy_adjacencies), paper_author_index=load_csr( data_root / EDGES_PAPER_AUTHOR, debug=use_dummy_adjacencies), paper_paper_index=paper_paper_index, paper_paper_index_t=paper_paper_index_t, )) if return_pca_embeddings: array_dict["bert_pca_129"] = np.load( data_root / PCA_MERGED_FEATURES_FILENAME, mmap_mode="r") assert array_dict["bert_pca_129"].shape == (NUM_NODES, 129) logging.info("Finish getting files") # pytype: disable=attribute-error assert array_dict["paper_year"].shape[0] == NUM_PAPERS assert array_dict["paper_label"].shape[0] == NUM_PAPERS if return_adjacencies and not use_dummy_adjacencies: array_dict = _fix_adjacency_shapes(array_dict) assert array_dict["paper_author_index"].shape == (NUM_PAPERS, NUM_AUTHORS) assert array_dict["author_paper_index"].shape == (NUM_AUTHORS, NUM_PAPERS) assert array_dict["paper_paper_index"].shape == (NUM_PAPERS, NUM_PAPERS) assert array_dict["paper_paper_index_t"].shape == (NUM_PAPERS, NUM_PAPERS) assert array_dict["institution_author_index"].shape == ( NUM_INSTITUTIONS, NUM_AUTHORS) assert array_dict["author_institution_index"].shape == ( NUM_AUTHORS, NUM_INSTITUTIONS) # pytype: enable=attribute-error return array_dict def add_nodes_year(graph, paper_year): nodes = graph.nodes.copy() indices = nodes["index"] year = paper_year[np.minimum(indices, paper_year.shape[0] - 1)].copy() year[nodes["type"] != 0] = 1900 nodes["year"] = year return graph._replace(nodes=nodes) def add_nodes_label(graph, paper_label): nodes = graph.nodes.copy() indices = nodes["index"] label = paper_label[np.minimum(indices, paper_label.shape[0] - 1)] label[nodes["type"] != 0] = 0 nodes["label"] = label return graph._replace(nodes=nodes) def add_nodes_embedding_from_array(graph, array): """Adds embeddings from the sstable_service for the indices.""" nodes = graph.nodes.copy() indices = nodes["index"] embedding_indices = indices.copy() embedding_indices[nodes["type"] == 1] += NUM_PAPERS embedding_indices[nodes["type"] == 2] += NUM_PAPERS + NUM_AUTHORS # Gather the embeddings for the indices. nodes["features"] = array[embedding_indices] return graph._replace(nodes=nodes) def get_graph_subsampling_dataset( prefix, arrays, shuffle_indices, ratio_unlabeled_data_to_labeled_data, max_nodes, max_edges, **subsampler_kwargs): """Returns tf_dataset for online sampling.""" def generator(): labeled_indices = arrays[f"{prefix}_indices"] if ratio_unlabeled_data_to_labeled_data > 0: num_unlabeled_data_to_add = int(ratio_unlabeled_data_to_labeled_data * labeled_indices.shape[0]) unlabeled_indices = np.random.choice( NUM_PAPERS, size=num_unlabeled_data_to_add, replace=False) root_node_indices = np.concatenate([labeled_indices, unlabeled_indices]) else: root_node_indices = labeled_indices if shuffle_indices: root_node_indices = root_node_indices.copy() np.random.shuffle(root_node_indices) for index in root_node_indices: graph = sub_sampler.subsample_graph( index, arrays["author_institution_index"], arrays["institution_author_index"], arrays["author_paper_index"], arrays["paper_author_index"], arrays["paper_paper_index"], arrays["paper_paper_index_t"], paper_years=arrays["paper_year"], max_nodes=max_nodes, max_edges=max_edges, **subsampler_kwargs) graph = add_nodes_label(graph, arrays["paper_label"]) graph = add_nodes_year(graph, arrays["paper_year"]) graph = tf_graphs.GraphsTuple(*graph) yield graph sample_graph = next(generator()) return tf.data.Dataset.from_generator( generator, output_signature=utils_tf.specs_from_graphs_tuple(sample_graph)) def paper_features_to_author_features( author_paper_index, paper_features): """Averages paper features to authors.""" assert paper_features.shape[0] == NUM_PAPERS assert author_paper_index.shape[0] == NUM_AUTHORS author_features = np.zeros( [NUM_AUTHORS, paper_features.shape[1]], dtype=paper_features.dtype) for author_i in range(NUM_AUTHORS): paper_indices = author_paper_index[author_i].indices author_features[author_i] = paper_features[paper_indices].mean( axis=0, dtype=np.float32) if author_i % 10000 == 0: logging.info("%d/%d", author_i, NUM_AUTHORS) return author_features def author_features_to_institution_features( institution_author_index, author_features): """Averages author features to institutions.""" assert author_features.shape[0] == NUM_AUTHORS assert institution_author_index.shape[0] == NUM_INSTITUTIONS institution_features = np.zeros( [NUM_INSTITUTIONS, author_features.shape[1]], dtype=author_features.dtype) for institution_i in range(NUM_INSTITUTIONS): author_indices = institution_author_index[institution_i].indices institution_features[institution_i] = author_features[ author_indices].mean(axis=0, dtype=np.float32) if institution_i % 10000 == 0: logging.info("%d/%d", institution_i, NUM_INSTITUTIONS) return institution_features def generate_fused_paper_adjacency_matrix(neighbor_indices, neighbor_distances, paper_paper_csr): """Generates fused adjacency matrix for identical nodes.""" # First construct set of identical node indices. # NOTE: Since we take only top K=26 identical pairs for each node, this is not # actually exhaustive. Also, if A and B are equal, and B and C are equal, # this method would not necessarily detect A and C being equal. # However, this should capture almost all cases. logging.info("Generating fused paper adjacency matrix") eps = 0.0 mask = ((neighbor_indices != np.mgrid[:neighbor_indices.shape[0], :1]) & (neighbor_distances <= eps)) identical_pairs = list(map(tuple, np.nonzero(mask))) del mask # Have a csc version for fast column access. paper_paper_csc = paper_paper_csr.tocsc() # Construct new matrix as coo, starting off with original rows/cols. paper_paper_coo = paper_paper_csr.tocoo() new_rows = [paper_paper_coo.row] new_cols = [paper_paper_coo.col] for pair in tqdm.tqdm(identical_pairs): # STEP ONE: First merge papers being cited by the pair. # Add edges from second paper, to all papers cited by first paper. cited_by_first = paper_paper_csr.getrow(pair[0]).nonzero()[1] if cited_by_first.shape[0] > 0: new_rows.append(pair[1] * np.ones_like(cited_by_first)) new_cols.append(cited_by_first) # Add edges from first paper, to all papers cited by second paper. cited_by_second = paper_paper_csr.getrow(pair[1]).nonzero()[1] if cited_by_second.shape[0] > 0: new_rows.append(pair[0] * np.ones_like(cited_by_second)) new_cols.append(cited_by_second) # STEP TWO: Then merge papers that cite the pair. # Add edges to second paper, from all papers citing the first paper. citing_first = paper_paper_csc.getcol(pair[0]).nonzero()[0] if citing_first.shape[0] > 0: new_rows.append(citing_first) new_cols.append(pair[1] * np.ones_like(citing_first)) # Add edges to first paper, from all papers citing the second paper. citing_second = paper_paper_csc.getcol(pair[1]).nonzero()[0] if citing_second.shape[0] > 0: new_rows.append(citing_second) new_cols.append(pair[0] * np.ones_like(citing_second)) logging.info("Done with adjacency loop") paper_paper_coo_shape = paper_paper_coo.shape del paper_paper_csr del paper_paper_csc del paper_paper_coo # All done; now concatenate everything together and form new matrix. new_rows = np.concatenate(new_rows) new_cols = np.concatenate(new_cols) return sp.coo_matrix( (np.ones_like(new_rows, dtype=np.bool), (new_rows, new_cols)), shape=paper_paper_coo_shape).tocsr() def generate_k_fold_splits( train_idx, valid_idx, output_path, num_splits=NUM_K_FOLD_SPLITS): """Generates splits adding fractions of the validation split to training.""" output_path = Path(output_path) np.random.seed(42) valid_idx = np.random.permutation(valid_idx) # Split into `num_parts` (almost) identically sized arrays. valid_idx_parts = np.array_split(valid_idx, num_splits) for i in range(num_splits): # Add all but the i'th subpart to training set. new_train_idx = np.concatenate( [train_idx, *valid_idx_parts[:i], *valid_idx_parts[i+1:]]) # i'th subpart is validation set. new_valid_idx = valid_idx_parts[i] train_path = output_path / f"train_idx_{i}_{num_splits}.npy" valid_path = output_path / f"valid_idx_{i}_{num_splits}.npy" np.save(train_path, new_train_idx) np.save(valid_path, new_valid_idx) logging.info("Saved: %s", train_path) logging.info("Saved: %s", valid_path) def get_train_and_valid_idx_for_split( split_id: int, num_splits: int, root_path: str, ) -> Tuple[np.ndarray, np.ndarray]: """Returns train and valid indices for given split.""" new_train_idx = load_npy(f"{root_path}/train_idx_{split_id}_{num_splits}.npy") new_valid_idx = load_npy(f"{root_path}/valid_idx_{split_id}_{num_splits}.npy") return new_train_idx, new_valid_idx def generate_fused_node_labels(neighbor_indices, neighbor_distances, node_labels, train_indices, valid_indices, test_indices): """Generates fused adjacency matrix for identical nodes.""" logging.info("Generating fused node labels") valid_indices = set(valid_indices.tolist()) test_indices = set(test_indices.tolist()) valid_or_test_indices = valid_indices | test_indices train_indices = train_indices[train_indices < neighbor_indices.shape[0]] # Go through list of all pairs where one node is in training set, and for i in tqdm.tqdm(train_indices): for j in range(neighbor_indices.shape[1]): other_index = neighbor_indices[i][j] # if the other is not a validation or test node, if other_index in valid_or_test_indices: continue # and they are identical, if neighbor_distances[i][j] == 0: # assign the label of the training node to the other node node_labels[other_index] = node_labels[i] return node_labels def _pad_to_shape( sparse_csr_matrix: sp.csr_matrix, output_shape: Tuple[int, int]) -> sp.csr_matrix: """Pads a csr sparse matrix to the given shape.""" # We should not try to expand anything smaller. assert np.all(sparse_csr_matrix.shape <= output_shape) # Maybe it already has the right shape. if sparse_csr_matrix.shape == output_shape: return sparse_csr_matrix # Append as many indptr elements as we need to match the leading size, # This is achieved by just padding with copies of the last indptr element. required_padding = output_shape[0] - sparse_csr_matrix.shape[0] updated_indptr = np.concatenate( [sparse_csr_matrix.indptr] + [sparse_csr_matrix.indptr[-1:]] * required_padding, axis=0) # The change in trailing size does not have structural implications, it just # determines the highest possible value for the indices, so it is sufficient # to just pass the new output shape, with the correct trailing size. return sp.csr.csr_matrix( (sparse_csr_matrix.data, sparse_csr_matrix.indices, updated_indptr), shape=output_shape) def _fix_adjacency_shapes( arrays: Dict[str, sp.csr.csr_matrix], ) -> Dict[str, sp.csr.csr_matrix]: """Fixes the shapes of the adjacency matrices.""" arrays = arrays.copy() for key in ["author_institution_index", "author_paper_index", "paper_paper_index", "institution_author_index", "paper_author_index", "paper_paper_index_t"]: type_sender = key.split("_")[0] type_receiver = key.split("_")[1] arrays[key] = _pad_to_shape( arrays[key], output_shape=(SIZES[type_sender], SIZES[type_receiver])) return arrays
deepmind/deepmind-research
ogb_lsc/mag/data_utils.py
Python
apache-2.0
18,032
<?php namespace Topxia\Common; use Imagine\Image\Box; use Imagine\Gd\Imagine; use Imagine\Image\Point; use Topxia\Service\Common\ServiceKernel; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\HttpFoundation\File\File; use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\HttpFoundation\File\Exception\FileException; class FileToolkit { public static function mungeFilename($fileName, $extensions) { $original = $fileName; // Remove any null bytes. See http://php.net/manual/en/security.filesystem.nullbytes.php $fileName = str_replace(chr(0), '', $fileName); $whitelist = array_unique(explode(' ', trim($extensions))); // Split the filename up by periods. The first part becomes the basename // the last part the final extension. $fileNameParts = explode('.', $fileName); $newFilename = array_shift($fileNameParts); // Remove file basename. $finalExtension = array_pop($fileNameParts); // Remove final extension. // Loop through the middle parts of the name and add an underscore to the // end of each section that could be a file extension but isn't in the list // of allowed extensions. foreach ($fileNameParts as $fileNamePart) { $newFilename .= '.'.$fileNamePart; if (!in_array($fileNamePart, $whitelist) && preg_match("/^[a-zA-Z]{2,5}\d?$/", $fileNamePart)) { $newFilename .= '_'; } } $fileName = $newFilename.'.'.$finalExtension; return $fileName; } public static function validateFileExtension(File $file, $extensions = array()) { if (empty($extensions)) { $extensions = static::getSecureFileExtensions(); } if ($file instanceof UploadedFile) { $filename = $file->getClientOriginalName(); } else { $filename = $file->getFilename(); } $errors = array(); $regex = '/\.('.preg_replace('/ +/', '|', preg_quote($extensions)).')$/i'; if (!preg_match($regex, $filename)) { $errors[] = "只允许上传以下扩展名的文件:".$extensions; } return $errors; } public static function isImageFile(File $file) { $ext = static::getFileExtension($file); return in_array(strtolower($ext), explode(' ', static::getImageExtensions())); } public static function isIcoFile(File $file) { $ext = strtolower(static::getFileExtension($file)); return $ext == 'ico' ? true : false; } public static function generateFilename($ext = '') { $filename = date('Yndhis').'-'.substr(base_convert(sha1(uniqid(mt_rand(), true)), 16, 36), 0, 6); return $filename.'.'.$ext; } public static function getFileExtension(File $file) { return $file instanceof UploadedFile ? $file->getClientOriginalExtension() : $file->getExtension(); } public static function getSecureFileMimeTypes() { $extensions = self::getSecureFileExtensions(); $extensions = explode(' ', $extensions); $mimeTypes = array(); foreach ($extensions as $key => $extension) { $mimeTypes[] = self::getMimeTypeByExtension($extension); } return $mimeTypes; } public static function getSecureFileExtensions() { return 'jpg jpeg gif png txt doc docx xls xlsx pdf ppt pptx pps ods odp mp4 mp3 avi flv wmv wma mov zip rar gz tar 7z swf ico'; } public static function getImageExtensions() { return 'bmp jpg jpeg gif png ico'; } public static function getMimeTypeByExtension($extension) { $mimes = array( 'ez' => 'application/andrew-inset', 'aw' => 'application/applixware', 'atom' => 'application/atom+xml', 'atomcat' => 'application/atomcat+xml', 'atomsvc' => 'application/atomsvc+xml', 'ccxml' => 'application/ccxml+xml', 'cdmia' => 'application/cdmi-capability', 'cdmic' => 'application/cdmi-container', 'cdmid' => 'application/cdmi-domain', 'cdmio' => 'application/cdmi-object', 'cdmiq' => 'application/cdmi-queue', 'cu' => 'application/cu-seeme', 'davmount' => 'application/davmount+xml', 'dbk' => 'application/docbook+xml', 'dssc' => 'application/dssc+der', 'xdssc' => 'application/dssc+xml', 'ecma' => 'application/ecmascript', 'emma' => 'application/emma+xml', 'epub' => 'application/epub+zip', 'exi' => 'application/exi', 'pfr' => 'application/font-tdpfr', 'gml' => 'application/gml+xml', 'gpx' => 'application/gpx+xml', 'gxf' => 'application/gxf', 'stk' => 'application/hyperstudio', 'ink' => 'application/inkml+xml', 'ipfix' => 'application/ipfix', 'jar' => 'application/java-archive', 'ser' => 'application/java-serialized-object', 'class' => 'application/java-vm', 'js' => 'application/javascript', 'json' => 'application/json', 'jsonml' => 'application/jsonml+json', 'lostxml' => 'application/lost+xml', 'hqx' => 'application/mac-binhex40', 'cpt' => 'application/mac-compactpro', 'mads' => 'application/mads+xml', 'mrc' => 'application/marc', 'mrcx' => 'application/marcxml+xml', 'ma' => 'application/mathematica', 'mathml' => 'application/mathml+xml', 'mbox' => 'application/mbox', 'mscml' => 'application/mediaservercontrol+xml', 'metalink' => 'application/metalink+xml', 'meta4' => 'application/metalink4+xml', 'mets' => 'application/mets+xml', 'mods' => 'application/mods+xml', 'm21' => 'application/mp21', 'mp4s' => 'application/mp4', 'doc' => 'application/msword', 'mxf' => 'application/mxf', 'bin' => 'application/octet-stream', 'oda' => 'application/oda', 'opf' => 'application/oebps-package+xml', 'ogx' => 'application/ogg', 'omdoc' => 'application/omdoc+xml', 'onetoc' => 'application/onenote', 'oxps' => 'application/oxps', 'xer' => 'application/patch-ops-error+xml', 'pdf' => 'application/pdf', 'pgp' => 'application/pgp-encrypted', 'asc' => 'application/pgp-signature', 'prf' => 'application/pics-rules', 'p10' => 'application/pkcs10', 'p7m' => 'application/pkcs7-mime', 'p7s' => 'application/pkcs7-signature', 'p8' => 'application/pkcs8', 'ac' => 'application/pkix-attr-cert', 'cer' => 'application/pkix-cert', 'crl' => 'application/pkix-crl', 'pkipath' => 'application/pkix-pkipath', 'pki' => 'application/pkixcmp', 'pls' => 'application/pls+xml', 'ai' => 'application/postscript', 'cww' => 'application/prs.cww', 'pskcxml' => 'application/pskc+xml', 'rdf' => 'application/rdf+xml', 'rif' => 'application/reginfo+xml', 'rnc' => 'application/relax-ng-compact-syntax', 'rl' => 'application/resource-lists+xml', 'rld' => 'application/resource-lists-diff+xml', 'rs' => 'application/rls-services+xml', 'gbr' => 'application/rpki-ghostbusters', 'mft' => 'application/rpki-manifest', 'roa' => 'application/rpki-roa', 'rsd' => 'application/rsd+xml', 'rss' => 'application/rss+xml', 'rtf' => 'application/rtf', 'sbml' => 'application/sbml+xml', 'scq' => 'application/scvp-cv-request', 'scs' => 'application/scvp-cv-response', 'spq' => 'application/scvp-vp-request', 'spp' => 'application/scvp-vp-response', 'sdp' => 'application/sdp', 'setpay' => 'application/set-payment-initiation', 'setreg' => 'application/set-registration-initiation', 'shf' => 'application/shf+xml', 'smi' => 'application/smil+xml', 'rq' => 'application/sparql-query', 'srx' => 'application/sparql-results+xml', 'gram' => 'application/srgs', 'grxml' => 'application/srgs+xml', 'sru' => 'application/sru+xml', 'ssdl' => 'application/ssdl+xml', 'ssml' => 'application/ssml+xml', 'tei' => 'application/tei+xml', 'tfi' => 'application/thraud+xml', 'tsd' => 'application/timestamped-data', 'plb' => 'application/vnd.3gpp.pic-bw-large', 'psb' => 'application/vnd.3gpp.pic-bw-small', 'pvb' => 'application/vnd.3gpp.pic-bw-var', 'tcap' => 'application/vnd.3gpp2.tcap', 'pwn' => 'application/vnd.3m.post-it-notes', 'aso' => 'application/vnd.accpac.simply.aso', 'imp' => 'application/vnd.accpac.simply.imp', 'acu' => 'application/vnd.acucobol', 'atc' => 'application/vnd.acucorp', 'air' => 'application/vnd.adobe.air-application-installer-package+zip', 'fcdt' => 'application/vnd.adobe.formscentral.fcdt', 'fxp' => 'application/vnd.adobe.fxp', 'xdp' => 'application/vnd.adobe.xdp+xml', 'xfdf' => 'application/vnd.adobe.xfdf', 'ahead' => 'application/vnd.ahead.space', 'azf' => 'application/vnd.airzip.filesecure.azf', 'azs' => 'application/vnd.airzip.filesecure.azs', 'azw' => 'application/vnd.amazon.ebook', 'acc' => 'application/vnd.americandynamics.acc', 'ami' => 'application/vnd.amiga.ami', 'apk' => 'application/vnd.android.package-archive', 'cii' => 'application/vnd.anser-web-certificate-issue-initiation', 'fti' => 'application/vnd.anser-web-funds-transfer-initiation', 'atx' => 'application/vnd.antix.game-component', 'mpkg' => 'application/vnd.apple.installer+xml', 'm3u8' => 'application/vnd.apple.mpegurl', 'swi' => 'application/vnd.aristanetworks.swi', 'iota' => 'application/vnd.astraea-software.iota', 'aep' => 'application/vnd.audiograph', 'mpm' => 'application/vnd.blueice.multipass', 'bmi' => 'application/vnd.bmi', 'rep' => 'application/vnd.businessobjects', 'cdxml' => 'application/vnd.chemdraw+xml', 'mmd' => 'application/vnd.chipnuts.karaoke-mmd', 'cdy' => 'application/vnd.cinderella', 'cla' => 'application/vnd.claymore', 'rp9' => 'application/vnd.cloanto.rp9', 'c4g' => 'application/vnd.clonk.c4group', 'c11amc' => 'application/vnd.cluetrust.cartomobile-config', 'c11amz' => 'application/vnd.cluetrust.cartomobile-config-pkg', 'csp' => 'application/vnd.commonspace', 'cdbcmsg' => 'application/vnd.contact.cmsg', 'cmc' => 'application/vnd.cosmocaller', 'clkx' => 'application/vnd.crick.clicker', 'clkk' => 'application/vnd.crick.clicker.keyboard', 'clkp' => 'application/vnd.crick.clicker.palette', 'clkt' => 'application/vnd.crick.clicker.template', 'clkw' => 'application/vnd.crick.clicker.wordbank', 'wbs' => 'application/vnd.criticaltools.wbs+xml', 'pml' => 'application/vnd.ctc-posml', 'ppd' => 'application/vnd.cups-ppd', 'car' => 'application/vnd.curl.car', 'pcurl' => 'application/vnd.curl.pcurl', 'dart' => 'application/vnd.dart', 'rdz' => 'application/vnd.data-vision.rdz', 'uvf' => 'application/vnd.dece.data', 'uvt' => 'application/vnd.dece.ttml+xml', 'uvx' => 'application/vnd.dece.unspecified', 'uvz' => 'application/vnd.dece.zip', 'fe_launch' => 'application/vnd.denovo.fcselayout-link', 'dna' => 'application/vnd.dna', 'mlp' => 'application/vnd.dolby.mlp', 'dpg' => 'application/vnd.dpgraph', 'dfac' => 'application/vnd.dreamfactory', 'kpxx' => 'application/vnd.ds-keypoint', 'ait' => 'application/vnd.dvb.ait', 'svc' => 'application/vnd.dvb.service', 'geo' => 'application/vnd.dynageo', 'mag' => 'application/vnd.ecowin.chart', 'nml' => 'application/vnd.enliven', 'esf' => 'application/vnd.epson.esf', 'msf' => 'application/vnd.epson.msf', 'qam' => 'application/vnd.epson.quickanime', 'slt' => 'application/vnd.epson.salt', 'ssf' => 'application/vnd.epson.ssf', 'es3' => 'application/vnd.eszigno3+xml', 'ez2' => 'application/vnd.ezpix-album', 'ez3' => 'application/vnd.ezpix-package', 'fdf' => 'application/vnd.fdf', 'mseed' => 'application/vnd.fdsn.mseed', 'seed' => 'application/vnd.fdsn.seed', 'gph' => 'application/vnd.flographit', 'ftc' => 'application/vnd.fluxtime.clip', 'fm' => 'application/vnd.framemaker', 'fnc' => 'application/vnd.frogans.fnc', 'ltf' => 'application/vnd.frogans.ltf', 'fsc' => 'application/vnd.fsc.weblaunch', 'oas' => 'application/vnd.fujitsu.oasys', 'oa2' => 'application/vnd.fujitsu.oasys2', 'oa3' => 'application/vnd.fujitsu.oasys3', 'fg5' => 'application/vnd.fujitsu.oasysgp', 'bh2' => 'application/vnd.fujitsu.oasysprs', 'ddd' => 'application/vnd.fujixerox.ddd', 'xdw' => 'application/vnd.fujixerox.docuworks', 'xbd' => 'application/vnd.fujixerox.docuworks.binder', 'fzs' => 'application/vnd.fuzzysheet', 'txd' => 'application/vnd.genomatix.tuxedo', 'ggb' => 'application/vnd.geogebra.file', 'ggt' => 'application/vnd.geogebra.tool', 'gex' => 'application/vnd.geometry-explorer', 'gxt' => 'application/vnd.geonext', 'g2w' => 'application/vnd.geoplan', 'g3w' => 'application/vnd.geospace', 'gmx' => 'application/vnd.gmx', 'kml' => 'application/vnd.google-earth.kml+xml', 'kmz' => 'application/vnd.google-earth.kmz', 'gqf' => 'application/vnd.grafeq', 'gac' => 'application/vnd.groove-account', 'ghf' => 'application/vnd.groove-help', 'gim' => 'application/vnd.groove-identity-message', 'grv' => 'application/vnd.groove-injector', 'gtm' => 'application/vnd.groove-tool-message', 'tpl' => 'application/vnd.groove-tool-template', 'vcg' => 'application/vnd.groove-vcard', 'hal' => 'application/vnd.hal+xml', 'zmm' => 'application/vnd.handheld-entertainment+xml', 'hbci' => 'application/vnd.hbci', 'les' => 'application/vnd.hhe.lesson-player', 'hpgl' => 'application/vnd.hp-hpgl', 'hpid' => 'application/vnd.hp-hpid', 'hps' => 'application/vnd.hp-hps', 'jlt' => 'application/vnd.hp-jlyt', 'pcl' => 'application/vnd.hp-pcl', 'pclxl' => 'application/vnd.hp-pclxl', 'sfd-hdstx' => 'application/vnd.hydrostatix.sof-data', 'mpy' => 'application/vnd.ibm.minipay', 'afp' => 'application/vnd.ibm.modcap', 'irm' => 'application/vnd.ibm.rights-management', 'sc' => 'application/vnd.ibm.secure-container', 'icc' => 'application/vnd.iccprofile', 'igl' => 'application/vnd.igloader', 'ivp' => 'application/vnd.immervision-ivp', 'ivu' => 'application/vnd.immervision-ivu', 'igm' => 'application/vnd.insors.igm', 'xpw' => 'application/vnd.intercon.formnet', 'i2g' => 'application/vnd.intergeo', 'qbo' => 'application/vnd.intu.qbo', 'qfx' => 'application/vnd.intu.qfx', 'rcprofile' => 'application/vnd.ipunplugged.rcprofile', 'irp' => 'application/vnd.irepository.package+xml', 'xpr' => 'application/vnd.is-xpr', 'fcs' => 'application/vnd.isac.fcs', 'jam' => 'application/vnd.jam', 'rms' => 'application/vnd.jcp.javame.midlet-rms', 'jisp' => 'application/vnd.jisp', 'joda' => 'application/vnd.joost.joda-archive', 'ktz' => 'application/vnd.kahootz', 'karbon' => 'application/vnd.kde.karbon', 'chrt' => 'application/vnd.kde.kchart', 'kfo' => 'application/vnd.kde.kformula', 'flw' => 'application/vnd.kde.kivio', 'kon' => 'application/vnd.kde.kontour', 'kpr' => 'application/vnd.kde.kpresenter', 'ksp' => 'application/vnd.kde.kspread', 'kwd' => 'application/vnd.kde.kword', 'htke' => 'application/vnd.kenameaapp', 'kia' => 'application/vnd.kidspiration', 'kne' => 'application/vnd.kinar', 'skp' => 'application/vnd.koan', 'sse' => 'application/vnd.kodak-descriptor', 'lasxml' => 'application/vnd.las.las+xml', 'lbd' => 'application/vnd.llamagraphics.life-balance.desktop', 'lbe' => 'application/vnd.llamagraphics.life-balance.exchange+xml', '123' => 'application/vnd.lotus-1-2-3', 'apr' => 'application/vnd.lotus-approach', 'pre' => 'application/vnd.lotus-freelance', 'nsf' => 'application/vnd.lotus-notes', 'org' => 'application/vnd.lotus-organizer', 'scm' => 'application/vnd.lotus-screencam', 'lwp' => 'application/vnd.lotus-wordpro', 'portpkg' => 'application/vnd.macports.portpkg', 'mcd' => 'application/vnd.mcd', 'mc1' => 'application/vnd.medcalcdata', 'cdkey' => 'application/vnd.mediastation.cdkey', 'mwf' => 'application/vnd.mfer', 'mfm' => 'application/vnd.mfmp', 'flo' => 'application/vnd.micrografx.flo', 'igx' => 'application/vnd.micrografx.igx', 'mif' => 'application/vnd.mif', 'daf' => 'application/vnd.mobius.daf', 'dis' => 'application/vnd.mobius.dis', 'mbk' => 'application/vnd.mobius.mbk', 'mqy' => 'application/vnd.mobius.mqy', 'msl' => 'application/vnd.mobius.msl', 'plc' => 'application/vnd.mobius.plc', 'txf' => 'application/vnd.mobius.txf', 'mpn' => 'application/vnd.mophun.application', 'mpc' => 'application/vnd.mophun.certificate', 'xul' => 'application/vnd.mozilla.xul+xml', 'cil' => 'application/vnd.ms-artgalry', 'cab' => 'application/vnd.ms-cab-compressed', 'xls' => 'application/vnd.ms-excel', 'xlam' => 'application/vnd.ms-excel.addin.macroenabled.12', 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroenabled.12', 'xlsm' => 'application/vnd.ms-excel.sheet.macroenabled.12', 'xltm' => 'application/vnd.ms-excel.template.macroenabled.12', 'eot' => 'application/vnd.ms-fontobject', 'chm' => 'application/vnd.ms-htmlhelp', 'ims' => 'application/vnd.ms-ims', 'lrm' => 'application/vnd.ms-lrm', 'thmx' => 'application/vnd.ms-officetheme', 'cat' => 'application/vnd.ms-pki.seccat', 'stl' => 'application/vnd.ms-pki.stl', 'ppt' => 'application/vnd.ms-powerpoint', 'ppam' => 'application/vnd.ms-powerpoint.addin.macroenabled.12', 'pptm' => 'application/vnd.ms-powerpoint.presentation.macroenabled.12', 'sldm' => 'application/vnd.ms-powerpoint.slide.macroenabled.12', 'ppsm' => 'application/vnd.ms-powerpoint.slideshow.macroenabled.12', 'potm' => 'application/vnd.ms-powerpoint.template.macroenabled.12', 'mpp' => 'application/vnd.ms-project', 'docm' => 'application/vnd.ms-word.document.macroenabled.12', 'dotm' => 'application/vnd.ms-word.template.macroenabled.12', 'wps' => 'application/vnd.ms-works', 'wpl' => 'application/vnd.ms-wpl', 'xps' => 'application/vnd.ms-xpsdocument', 'mseq' => 'application/vnd.mseq', 'mus' => 'application/vnd.musician', 'msty' => 'application/vnd.muvee.style', 'taglet' => 'application/vnd.mynfc', 'nlu' => 'application/vnd.neurolanguage.nlu', 'ntf' => 'application/vnd.nitf', 'nnd' => 'application/vnd.noblenet-directory', 'nns' => 'application/vnd.noblenet-sealer', 'nnw' => 'application/vnd.noblenet-web', 'ngdat' => 'application/vnd.nokia.n-gage.data', 'n-gage' => 'application/vnd.nokia.n-gage.symbian.install', 'rpst' => 'application/vnd.nokia.radio-preset', 'rpss' => 'application/vnd.nokia.radio-presets', 'edm' => 'application/vnd.novadigm.edm', 'edx' => 'application/vnd.novadigm.edx', 'ext' => 'application/vnd.novadigm.ext', 'odc' => 'application/vnd.oasis.opendocument.chart', 'otc' => 'application/vnd.oasis.opendocument.chart-template', 'odb' => 'application/vnd.oasis.opendocument.database', 'odf' => 'application/vnd.oasis.opendocument.formula', 'odft' => 'application/vnd.oasis.opendocument.formula-template', 'odg' => 'application/vnd.oasis.opendocument.graphics', 'otg' => 'application/vnd.oasis.opendocument.graphics-template', 'odi' => 'application/vnd.oasis.opendocument.image', 'oti' => 'application/vnd.oasis.opendocument.image-template', 'odp' => 'application/vnd.oasis.opendocument.presentation', 'otp' => 'application/vnd.oasis.opendocument.presentation-template', 'ods' => 'application/vnd.oasis.opendocument.spreadsheet', 'ots' => 'application/vnd.oasis.opendocument.spreadsheet-template', 'odt' => 'application/vnd.oasis.opendocument.text', 'odm' => 'application/vnd.oasis.opendocument.text-master', 'ott' => 'application/vnd.oasis.opendocument.text-template', 'oth' => 'application/vnd.oasis.opendocument.text-web', 'xo' => 'application/vnd.olpc-sugar', 'dd2' => 'application/vnd.oma.dd2+xml', 'oxt' => 'application/vnd.openofficeorg.extension', 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide', 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template', 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'mgp' => 'application/vnd.osgeo.mapguide.package', 'dp' => 'application/vnd.osgi.dp', 'esa' => 'application/vnd.osgi.subsystem', 'pdb' => 'application/vnd.palm', 'paw' => 'application/vnd.pawaafile', 'str' => 'application/vnd.pg.format', 'ei6' => 'application/vnd.pg.osasli', 'efif' => 'application/vnd.picsel', 'wg' => 'application/vnd.pmi.widget', 'plf' => 'application/vnd.pocketlearn', 'pbd' => 'application/vnd.powerbuilder6', 'box' => 'application/vnd.previewsystems.box', 'mgz' => 'application/vnd.proteus.magazine', 'qps' => 'application/vnd.publishare-delta-tree', 'ptid' => 'application/vnd.pvi.ptid1', 'qxd' => 'application/vnd.quark.quarkxpress', 'bed' => 'application/vnd.realvnc.bed', 'mxl' => 'application/vnd.recordare.musicxml', 'musicxml' => 'application/vnd.recordare.musicxml+xml', 'cryptonote' => 'application/vnd.rig.cryptonote', 'cod' => 'application/vnd.rim.cod', 'rm' => 'application/vnd.rn-realmedia', 'rmvb' => 'application/vnd.rn-realmedia-vbr', 'link66' => 'application/vnd.route66.link66+xml', 'st' => 'application/vnd.sailingtracker.track', 'see' => 'application/vnd.seemail', 'sema' => 'application/vnd.sema', 'semd' => 'application/vnd.semd', 'semf' => 'application/vnd.semf', 'ifm' => 'application/vnd.shana.informed.formdata', 'itp' => 'application/vnd.shana.informed.formtemplate', 'iif' => 'application/vnd.shana.informed.interchange', 'ipk' => 'application/vnd.shana.informed.package', 'twd' => 'application/vnd.simtech-mindmapper', 'mmf' => 'application/vnd.smaf', 'teacher' => 'application/vnd.smart.teacher', 'sdkm' => 'application/vnd.solent.sdkm+xml', 'dxp' => 'application/vnd.spotfire.dxp', 'sfs' => 'application/vnd.spotfire.sfs', 'sdc' => 'application/vnd.stardivision.calc', 'sda' => 'application/vnd.stardivision.draw', 'sdd' => 'application/vnd.stardivision.impress', 'smf' => 'application/vnd.stardivision.math', 'sdw' => 'application/vnd.stardivision.writer', 'sgl' => 'application/vnd.stardivision.writer-global', 'smzip' => 'application/vnd.stepmania.package', 'sm' => 'application/vnd.stepmania.stepchart', 'sxc' => 'application/vnd.sun.xml.calc', 'stc' => 'application/vnd.sun.xml.calc.template', 'sxd' => 'application/vnd.sun.xml.draw', 'std' => 'application/vnd.sun.xml.draw.template', 'sxi' => 'application/vnd.sun.xml.impress', 'sti' => 'application/vnd.sun.xml.impress.template', 'sxm' => 'application/vnd.sun.xml.math', 'sxw' => 'application/vnd.sun.xml.writer', 'sxg' => 'application/vnd.sun.xml.writer.global', 'stw' => 'application/vnd.sun.xml.writer.template', 'sus' => 'application/vnd.sus-calendar', 'svd' => 'application/vnd.svd', 'sis' => 'application/vnd.symbian.install', 'xsm' => 'application/vnd.syncml+xml', 'bdm' => 'application/vnd.syncml.dm+wbxml', 'xdm' => 'application/vnd.syncml.dm+xml', 'tao' => 'application/vnd.tao.intent-module-archive', 'pcap' => 'application/vnd.tcpdump.pcap', 'tmo' => 'application/vnd.tmobile-livetv', 'tpt' => 'application/vnd.trid.tpt', 'mxs' => 'application/vnd.triscape.mxs', 'tra' => 'application/vnd.trueapp', 'ufd' => 'application/vnd.ufdl', 'utz' => 'application/vnd.uiq.theme', 'umj' => 'application/vnd.umajin', 'unityweb' => 'application/vnd.unity', 'uoml' => 'application/vnd.uoml+xml', 'vcx' => 'application/vnd.vcx', 'vsd' => 'application/vnd.visio', 'vis' => 'application/vnd.visionary', 'vsf' => 'application/vnd.vsf', 'wbxml' => 'application/vnd.wap.wbxml', 'wmlc' => 'application/vnd.wap.wmlc', 'wmlsc' => 'application/vnd.wap.wmlscriptc', 'wtb' => 'application/vnd.webturbo', 'nbp' => 'application/vnd.wolfram.player', 'wpd' => 'application/vnd.wordperfect', 'wqd' => 'application/vnd.wqd', 'stf' => 'application/vnd.wt.stf', 'xar' => 'application/vnd.xara', 'xfdl' => 'application/vnd.xfdl', 'hvd' => 'application/vnd.yamaha.hv-dic', 'hvs' => 'application/vnd.yamaha.hv-script', 'hvp' => 'application/vnd.yamaha.hv-voice', 'osf' => 'application/vnd.yamaha.openscoreformat', 'osfpvg' => 'application/vnd.yamaha.openscoreformat.osfpvg+xml', 'saf' => 'application/vnd.yamaha.smaf-audio', 'spf' => 'application/vnd.yamaha.smaf-phrase', 'cmp' => 'application/vnd.yellowriver-custom-menu', 'zir' => 'application/vnd.zul', 'zaz' => 'application/vnd.zzazz.deck+xml', 'vxml' => 'application/voicexml+xml', 'wgt' => 'application/widget', 'hlp' => 'application/winhlp', 'wsdl' => 'application/wsdl+xml', 'wspolicy' => 'application/wspolicy+xml', '7z' => 'application/x-7z-compressed', 'abw' => 'application/x-abiword', 'ace' => 'application/x-ace-compressed', 'dmg' => 'application/x-apple-diskimage', 'aab' => 'application/x-authorware-bin', 'aam' => 'application/x-authorware-map', 'aas' => 'application/x-authorware-seg', 'bcpio' => 'application/x-bcpio', 'torrent' => 'application/x-bittorrent', 'blb' => 'application/x-blorb', 'bz' => 'application/x-bzip', 'bz2' => 'application/x-bzip2', 'cbr' => 'application/x-cbr', 'vcd' => 'application/x-cdlink', 'cfs' => 'application/x-cfs-compressed', 'chat' => 'application/x-chat', 'pgn' => 'application/x-chess-pgn', 'nsc' => 'application/x-conference', 'cpio' => 'application/x-cpio', 'csh' => 'application/x-csh', 'deb' => 'application/x-debian-package', 'dgc' => 'application/x-dgc-compressed', 'dir' => 'application/x-director', 'wad' => 'application/x-doom', 'ncx' => 'application/x-dtbncx+xml', 'dtb' => 'application/x-dtbook+xml', 'res' => 'application/x-dtbresource+xml', 'dvi' => 'application/x-dvi', 'evy' => 'application/x-envoy', 'eva' => 'application/x-eva', 'bdf' => 'application/x-font-bdf', 'gsf' => 'application/x-font-ghostscript', 'psf' => 'application/x-font-linux-psf', 'otf' => 'application/x-font-otf', 'pcf' => 'application/x-font-pcf', 'snf' => 'application/x-font-snf', 'ttf' => 'application/x-font-ttf', 'pfa' => 'application/x-font-type1', 'woff' => 'application/x-font-woff', 'arc' => 'application/x-freearc', 'spl' => 'application/x-futuresplash', 'gca' => 'application/x-gca-compressed', 'ulx' => 'application/x-glulx', 'gnumeric' => 'application/x-gnumeric', 'gramps' => 'application/x-gramps-xml', 'gtar' => 'application/x-gtar', 'hdf' => 'application/x-hdf', 'install' => 'application/x-install-instructions', 'iso' => 'application/x-iso9660-image', 'jnlp' => 'application/x-java-jnlp-file', 'latex' => 'application/x-latex', 'lzh' => 'application/x-lzh-compressed', 'mie' => 'application/x-mie', 'prc' => 'application/x-mobipocket-ebook', 'application' => 'application/x-ms-application', 'lnk' => 'application/x-ms-shortcut', 'wmd' => 'application/x-ms-wmd', 'wmz' => 'application/x-ms-wmz', 'xbap' => 'application/x-ms-xbap', 'mdb' => 'application/x-msaccess', 'obd' => 'application/x-msbinder', 'crd' => 'application/x-mscardfile', 'clp' => 'application/x-msclip', 'exe' => 'application/x-msdownload', 'mvb' => 'application/x-msmediaview', 'wmf' => 'application/x-msmetafile', 'mny' => 'application/x-msmoney', 'pub' => 'application/x-mspublisher', 'scd' => 'application/x-msschedule', 'trm' => 'application/x-msterminal', 'wri' => 'application/x-mswrite', 'nc' => 'application/x-netcdf', 'nzb' => 'application/x-nzb', 'p12' => 'application/x-pkcs12', 'p7b' => 'application/x-pkcs7-certificates', 'p7r' => 'application/x-pkcs7-certreqresp', 'rar' => 'application/x-rar-compressed', 'rar' => 'application/x-rar', 'ris' => 'application/x-research-info-systems', 'sh' => 'application/x-sh', 'shar' => 'application/x-shar', 'swf' => 'application/x-shockwave-flash', 'xap' => 'application/x-silverlight-app', 'sql' => 'application/x-sql', 'sit' => 'application/x-stuffit', 'sitx' => 'application/x-stuffitx', 'srt' => 'application/x-subrip', 'sv4cpio' => 'application/x-sv4cpio', 'sv4crc' => 'application/x-sv4crc', 't3' => 'application/x-t3vm-image', 'gam' => 'application/x-tads', 'tar' => 'application/x-tar', 'tcl' => 'application/x-tcl', 'tex' => 'application/x-tex', 'tfm' => 'application/x-tex-tfm', 'texinfo' => 'application/x-texinfo', 'obj' => 'application/x-tgif', 'ustar' => 'application/x-ustar', 'src' => 'application/x-wais-source', 'der' => 'application/x-x509-ca-cert', 'fig' => 'application/x-xfig', 'xlf' => 'application/x-xliff+xml', 'xpi' => 'application/x-xpinstall', 'xz' => 'application/x-xz', 'z1' => 'application/x-zmachine', 'xaml' => 'application/xaml+xml', 'xdf' => 'application/xcap-diff+xml', 'xenc' => 'application/xenc+xml', 'xhtml' => 'application/xhtml+xml', 'xml' => 'application/xml', 'dtd' => 'application/xml-dtd', 'xop' => 'application/xop+xml', 'xpl' => 'application/xproc+xml', 'xslt' => 'application/xslt+xml', 'xspf' => 'application/xspf+xml', 'mxml' => 'application/xv+xml', 'yang' => 'application/yang', 'yin' => 'application/yin+xml', 'zip' => 'application/zip', 'adp' => 'audio/adpcm', 'au' => 'audio/basic', 'mid' => 'audio/midi', 'mp4a' => 'audio/mp4', 'mpga' => 'audio/mpeg', 'oga' => 'audio/ogg', 's3m' => 'audio/s3m', 'sil' => 'audio/silk', 'uva' => 'audio/vnd.dece.audio', 'eol' => 'audio/vnd.digital-winds', 'dra' => 'audio/vnd.dra', 'dts' => 'audio/vnd.dts', 'dtshd' => 'audio/vnd.dts.hd', 'lvp' => 'audio/vnd.lucent.voice', 'pya' => 'audio/vnd.ms-playready.media.pya', 'ecelp4800' => 'audio/vnd.nuera.ecelp4800', 'ecelp7470' => 'audio/vnd.nuera.ecelp7470', 'ecelp9600' => 'audio/vnd.nuera.ecelp9600', 'rip' => 'audio/vnd.rip', 'weba' => 'audio/webm', 'aac' => 'audio/x-aac', 'aif' => 'audio/x-aiff', 'caf' => 'audio/x-caf', 'flac' => 'audio/x-flac', 'mka' => 'audio/x-matroska', 'm3u' => 'audio/x-mpegurl', 'wax' => 'audio/x-ms-wax', 'wma' => 'audio/x-ms-wma', 'ram' => 'audio/x-pn-realaudio', 'rmp' => 'audio/x-pn-realaudio-plugin', 'wav' => 'audio/x-wav', 'xm' => 'audio/xm', 'cdx' => 'chemical/x-cdx', 'cif' => 'chemical/x-cif', 'cmdf' => 'chemical/x-cmdf', 'cml' => 'chemical/x-cml', 'csml' => 'chemical/x-csml', 'xyz' => 'chemical/x-xyz', 'bmp' => 'image/bmp', 'cgm' => 'image/cgm', 'g3' => 'image/g3fax', 'gif' => 'image/gif', 'ief' => 'image/ief', 'jpeg' => 'image/jpeg', 'ktx' => 'image/ktx', 'png' => 'image/png', 'btif' => 'image/prs.btif', 'sgi' => 'image/sgi', 'svg' => 'image/svg+xml', 'tiff' => 'image/tiff', 'psd' => 'image/vnd.adobe.photoshop', 'uvi' => 'image/vnd.dece.graphic', 'sub' => 'image/vnd.dvb.subtitle', 'djvu' => 'image/vnd.djvu', 'dwg' => 'image/vnd.dwg', 'dxf' => 'image/vnd.dxf', 'fbs' => 'image/vnd.fastbidsheet', 'fpx' => 'image/vnd.fpx', 'fst' => 'image/vnd.fst', 'mmr' => 'image/vnd.fujixerox.edmics-mmr', 'rlc' => 'image/vnd.fujixerox.edmics-rlc', 'mdi' => 'image/vnd.ms-modi', 'wdp' => 'image/vnd.ms-photo', 'npx' => 'image/vnd.net-fpx', 'wbmp' => 'image/vnd.wap.wbmp', 'xif' => 'image/vnd.xiff', 'webp' => 'image/webp', '3ds' => 'image/x-3ds', 'ras' => 'image/x-cmu-raster', 'cmx' => 'image/x-cmx', 'fh' => 'image/x-freehand', 'ico' => 'image/x-icon', 'sid' => 'image/x-mrsid-image', 'pcx' => 'image/x-pcx', 'pic' => 'image/x-pict', 'pnm' => 'image/x-portable-anymap', 'pbm' => 'image/x-portable-bitmap', 'pgm' => 'image/x-portable-graymap', 'ppm' => 'image/x-portable-pixmap', 'rgb' => 'image/x-rgb', 'tga' => 'image/x-tga', 'xbm' => 'image/x-xbitmap', 'xpm' => 'image/x-xpixmap', 'xwd' => 'image/x-xwindowdump', 'eml' => 'message/rfc822', 'igs' => 'model/iges', 'msh' => 'model/mesh', 'dae' => 'model/vnd.collada+xml', 'dwf' => 'model/vnd.dwf', 'gdl' => 'model/vnd.gdl', 'gtw' => 'model/vnd.gtw', 'mts' => 'model/vnd.mts', 'vtu' => 'model/vnd.vtu', 'wrl' => 'model/vrml', 'x3db' => 'model/x3d+binary', 'x3dv' => 'model/x3d+vrml', 'x3d' => 'model/x3d+xml', 'appcache' => 'text/cache-manifest', 'ics' => 'text/calendar', 'css' => 'text/css', 'csv' => 'text/csv', 'html' => 'text/html', 'n3' => 'text/n3', 'txt' => 'text/plain', 'dsc' => 'text/prs.lines.tag', 'rtx' => 'text/richtext', 'sgml' => 'text/sgml', 'tsv' => 'text/tab-separated-values', 't' => 'text/troff', 'ttl' => 'text/turtle', 'uri' => 'text/uri-list', 'vcard' => 'text/vcard', 'curl' => 'text/vnd.curl', 'dcurl' => 'text/vnd.curl.dcurl', 'scurl' => 'text/vnd.curl.scurl', 'mcurl' => 'text/vnd.curl.mcurl', 'sub' => 'text/vnd.dvb.subtitle', 'fly' => 'text/vnd.fly', 'flx' => 'text/vnd.fmi.flexstor', 'gv' => 'text/vnd.graphviz', '3dml' => 'text/vnd.in3d.3dml', 'spot' => 'text/vnd.in3d.spot', 'jad' => 'text/vnd.sun.j2me.app-descriptor', 'wml' => 'text/vnd.wap.wml', 'wmls' => 'text/vnd.wap.wmlscript', 's' => 'text/x-asm', 'c' => 'text/x-c', 'f' => 'text/x-fortran', 'p' => 'text/x-pascal', 'java' => 'text/x-java-source', 'opml' => 'text/x-opml', 'nfo' => 'text/x-nfo', 'etx' => 'text/x-setext', 'sfv' => 'text/x-sfv', 'uu' => 'text/x-uuencode', 'vcs' => 'text/x-vcalendar', 'vcf' => 'text/x-vcard', '3gp' => 'video/3gpp', '3g2' => 'video/3gpp2', 'h261' => 'video/h261', 'h263' => 'video/h263', 'h264' => 'video/h264', 'jpgv' => 'video/jpeg', 'jpm' => 'video/jpm', 'mj2' => 'video/mj2', 'mp4' => 'video/mp4', 'mpeg' => 'video/mpeg', 'ogv' => 'video/ogg', 'qt' => 'video/quicktime', 'uvh' => 'video/vnd.dece.hd', 'uvm' => 'video/vnd.dece.mobile', 'uvp' => 'video/vnd.dece.pd', 'uvs' => 'video/vnd.dece.sd', 'uvv' => 'video/vnd.dece.video', 'dvb' => 'video/vnd.dvb.file', 'fvt' => 'video/vnd.fvt', 'mxu' => 'video/vnd.mpegurl', 'pyv' => 'video/vnd.ms-playready.media.pyv', 'uvu' => 'video/vnd.uvvu.mp4', 'viv' => 'video/vnd.vivo', 'webm' => 'video/webm', 'f4v' => 'video/x-f4v', 'fli' => 'video/x-fli', 'flv' => 'video/x-flv', 'm4v' => 'video/x-m4v', 'mkv' => 'video/x-matroska', 'mng' => 'video/x-mng', 'asf' => 'video/x-ms-asf', 'vob' => 'video/x-ms-vob', 'wm' => 'video/x-ms-wm', 'wmv' => 'video/x-ms-wmv', 'wmx' => 'video/x-ms-wmx', 'wvx' => 'video/x-ms-wvx', 'avi' => 'video/x-msvideo', 'movie' => 'video/x-sgi-movie', 'smv' => 'video/x-smv', 'ice' => 'x-conference/x-cooltalk', 'mpg' => 'video/mpeg', 'mp3' => 'audio/mpeg', 'gz' => 'application/x-gzip', 'jpg' => 'image/jpeg', 'pps' => 'application/vnd.ms-powerpoint', 'mov' => 'video/quicktime' ); return empty($mimes[$extension]) ? null : $mimes[$extension]; } public static function getFileTypeByExtension($extension) { $extension = strtolower($extension); if (in_array($extension, array('mp4', 'avi', 'mpg', 'flv', 'f4v', 'wmv', 'mov', 'rmvb', 'mkv', 'm4v'))) { return 'video'; } elseif (in_array($extension, array('mp3', 'wma'))) { return 'audio'; } elseif (in_array($extension, array('jpg', 'jpeg', 'png', 'gif', 'bmp'))) { return 'image'; } elseif (in_array($extension, array('doc', 'docx', 'pdf', 'xls', 'xlsx', 'wps', 'odt'))) { return 'document'; } elseif (in_array($extension, array('ppt', 'pptx'))) { return 'ppt'; } elseif (in_array($extension, array('swf'))) { return 'flash'; } elseif (in_array($extension, array('srt'))) { return 'subtitle'; } else { return 'other'; } } public static function formatFileSize($size) { $currentValue = $currentUnit = null; $unitExps = array('B' => 0, 'KB' => 1, 'MB' => 2, 'GB' => 3); foreach ($unitExps as $unit => $exp) { $divisor = pow(1024, $exp); $currentUnit = $unit; $currentValue = $size / $divisor; if ($currentValue < 1024) { break; } } return sprintf('%.1f', $currentValue).$currentUnit; } public static function getMaxFilesize() { $max = strtolower(ini_get('upload_max_filesize')); if ('' === $max) { return PHP_INT_MAX; } if (preg_match('#^\+?(0x?)?(.*?)([kmg]?)$#', $max, $match)) { $shifts = array('' => 0, 'k' => 10, 'm' => 20, 'g' => 30); $bases = array('' => 10, '0' => 8, '0x' => 16); return intval($match[2], $bases[$match[1]]) << $shifts[$match[3]]; } return 0; } public static function moveFile($originFile, $targetGroup) { $targetFilenamePrefix = rand(10000, 99999); $hash = substr(md5($targetFilenamePrefix.time()), -8); $ext = $originFile->getClientOriginalExtension(); $filename = $targetFilenamePrefix.$hash.'.'.$ext; $directory = ServiceKernel::instance()->getParameter('topxia.upload.public_directory').'/'.$targetGroup; $file = $originFile->move($directory, $filename); return $file; } public static function remove($filepath) { if (empty($filepath)) { throw new \RuntimeException("filepath to be deleted is empty"); } $isRemoved = false; $prefixArr = array('data/private_files', 'data/udisk', 'web/files'); foreach ($prefixArr as $prefix) { if (strpos($filepath, trim($prefix))) { $fileSystem = new Filesystem(); if ($fileSystem->exists($filepath)) { $fileSystem->remove($filepath); } $isRemoved = true; break; } } if (!$isRemoved) { $prefixString = join(' || ', $prefixArr); throw new \RuntimeException("{$filepath} is not allowed to be deleted without prefix {$prefixString}"); } } public static function crop($rawImage, $targetPath, $x, $y, $width, $height, $resizeWidth = 0, $resizeHeight = 0) { $image = $rawImage->copy(); $image->crop(new Point($x, $y), new Box($width, $height)); if ($resizeWidth > 0 && $resizeHeight > 0) { $image->resize(new Box($resizeWidth, $resizeHeight)); } $image->save($targetPath); return $image; } public static function resize($image, $targetPath, $resizeWidth = 0, $resizeHeight = 0) { $image->resize(new Box($resizeWidth, $resizeHeight)); $image->save($targetPath); return $image; } public static function cropImages($filePath, $options) { $pathinfo = pathinfo($filePath); $imagine = new Imagine(); $rawImage = $imagine->open($filePath); $naturalSize = $rawImage->getSize(); $rate = $naturalSize->getWidth() / $options["width"]; $options["w"] = $rate * $options["w"]; $options["h"] = $rate * $options["h"]; $options["x"] = $rate * $options["x"]; $options["y"] = $rate * $options["y"]; $filePaths = array(); if (!empty($options["imgs"]) && count($options["imgs"]) > 0) { foreach ($options["imgs"] as $key => $value) { $savedFilePath = "{$pathinfo['dirname']}/{$pathinfo['filename']}_{$key}.{$pathinfo['extension']}"; $image = static::crop($rawImage, $savedFilePath, $options['x'], $options['y'], $options['w'], $options['h'], $value[0], $value[1]); $filePaths[$key] = $savedFilePath; } } else { $savedFilePath = "{$pathinfo['dirname']}/{$pathinfo['filename']}.{$pathinfo['extension']}"; $image = static::crop($rawImage, $savedFilePath, $options['x'], $options['y'], $options['w'], $options['h']); $filePaths[] = $savedFilePath; } return $filePaths; } public static function reduceImgQuality($fullPath, $level = 10) { $extension = strtolower(substr(strrchr($fullPath, '.'), 1)); $options = array(); if (in_array($extension, array('jpg', 'jpeg'))) { $options['jpeg_quality'] = $level * 10; } elseif ($extension == 'png') { $options['png_compression_level'] = $level; } else { return $fullPath; } try { $imagine = new Imagine(); $image = $imagine->open($fullPath)->save($fullPath, $options); } catch (\Exception $e) { throw new \Exception("该文件为非图片格式文件,请重新上传。"); } } public static function getImgInfo($fullPath, $width, $height) { try { $imagine = new Imagine(); $image = $imagine->open($fullPath); } catch (\Exception $e) { throw new \Exception("该文件为非图片格式文件,请重新上传。"); } $naturalSize = $image->getSize(); $scaledSize = $naturalSize->widen($width)->heighten($height); return array($naturalSize, $scaledSize); } //将图片旋转正确 public static function imagerotatecorrect($path) { try { //只旋转JPEG的图片 //IMAGETYPE_JPEG = 2 if (extension_loaded('gd') && extension_loaded('exif') && exif_imagetype($path) == 2) { $exif = @exif_read_data($path); if (!empty($exif['Orientation'])) { $image = imagecreatefromstring(file_get_contents($path)); switch ($exif['Orientation']) { case 8: $image = imagerotate($image, 90, 0); break; case 3: $image = imagerotate($image, 180, 0); break; case 6: $image = imagerotate($image, -90, 0); break; } imagejpeg($image, $path); imagedestroy($image); return $path; } } } catch (\Exception $e) { //报错了不旋转,保证不影响上传流程 } return false; } protected function getServiceKernel() { return ServiceKernel::instance(); } public static function downloadImg($url, $savePath) { $curl = curl_init($url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $imageData = curl_exec($curl); curl_close($curl); $tp = @fopen($savePath, 'w'); fwrite($tp, $imageData); fclose($tp); return $savePath; } }
18826252059/im
src/Topxia/Common/FileToolkit.php
PHP
apache-2.0
56,525
import android.content.Context; import android.graphics.Bitmap; import android.graphics.Rect; import android.graphics.RectF; import android.util.DisplayMetrics; import android.view.Display; import android.view.View; import android.view.WindowManager; public final class lsr { static final lsp<Bitmap> a = new lsq(64); private final RectF A = new RectF(); private final RectF B = new RectF(); private int C; private final Rect[] D; private boolean E; int b; lsv c; int d; int e = 0; final kp<lss> f = new kp(); final Object g = new Object(); final lsu h = new lsu(); final lsu i = new lsu(); final lsu j = new lsu(); int k = -1; int l = -1; public int m; public int n; public float o; public boolean p; final Rect q = new Rect(); lst r; public int s; public int t; View u; private iax v; private int w; private int x; private int y; private boolean z; public lsr(View paramView) { Rect[] arrayOfRect = new Rect[2]; arrayOfRect[0] = new Rect(); arrayOfRect[1] = new Rect(); this.D = arrayOfRect; this.u = paramView; this.r = new lst(this); this.r.setName("TileDecoder"); this.r.start(); } public static int a(Context paramContext) { DisplayMetrics localDisplayMetrics = new DisplayMetrics(); ((WindowManager)paramContext.getSystemService("window")).getDefaultDisplay().getMetrics(localDisplayMetrics); if ((localDisplayMetrics.heightPixels > 2048) || (localDisplayMetrics.widthPixels > 2048)) {} for (int i1 = 1; i1 != 0; i1 = 0) { return 512; } return 256; } private final void a(Rect paramRect, int paramInt1, int paramInt2, int paramInt3, float paramFloat, int paramInt4) { double d1 = Math.toRadians(-paramInt4); double d2 = this.s; double d3 = this.t; double d4 = Math.cos(d1); double d5 = Math.sin(d1); int i1 = (int)Math.ceil(Math.max(Math.abs(d4 * d2 - d5 * d3), Math.abs(d4 * d2 + d5 * d3))); int i2 = (int)Math.ceil(Math.max(Math.abs(d5 * d2 + d4 * d3), Math.abs(d5 * d2 - d4 * d3))); int i3 = (int)Math.floor(paramInt1 - i1 / (2.0F * paramFloat)); int i4 = (int)Math.floor(paramInt2 - i2 / (2.0F * paramFloat)); int i5 = (int)Math.ceil(i3 + i1 / paramFloat); int i6 = (int)Math.ceil(i4 + i2 / paramFloat); int i7 = this.b << paramInt3; paramRect.set(Math.max(0, i7 * (i3 / i7)), Math.max(0, i7 * (i4 / i7)), Math.min(this.k, i5), Math.min(this.l, i6)); } private final void a(lss paramlss) { synchronized (this.g) { if (paramlss.o == 1) { paramlss.o = 2; if (this.j.a(paramlss)) { this.g.notifyAll(); } } return; } } private final boolean a(lss paramlss, iaz paramiaz, RectF paramRectF1, RectF paramRectF2) { if (paramlss.j()) { paramiaz.a(paramlss, paramRectF1, paramRectF2); return true; } if (1 + paramlss.l == paramlss.p.d) {} int i2; int i3; for (lss locallss = null; locallss == null; locallss = paramlss.p.a(i2, i3, 1 + paramlss.l)) { return false; int i1 = paramlss.p.b << 1 + paramlss.l; i2 = i1 * (paramlss.j / i1); i3 = i1 * (paramlss.k / i1); } if (paramlss.j == locallss.j) { paramRectF1.left /= 2.0F; paramRectF1.right /= 2.0F; label139: if (paramlss.k != locallss.k) { break label212; } paramRectF1.top /= 2.0F; } for (paramRectF1.bottom /= 2.0F;; paramRectF1.bottom = ((this.b + paramRectF1.bottom) / 2.0F)) { paramlss = locallss; break; paramRectF1.left = ((this.b + paramRectF1.left) / 2.0F); paramRectF1.right = ((this.b + paramRectF1.right) / 2.0F); break label139; label212: paramRectF1.top = ((this.b + paramRectF1.top) / 2.0F); } } private final lss b(int paramInt1, int paramInt2, int paramInt3) { synchronized (this.g) { lss locallss1 = this.h.a(); if (locallss1 != null) { locallss1.o = 1; locallss1.j = paramInt1; locallss1.k = paramInt2; locallss1.l = paramInt3; if (locallss1.i != null) { locallss1.i(); } locallss1.h = false; locallss1.c = -1; locallss1.d = -1; return locallss1; } lss locallss2 = new lss(this, paramInt1, paramInt2, paramInt3); return locallss2; } } private final void b() { synchronized (this.g) { this.j.a = null; this.i.a = null; kp localkp = this.f; if (localkp.b) { localkp.a(); } int i1 = localkp.e; for (int i2 = 0; i2 < i1; i2++) { b((lss)this.f.b(i2)); } this.f.c(); return; } } private final void b(lss paramlss) { synchronized (this.g) { if (paramlss.o == 4) { paramlss.o = 32; return; } paramlss.o = 64; if (paramlss.n != null) { a.a(paramlss.n); paramlss.n = null; } this.h.a(paramlss); return; } } private static long c(int paramInt1, int paramInt2, int paramInt3) { return (paramInt1 << 16 | paramInt2) << 16 | paramInt3; } private final void c() { this.E = true; kp localkp = this.f; if (localkp.b) { localkp.a(); } int i1 = localkp.e; for (int i2 = 0; i2 < i1; i2++) { lss locallss = (lss)this.f.b(i2); if (!locallss.j()) { a(locallss); } } } final lss a(int paramInt1, int paramInt2, int paramInt3) { return (lss)this.f.a(c(paramInt1, paramInt2, paramInt3)); } public final void a() { this.p = true; this.r.interrupt(); synchronized (this.g) { this.i.a = null; this.j.a = null; for (lss locallss = this.h.a(); locallss != null; locallss = this.h.a()) { locallss.g(); } kp localkp = this.f; if (localkp.b) { localkp.a(); } int i1 = localkp.e; int i2 = 0; if (i2 < i1) { ((lss)this.f.b(i2)).g(); i2++; } } this.f.c(); this.q.set(0, 0, 0, 0); while (a.a() != null) {} } public final void a(lsv paramlsv, int paramInt) { if (this.c != paramlsv) { this.c = paramlsv; b(); if (this.c != null) { break label68; } this.k = 0; this.l = 0; this.d = 0; this.v = null; } for (;;) { this.p = true; if (this.C != paramInt) { this.C = paramInt; this.p = true; } return; label68: this.k = this.c.b(); this.l = this.c.c(); this.v = this.c.d(); this.b = this.c.a(); if (this.v != null) { this.d = Math.max(0, iaw.a(this.k / this.v.b())); } else { int i1 = Math.max(this.k, this.l); int i2 = this.b; for (int i3 = 1; i2 < i1; i3++) { i2 <<= 1; } this.d = i3; } } } public final boolean a(iaz paramiaz) { int i1; lss locallss1; if ((this.s == 0) || (this.t == 0) || (!this.p)) { i1 = 1; locallss1 = null; } int i18; int i19; for (;;) { for (;;) { if (i1 <= 0) { break label837; } synchronized (this.g) { locallss1 = this.i.a(); if (locallss1 == null) { break label837; } if (!locallss1.j()) { if (locallss1.o == 8) { locallss1.b(paramiaz); i1--; continue; this.p = false; this.e = iaw.a(iaw.b(1.0F / this.o), 0, this.d); int i14; if (this.e != this.d) { Rect localRect4 = this.q; a(localRect4, this.m, this.n, this.e, this.o, this.C); this.w = Math.round(this.s / 2.0F + (localRect4.left - this.m) * this.o); this.x = Math.round(this.t / 2.0F + (localRect4.top - this.n) * this.o); if (this.o * (1 << this.e) > 0.75F) { i14 = -1 + this.e; } } int i15; int i16; Rect[] arrayOfRect; for (;;) { i15 = Math.max(0, Math.min(i14, -2 + this.d)); i16 = Math.min(i15 + 2, this.d); arrayOfRect = this.D; for (int i17 = i15; i17 < i16; i17++) { Rect localRect3 = arrayOfRect[(i17 - i15)]; int i32 = this.m; int i33 = this.n; int i34 = this.C; a(localRect3, i32, i33, i17, Math.scalb(1.0F, -(i17 + 1)), i34); } i14 = this.e; continue; i14 = -2 + this.e; this.w = Math.round(this.s / 2.0F - this.m * this.o); this.x = Math.round(this.t / 2.0F - this.n * this.o); } if (this.C % 90 != 0) { break; } for (;;) { int i24; int i25; int i28; int i31; long l1; synchronized (this.g) { this.j.a = null; this.i.a = null; this.E = false; kp localkp1 = this.f; if (localkp1.b) { localkp1.a(); } i18 = localkp1.e; i19 = 0; if (i19 < i18) { lss locallss3 = (lss)this.f.b(i19); int i20 = locallss3.l; if ((i20 >= i15) && (i20 < i16) && (arrayOfRect[(i20 - i15)].contains(locallss3.j, locallss3.k))) { break label1433; } kp localkp2 = this.f; if (localkp2.d[i19] != kp.a) { localkp2.d[i19] = kp.a; localkp2.b = true; } i19--; i18--; b(locallss3); break label1433; } i24 = i15; if (i24 >= i16) { break; } i25 = this.b << i24; Rect localRect2 = arrayOfRect[(i24 - i15)]; int i26 = localRect2.top; int i27 = localRect2.bottom; i28 = i26; if (i28 >= i27) { break label783; } int i29 = localRect2.left; int i30 = localRect2.right; i31 = i29; if (i31 >= i30) { break label773; } l1 = c(i31, i28, i24); lss locallss4 = (lss)this.f.a(l1); if (locallss4 != null) { if (locallss4.o == 2) { locallss4.o = 1; } i31 += i25; } } lss locallss5 = b(i31, i28, i24); this.f.a(l1, locallss5); continue; label773: i28 += i25; continue; label783: i24++; } this.u.postInvalidate(); } } } } int i13 = locallss1.o; new StringBuilder(51).append("Tile in upload queue has invalid state: ").append(i13); } label837: if (locallss1 != null) { this.u.postInvalidate(); } this.y = 1; this.z = true; int i2 = this.e; int i3 = this.C; int i4; if (i3 != 0) { i4 = 2; label878: if (i4 != 0) { paramiaz.a(2); if (i3 != 0) { int i11 = this.s / 2; int i12 = this.t / 2; paramiaz.a(i11, i12); paramiaz.a(i3, 0.0F, 0.0F, 1.0F); paramiaz.a(-i11, -i12); } } } for (;;) { int i5; int i6; int i7; int i8; int i9; lss locallss2; try { if (i2 == this.d) { break label1319; } i5 = this.b << i2; float f1 = i5 * this.o; Rect localRect1 = this.q; i6 = localRect1.top; i7 = 0; if (i6 >= localRect1.bottom) { break label1370; } float f2 = this.x + f1 * i7; i8 = localRect1.left; i9 = 0; if (i8 >= localRect1.right) { break label1471; } float f3 = this.w + f1 * i9; RectF localRectF1 = this.A; RectF localRectF2 = this.B; localRectF2.set(f3, f2, f3 + f1, f2 + f1); localRectF1.set(0.0F, 0.0F, this.b, this.b); locallss2 = a(i8, i6, i2); if (locallss2 != null) { if (!locallss2.j()) { if (locallss2.o != 8) { break label1295; } if (this.y > 0) { this.y = (-1 + this.y); locallss2.b(paramiaz); } } else { if (a(locallss2, paramiaz, localRectF1, localRectF2)) { break label1458; } } } else { if (this.v == null) { break label1458; } int i10 = this.b << i2; float f4 = this.v.b() / this.k; float f5 = this.v.c() / this.l; localRectF1.set(f4 * i8, f5 * i6, f4 * (i8 + i10), f5 * (i10 + i6)); paramiaz.a(this.v, localRectF1, localRectF2); break label1458; } this.z = false; continue; if (locallss2.o == 16) { continue; } } finally { if (i4 != 0) { paramiaz.b(); } } label1295: this.z = false; a(locallss2); continue; label1319: if (this.v != null) { paramiaz.a(this.v, this.w, this.x, Math.round(this.k * this.o), Math.round(this.l * this.o)); } label1370: if (i4 != 0) { paramiaz.b(); } if (this.z) { if (!this.E) { c(); } } while ((this.z) || (this.v != null)) { return true; this.u.postInvalidate(); } return false; i4 = 0; break label878; label1433: int i21 = i19; int i22 = i18; int i23 = i21 + 1; i18 = i22; i19 = i23; break; label1458: i8 += i5; i9++; continue; label1471: i6 += i5; i7++; } } } /* Location: F:\apktool\apktool\com.google.android.apps.plus\classes-dex2jar.jar * Qualified Name: lsr * JD-Core Version: 0.7.0.1 */
ChiangC/FMTech
GooglePlus/app/src/main/java/lsr.java
Java
apache-2.0
15,760
package middleware import ( "encoding/base64" "strconv" "strings" "github.com/raintank/raintank-apps/pkg/auth" "gopkg.in/macaron.v1" ) type Context struct { *macaron.Context *auth.SignedInUser ApiKey string } func GetContextHandler() macaron.Handler { return func(c *macaron.Context) { ctx := &Context{ Context: c, SignedInUser: &auth.SignedInUser{}, } c.Map(ctx) } } func RequireAdmin() macaron.Handler { return func(ctx *Context) { if !ctx.IsAdmin { ctx.JSON(403, "Permission denied") } } } func RoleAuth(roles ...auth.RoleType) macaron.Handler { return func(c *Context) { ok := false for _, role := range roles { if role == c.Role { ok = true break } } if !ok { c.JSON(403, "Permission denied") } } } func Auth(adminKey string) macaron.Handler { return func(ctx *Context) { key, err := getApiKey(ctx) if err != nil { ctx.JSON(401, "Invalid Authentication header.") return } if key == "" { ctx.JSON(401, "Unauthorized") return } user, err := auth.Auth(adminKey, key) if err != nil { if err == auth.ErrInvalidApiKey { ctx.JSON(401, "Unauthorized") return } ctx.JSON(500, err) return } // allow admin users to impersonate other orgs. if user.IsAdmin { header := ctx.Req.Header.Get("X-Worldping-Org") if header != "" { orgId, err := strconv.ParseInt(header, 10, 64) if err == nil && orgId != 0 { user.OrgId = orgId } } } ctx.SignedInUser = user ctx.ApiKey = key } } func getApiKey(c *Context) (string, error) { header := c.Req.Header.Get("Authorization") parts := strings.SplitN(header, " ", 2) if len(parts) == 2 && parts[0] == "Bearer" { key := parts[1] return key, nil } if len(parts) == 2 && parts[0] == "Basic" { decoded, err := base64.StdEncoding.DecodeString(parts[1]) if err != nil { return "", err } userAndPass := strings.SplitN(string(decoded), ":", 2) if userAndPass[0] == "api_key" { return userAndPass[1], nil } } return "", nil }
raintank/raintank-apps
vendor/github.com/raintank/worldping-api/pkg/middleware/middleware.go
GO
apache-2.0
2,035
import { Component } from '@angular/core'; import { NavController } from 'ionic-angular'; import { HttpModule } from '@angular/http'; import { RecipeServiceProvider } from '../../providers/recipe/recipe.service'; import { Recipe } from '../../providers/recipe/recipe.model'; import { RecipeDetailPage } from '../recipe-detail/recipe-detail'; import { UtilityProvider } from '../../providers/utility/utility'; @Component({ selector: 'page-home', templateUrl: 'home.html', providers: [HttpModule, RecipeServiceProvider,UtilityProvider] }) export class HomePage { recipeList: Recipe[]; recipe: any; constructor(public navCtrl: NavController, public recipeService: RecipeServiceProvider) { this.loadRecipes(); } loadRecipes() { this.recipeService.loadRecipes().subscribe(recipe => this.recipeList = recipe); } viewItem(recipe: any) { this.recipe = recipe; console.log(this.recipe); this.navCtrl.push(RecipeDetailPage, { recipe: recipe }); } filterTime(seconds:string){ return UtilityProvider.filterTime(seconds); } }
gokhankuyucak/AeropressApp
src/pages/home/home.ts
TypeScript
apache-2.0
1,064
package com.google.api.ads.dfp.jaxws.v201511; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * * Action that can be performed on {@link FirstPartyAudienceSegment} objects to deactivate them. * * * <p>Java class for DeactivateAudienceSegments complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="DeactivateAudienceSegments"> * &lt;complexContent> * &lt;extension base="{https://www.google.com/apis/ads/publisher/v201511}AudienceSegmentAction"> * &lt;sequence> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "DeactivateAudienceSegments") public class DeactivateAudienceSegments extends AudienceSegmentAction { }
gawkermedia/googleads-java-lib
modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201511/DeactivateAudienceSegments.java
Java
apache-2.0
984
/* * * Copyright 2017-2018 Nitrite 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.dizitart.no2.objects.data; import lombok.Data; import org.dizitart.no2.IndexType; import org.dizitart.no2.objects.Id; import org.dizitart.no2.objects.Index; import org.dizitart.no2.objects.Indices; import java.util.Date; import java.util.UUID; /** * @author Anindya Chatterjee */ @Data @Indices({ @Index(value = "name", type = IndexType.Fulltext) }) public class PersonEntity { @Id private String uuid; private String name; private String status; private PersonEntity friend; private Date dateCreated; public PersonEntity() { this.uuid = UUID.randomUUID().toString(); this.dateCreated = new Date(); } public PersonEntity(String name) { this.uuid = UUID.randomUUID().toString(); this.name = name; this.dateCreated = new Date(); } }
dizitart/nitrite-database
nitrite/src/test/java/org/dizitart/no2/objects/data/PersonEntity.java
Java
apache-2.0
1,463
package org.devel.reportfx; import de.saxsys.mvvmfx.FluentViewLoader; import javafx.application.Application; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; import de.saxsys.mvvmfx.ViewTuple; public class Starter extends Application { public static void main(String... args) { Application.launch(args); } @Override public void start(Stage stage) throws Exception { stage.setTitle("ReportFX"); ViewTuple<MainView, MainViewModel> viewTuple = FluentViewLoader.fxmlView(MainView.class).load(); Parent root = viewTuple.getView(); Scene scene = new Scene(root); stage.setScene(scene); stage.show(); stage.setResizable(false); } }
stefanil/ReportFX
client/src/main/java/org/devel/reportfx/Starter.java
Java
apache-2.0
695
// Copyright 2011, 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 v201109; import com.google.api.adwords.lib.AdWordsService; import com.google.api.adwords.lib.AdWordsServiceLogger; import com.google.api.adwords.lib.AdWordsUser; import com.google.api.adwords.v201109.cm.Media; import com.google.api.adwords.v201109.cm.MediaPage; import com.google.api.adwords.v201109.cm.MediaServiceInterface; import com.google.api.adwords.v201109.cm.OrderBy; import com.google.api.adwords.v201109.cm.Predicate; import com.google.api.adwords.v201109.cm.PredicateOperator; import com.google.api.adwords.v201109.cm.Selector; import com.google.api.adwords.v201109.cm.SortOrder; /** * This example gets all videos. To upload a video, see * http://adwords.google.com/support/aw/bin/answer.py?hl=en&answer=39454. * * Tags: MediaService.get * * @category adx-exclude * @author api.arogal@gmail (Adam Rogal) */ public class GetAllVideos { public static void main(String[] args) { try { // Log SOAP XML request and response. AdWordsServiceLogger.log(); // Get AdWordsUser from "~/adwords.properties". AdWordsUser user = new AdWordsUser(); // Get the MediaService. MediaServiceInterface mediaService = user.getService(AdWordsService.V201109.MEDIA_SERVICE); // Create selector. Selector selector = new Selector(); selector.setFields(new String[] {"MediaId", "Name"}); selector.setOrdering(new OrderBy[] {new OrderBy("MediaId", SortOrder.ASCENDING)}); // Create predicates. Predicate typePredicate = new Predicate("Type", PredicateOperator.IN, new String[] {"VIDEO"}); selector.setPredicates(new Predicate[] {typePredicate}); // Get all videos. MediaPage page = mediaService.get(selector); // Display videos. if (page.getEntries() != null) { for (Media video : page.getEntries()) { System.out.println("Video with id '" + video.getMediaId() + "' and name '" + video.getName() + "' was found."); } } else { System.out.println("No videos were found."); } } catch (Exception e) { e.printStackTrace(); } } }
cmmanish/OldUITempTest
examples/v201109/GetAllVideos.java
Java
apache-2.0
2,746
package com.nitorcreations.willow.auth; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Collections.singletonMap; import static java.util.Collections.unmodifiableSet; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.inject.Inject; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.SimpleAccount; import org.apache.shiro.authz.Permission; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.google.common.collect.ImmutableMap; import mx.com.inftel.shiro.oauth2.AbstractOAuth2AuthenticatingFilter; public class GitHubOAuthAuthenticatingFilter extends AbstractOAuth2AuthenticatingFilter { private static final String SCOPE = "user:email,read:org"; private final Map<String,? extends Permission> PERMISSIONS; private final GitHubOAuthAccounts accounts; @Inject public GitHubOAuthAuthenticatingFilter(GitHubOAuthConfig config, GitHubOAuthAccounts accounts) throws IOException { setRedirectUri(config.getRedirectUri()); setClientId(config.getClientId()); setClientSecret(config.getClientSecret()); setLoginUrl("/"); this.accounts = accounts; PERMISSIONS = ImmutableMap.of( config.getOrganization() + "." + config.getAdminTeam(), Permissions.ADMIN, config.getOrganization(), Permissions.MONITOR); } @Override public String getName() { return getClass().getName(); } @Override protected String getAuthorizeURL(ServletRequest request, ServletResponse response) throws Exception { return makeStandardAuthorizeURL(request, response, "https://github.com/login/oauth/authorize", SCOPE); } @Override protected JSONObject getOAuth2Principal(ServletRequest request, ServletResponse response) throws Exception { String tokenResponse = httpPost("https://github.com/login/oauth/access_token", "client_id=" + getClientId() + "&client_secret=" + getClientSecret() + "&redirect_uri=" + encodeURL(getRedirectUri()) + "&code=" + encodeURL(request.getParameter("code"))); String token = getAccessToken(tokenResponse); Map<String,String> headers = singletonMap("Authorization", "token " + token); JSONArray memberOf = JSONTool.toArray(getOrganizations(headers), getTeams(headers)); String loginId = new JSONObject(httpGet("https://api.github.com/user", headers)).getString("login"); JSONObject ret = new JSONObject() .put("login", loginId) .put("member_of", memberOf) .put("token", token); SimpleAccount acco = doGetAuthenticationInfo(ret); accounts.add(acco); return ret; } @Override protected String getOAuth2Credentials(JSONObject principal) throws Exception { return principal.getString("login"); } private String getAccessToken(String response) throws Exception { for(String param : response.split("&")) { if(param.startsWith("access_token=")) { return decodeURL(param.substring(param.indexOf('=') + 1)); } } throw new IllegalStateException("access_token param not sent by idp"); } private List<String> getOrganizations(Map<String,String> headers) throws Exception { JSONArray organizations = new JSONArray(httpGet("https://api.github.com/user/orgs", headers)); List<String> names = new ArrayList<>(); for(int i = 0; i < organizations.length(); i++) { names.add(organizations.getJSONObject(i).getString("login")); } return Collections.unmodifiableList(names); } private List<String> getTeams(Map<String,String> headers) throws Exception { JSONArray teams = new JSONArray(httpGet("https://api.github.com/user/teams", headers)); List<String> names = new ArrayList<>(); for(int i = 0; i < teams.length(); i++) { JSONObject team = teams.getJSONObject(i); names.add(team.getJSONObject("organization").getString("login") + "." + team.getString("name")); } return Collections.unmodifiableList(names); } private String httpGet(String url, Map<String, String> headers) throws Exception { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setDoOutput(true); for(Map.Entry<String,String> header : headers.entrySet()) { conn.setRequestProperty(header.getKey(), header.getValue()); } return readResponseBody(conn); } private String httpPost(String url, String data) throws Exception { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setDoOutput(true); try(OutputStream out = conn.getOutputStream()) { out.write(data.getBytes(UTF_8)); } return readResponseBody(conn); } @SuppressFBWarnings(value={"RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", "RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE"}, justification="null check in try-with-resources magic bytecode") private String readResponseBody(HttpURLConnection conn) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[4096]; try(InputStream in = conn.getResponseCode() == 200 ? conn.getInputStream() : conn.getErrorStream()) { for(int i = in.read(buf); i != -1; i = in.read(buf)) { baos.write(buf, 0, i); } } String body = new String(baos.toByteArray(), UTF_8); if(conn.getResponseCode() != 200) { throw new IllegalStateException(String.format("idp responded with HTTP %s %s: %s", conn.getResponseCode(), conn.getResponseMessage(), body)); } return body; } public SimpleAccount doGetAuthenticationInfo(JSONObject user) throws AuthenticationException { try { String userId = user.getString("login"); Set<String> memberOf = JSONTool.toStringSet(user.getJSONArray("member_of")); return new SimpleAccount(userId, userId, getName(), memberOf, memberShipsToPermissions(memberOf)); } catch (JSONException e) { throw new AuthenticationException(e); } } protected Set<Permission> memberShipsToPermissions(Set<String> organizations) { Set<Permission> permissions = new HashSet<>(); for(String team : organizations) { Permission permission = PERMISSIONS.get(team); if(permission != null) { permissions.add(permission); } } return unmodifiableSet(permissions); } }
NitorCreations/willow
willow-servers/src/main/java/com/nitorcreations/willow/auth/GitHubOAuthAuthenticatingFilter.java
Java
apache-2.0
6,779
/* First created by JCasGen Sat Apr 11 19:49:33 EDT 2015 */ package edu.cmu.lti.oaqa.type.answer; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.JCasRegistry; import org.apache.uima.cas.impl.CASImpl; import org.apache.uima.cas.impl.FSGenerator; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.cas.impl.TypeImpl; import org.apache.uima.cas.Type; import org.apache.uima.cas.impl.FeatureImpl; import org.apache.uima.cas.Feature; import org.apache.uima.jcas.tcas.Annotation_Type; /** A Named Entity type that represents the type of the answer being sought. * Updated by JCasGen Sun Apr 19 19:46:49 EDT 2015 * @generated */ public class AnswerType_Type extends Annotation_Type { /** @generated * @return the generator for this type */ @Override protected FSGenerator getFSGenerator() {return fsGenerator;} /** @generated */ private final FSGenerator fsGenerator = new FSGenerator() { public FeatureStructure createFS(int addr, CASImpl cas) { if (AnswerType_Type.this.useExistingInstance) { // Return eq fs instance if already created FeatureStructure fs = AnswerType_Type.this.jcas.getJfsFromCaddr(addr); if (null == fs) { fs = new AnswerType(addr, AnswerType_Type.this); AnswerType_Type.this.jcas.putJfsFromCaddr(addr, fs); return fs; } return fs; } else return new AnswerType(addr, AnswerType_Type.this); } }; /** @generated */ @SuppressWarnings ("hiding") public final static int typeIndexID = AnswerType.typeIndexID; /** @generated @modifiable */ @SuppressWarnings ("hiding") public final static boolean featOkTst = JCasRegistry.getFeatOkTst("edu.cmu.lti.oaqa.type.answer.AnswerType"); /** @generated */ final Feature casFeat_label; /** @generated */ final int casFeatCode_label; /** @generated * @param addr low level Feature Structure reference * @return the feature value */ public String getLabel(int addr) { if (featOkTst && casFeat_label == null) jcas.throwFeatMissing("label", "edu.cmu.lti.oaqa.type.answer.AnswerType"); return ll_cas.ll_getStringValue(addr, casFeatCode_label); } /** @generated * @param addr low level Feature Structure reference * @param v value to set */ public void setLabel(int addr, String v) { if (featOkTst && casFeat_label == null) jcas.throwFeatMissing("label", "edu.cmu.lti.oaqa.type.answer.AnswerType"); ll_cas.ll_setStringValue(addr, casFeatCode_label, v);} /** @generated */ final Feature casFeat_targetType; /** @generated */ final int casFeatCode_targetType; /** @generated * @param addr low level Feature Structure reference * @return the feature value */ public int getTargetType(int addr) { if (featOkTst && casFeat_targetType == null) jcas.throwFeatMissing("targetType", "edu.cmu.lti.oaqa.type.answer.AnswerType"); return ll_cas.ll_getRefValue(addr, casFeatCode_targetType); } /** @generated * @param addr low level Feature Structure reference * @param v value to set */ public void setTargetType(int addr, int v) { if (featOkTst && casFeat_targetType == null) jcas.throwFeatMissing("targetType", "edu.cmu.lti.oaqa.type.answer.AnswerType"); ll_cas.ll_setRefValue(addr, casFeatCode_targetType, v);} /** initialize variables to correspond with Cas Type and Features * @generated * @param jcas JCas * @param casType Type */ public AnswerType_Type(JCas jcas, Type casType) { super(jcas, casType); casImpl.getFSClassRegistry().addGeneratorForType((TypeImpl)this.casType, getFSGenerator()); casFeat_label = jcas.getRequiredFeatureDE(casType, "label", "uima.cas.String", featOkTst); casFeatCode_label = (null == casFeat_label) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_label).getCode(); casFeat_targetType = jcas.getRequiredFeatureDE(casType, "targetType", "uima.tcas.Annotation", featOkTst); casFeatCode_targetType = (null == casFeat_targetType) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_targetType).getCode(); } }
oaqa/baseqa
src/main/java/edu/cmu/lti/oaqa/type/answer/AnswerType_Type.java
Java
apache-2.0
4,196
""" Simple demo of a scatter plot. """ import numpy as np import matplotlib.pyplot as plt N = 50 x = np.random.rand(N) y = np.random.rand(N) colors = np.random.rand(N) area = np.pi * (15 * np.random.rand(N))**2 # 0 to 15 point radii plt.scatter(x, y, s=area, c=colors, alpha=0.5) plt.show()
ArmstrongYang/StudyShare
Python-matplotlib/scatter_demo.py
Python
apache-2.0
295
package com.planet_ink.coffee_mud.Abilities.Traps; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2003-2016 Bo Zimmerman 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. */ public class Trap_CaveIn extends StdTrap { @Override public String ID() { return "Trap_CaveIn"; } private final static String localizedName = CMLib.lang().L("cave-in"); @Override public String name() { return localizedName; } @Override protected int canAffectCode() { return Ability.CAN_ROOMS; } @Override protected int canTargetCode() { return 0; } @Override protected int trapLevel() { return 22; } @Override public String requiresToSet() { return "100 pounds of wood"; } @Override public int baseRejuvTime(int level) { return 6; } @Override public List<Item> getTrapComponents() { final List<Item> V=new Vector<Item>(); for(int i=0;i<100;i++) V.add(CMLib.materials().makeItemResource(RawMaterial.RESOURCE_WOOD)); return V; } @Override public Trap setTrap(MOB mob, Physical P, int trapBonus, int qualifyingClassLevel, boolean perm) { if(P==null) return null; if(mob!=null) { final Item I=findMostOfMaterial(mob.location(),RawMaterial.MATERIAL_WOODEN); if(I!=null) super.destroyResources(mob.location(),I.material(),100); } return super.setTrap(mob,P,trapBonus,qualifyingClassLevel,perm); } @Override public boolean canSetTrapOn(MOB mob, Physical P) { if(!super.canSetTrapOn(mob,P)) return false; if(mob!=null) { final Item I=findMostOfMaterial(mob.location(),RawMaterial.MATERIAL_WOODEN); if((I==null) ||(super.findNumberOfResource(mob.location(),I.material())<100)) { mob.tell(L("You'll need to set down at least 100 pounds of wood first.")); return false; } } if(P instanceof Room) { final Room R=(Room)P; if(R.domainType()!=Room.DOMAIN_INDOORS_CAVE) { if(mob!=null) mob.tell(L("You can only set this trap in caves.")); return false; } } return true; } @Override public boolean okMessage(final Environmental myHost, final CMMsg msg) { if((sprung) &&(affected!=null) &&(!disabled()) &&(tickDown>=0)) { if(((msg.targetMinor()==CMMsg.TYP_LEAVE) ||(msg.targetMinor()==CMMsg.TYP_ENTER) ||(msg.targetMinor()==CMMsg.TYP_FLEE)) &&(msg.amITarget(affected))) { msg.source().tell(L("The cave-in prevents entry or exit from here.")); return false; } } return super.okMessage(myHost,msg); } @Override public void spring(MOB target) { if((target!=invoker())&&(target.location()!=null)) { if((doesSaveVsTraps(target)) ||(invoker().getGroupMembers(new HashSet<MOB>()).contains(target))) target.location().show(target,null,null,CMMsg.MASK_ALWAYS|CMMsg.MSG_NOISE,L("<S-NAME> avoid(s) setting off a cave-in!")); else if(target.location().show(target,target,this,CMMsg.MASK_ALWAYS|CMMsg.MSG_NOISE,L("<S-NAME> trigger(s) a cave-in!"))) { super.spring(target); if((affected!=null) &&(affected instanceof Room)) { final Room R=(Room)affected; for(int i=0;i<R.numInhabitants();i++) { final MOB M=R.fetchInhabitant(i); if((M!=null)&&(M!=invoker())) if(invoker().mayIFight(M)) { final int damage=CMLib.dice().roll(trapLevel()+abilityCode(),20,1); CMLib.combat().postDamage(invoker(),M,this,damage,CMMsg.MASK_MALICIOUS|CMMsg.MASK_ALWAYS|CMMsg.TYP_JUSTICE,Weapon.TYPE_BASHING,L("The cave-in <DAMAGE> <T-NAME>!")); } } } } } } }
oriontribunal/CoffeeMud
com/planet_ink/coffee_mud/Abilities/Traps/Trap_CaveIn.java
Java
apache-2.0
4,993
/* * Copyright 2018 Mirko Sertic * * 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 de.mirkosertic.bytecoder.backend.wasm.ast; import de.mirkosertic.bytecoder.ssa.Expression; public class I32Or extends BinaryExpression { I32Or(final WASMValue left, final WASMValue right, final Expression expression) { super(left, right,"i32.or", (byte) 0x72, expression); } }
mirkosertic/Bytecoder
core/src/main/java/de/mirkosertic/bytecoder/backend/wasm/ast/I32Or.java
Java
apache-2.0
902
package com.coolweather.android.gson; /** * Created by LanQ on 2017/8/21 0021. */ public class AQI { public AQICity city; public class AQICity{ public String aqi; public String pm25; } }
lq2677/myweather
app/src/main/java/com/coolweather/android/gson/AQI.java
Java
apache-2.0
223
/** * Copyright (C) 2016 - 2030 youtongluan. * * 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.yx.validate; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.yx.annotation.spec.ParamSpec; import org.yx.annotation.spec.Specs; import org.yx.util.CollectionUtil; public final class FieldParameterHolder { private static final ConcurrentMap<Class<?>, List<FieldParameterInfo>> map = new ConcurrentHashMap<>(); public static void put(Class<?> clz, List<FieldParameterInfo> infos) { if (clz == null || infos == null || infos.isEmpty()) { return; } map.put(clz, infos); } public static Set<Class<?>> keys() { return new HashSet<>(map.keySet()); } public static List<FieldParameterInfo> get(Class<?> clz) { return map.get(clz); } public static Map<Field, FieldParameterInfo> getFieldParameterMap(Class<?> clz) { List<FieldParameterInfo> infos = get(clz); if (infos == null) { return Collections.emptyMap(); } Map<Field, FieldParameterInfo> infoMap = new HashMap<>(); for (FieldParameterInfo info : infos) { infoMap.put(info.getField(), info); } return infoMap; } public static void registerFieldInfo(final Class<?> clazz) { if (clazz.isArray()) { registerFieldInfo(clazz.getComponentType()); return; } if (!Validators.supportComplex(clazz)) { return; } if (get(clazz) != null) { return; } List<FieldParameterInfo> list = new ArrayList<>(); Class<?> tempClz = clazz; while (tempClz != null && !tempClz.getName().startsWith("java.")) { Field[] fs = tempClz.getDeclaredFields(); for (Field f : fs) { if (Modifier.isStatic(f.getModifiers())) { continue; } ParamSpec p = Specs.extractParamField(f); if (p == null) { continue; } FieldParameterInfo info = new FieldParameterInfo(p, f); if (!info.maybeCheck()) { continue; } list.add(info); if (info.isComplex()) { registerFieldInfo(info.getParamType()); } } tempClz = tempClz.getSuperclass(); } if (list.size() > 0) { put(clazz, CollectionUtil.unmodifyList(list.toArray(new FieldParameterInfo[list.size()]))); } } }
youtongluan/sumk
src/main/java/org/yx/validate/FieldParameterHolder.java
Java
apache-2.0
2,939
package eu.ensure.ppe; import org.gautelis.vopn.lang.Number; import org.gautelis.vopn.statistics.MovingAverage; import eu.ensure.ppe.model.Consequence; import java.util.Collection; import java.util.LinkedList; public class AggregationLevelScore { public static final double FAILURE_SCORE = 0.0; final String id; // Id of aggregation final String name; final double score; final double stdDev; final double cv; final long datasetSize; final Collection<String> storyLine; final Collection<Consequence> consequences; AggregationLevelScore(String aggrId, String aggrName, MovingAverage stats, Collection<String> storyLine, Collection<Consequence> consequences) { this.id = aggrId; this.name = aggrName; this.storyLine = storyLine; if (null == consequences) { this.consequences = new LinkedList<Consequence>(); } else { this.consequences = consequences; } // this.score = Number.roundTwoDecimals(stats.getAverage()); this.stdDev = Number.roundTwoDecimals(stats.getStdDev()); this.cv = Number.roundTwoDecimals(stats.getCV()); this.datasetSize = stats.getCount(); } public String getId() { return id; } public String getName() { return name; } public double getScore() { return score; } public double getStdDev() { return stdDev; } public double getCV() { return cv; } public long getDatasetSize() { return datasetSize; } public Collection<String> getStoryLine() { return storyLine; } public Collection<Consequence> getConsequences() { return consequences; } }
FrodeRanders/ensure
ppe/src/main/java/eu/ensure/ppe/AggregationLevelScore.java
Java
apache-2.0
1,778
/* * 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.iot1clickprojects.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iot1click-projects-2018-05-14/DescribePlacement" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DescribePlacementRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The name of the placement within a project. * </p> */ private String placementName; /** * <p> * The project containing the placement to be described. * </p> */ private String projectName; /** * <p> * The name of the placement within a project. * </p> * * @param placementName * The name of the placement within a project. */ public void setPlacementName(String placementName) { this.placementName = placementName; } /** * <p> * The name of the placement within a project. * </p> * * @return The name of the placement within a project. */ public String getPlacementName() { return this.placementName; } /** * <p> * The name of the placement within a project. * </p> * * @param placementName * The name of the placement within a project. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribePlacementRequest withPlacementName(String placementName) { setPlacementName(placementName); return this; } /** * <p> * The project containing the placement to be described. * </p> * * @param projectName * The project containing the placement to be described. */ public void setProjectName(String projectName) { this.projectName = projectName; } /** * <p> * The project containing the placement to be described. * </p> * * @return The project containing the placement to be described. */ public String getProjectName() { return this.projectName; } /** * <p> * The project containing the placement to be described. * </p> * * @param projectName * The project containing the placement to be described. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribePlacementRequest withProjectName(String projectName) { setProjectName(projectName); 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 (getPlacementName() != null) sb.append("PlacementName: ").append(getPlacementName()).append(","); if (getProjectName() != null) sb.append("ProjectName: ").append(getProjectName()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DescribePlacementRequest == false) return false; DescribePlacementRequest other = (DescribePlacementRequest) obj; if (other.getPlacementName() == null ^ this.getPlacementName() == null) return false; if (other.getPlacementName() != null && other.getPlacementName().equals(this.getPlacementName()) == false) return false; if (other.getProjectName() == null ^ this.getProjectName() == null) return false; if (other.getProjectName() != null && other.getProjectName().equals(this.getProjectName()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getPlacementName() == null) ? 0 : getPlacementName().hashCode()); hashCode = prime * hashCode + ((getProjectName() == null) ? 0 : getProjectName().hashCode()); return hashCode; } @Override public DescribePlacementRequest clone() { return (DescribePlacementRequest) super.clone(); } }
jentfoo/aws-sdk-java
aws-java-sdk-iot1clickprojects/src/main/java/com/amazonaws/services/iot1clickprojects/model/DescribePlacementRequest.java
Java
apache-2.0
5,307
using System; using System.Collections.Generic; namespace PMS.Data.Models { public partial class Status { public Status() { Issue = new HashSet<Issue>(); } public int Id { get; set; } public string Name { get; set; } public short Priority { get; set; } public ICollection<Issue> Issue { get; set; } } }
ntgnst/ProjectManagementSystem
PMS.Data/Models/Status.cs
C#
apache-2.0
389
/* * Copyright 2009-2015 University of Hildesheim, Software Systems Engineering * * 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 net.ssehub.easy.basics.modelManagement; import java.io.File; import java.net.URI; import java.util.ArrayList; import java.util.List; /** * Stores model information objects of the same version. * * @param <M> the specific type of model * * @author Holger Eichelberger */ public class VersionedModelInfos <M extends IModel> { private Version version; private List<ModelInfo<M>> infos = new ArrayList<ModelInfo<M>>(); /** * Creates a new versioned model information container. * * @param version the version of this container (may be <b>null</b>) */ public VersionedModelInfos(Version version) { this.version = version; } /** * Adds a model information object. * * @param info the object to be added * @throws IllegalArgumentException if the version of <code>info</code> does * not match {@link #version} or the name of <code>info</code> does not match * the name of the first stored model information object (if there is any) */ public void add(ModelInfo<M> info) { assert null != info; if (!Version.equals(info.getVersion(), version)) { throw new IllegalArgumentException("versions do not match"); } if (!infos.isEmpty()) { ModelInfo<M> first = infos.get(0); if (!first.getName().equals(info.getName())) { throw new IllegalArgumentException("names do not match"); } } for (int i = 0; i < infos.size(); i++) { ModelInfo<M> tmp = infos.get(i); if (isSame(tmp.getLocation(), info.getLocation()) && tmp.getLoader() == info.getLoader()) { throw new IllegalArgumentException("URI and loader match"); } } // multiple equal URIs may exist due to different loaders -> any shall be fine infos.add(info); } /** * Checks two URIs for equality. * * @param uri1 the first URI (may be <b>null</b>) * @param uri2 the second URI (may be <b>null</b>) * @return <code>true</code> if both are the same, <code>false</code> else */ public static final boolean isSame(URI uri1, URI uri2) { return (null == uri1 && uri1 == uri2) || (null != uri1 && uri1.equals(uri2)); } /** * Returns the specified model information object. * * @param index the index of the object to be returned * @return the specified object * @throws IndexOutOfBoundsException if <code>index&lt;0 * || index&gt;={@link #size()}</code> */ public ModelInfo<M> get(int index) { return infos.get(index); } /** * Returns the model information objects with <code>model</code> as resolved model. * * @param model the (resolved) model to search for * @return the model information object or <b>null</b> if there is none */ public ModelInfo<M> get(M model) { ModelInfo<M> result = null; int size = infos.size(); for (int i = 0; i < size; i++) { ModelInfo<M> tmp = infos.get(i); if (tmp.getResolved() == model) { result = tmp; } } return result; } /** * Returns the model information objects with <code>uri</code> as location. * * @param uri the URI to search for * @return the model information object or <b>null</b> if there is none */ public ModelInfo<M> get(URI uri) { ModelInfo<M> result = null; int size = infos.size(); for (int i = 0; i < size; i++) { ModelInfo<M> tmp = infos.get(i); if ((null == uri && tmp.getLocation() == uri) || (null != uri && uri.equals(tmp.getLocation()))) { result = tmp; } } return result; } /** * Returns the number of contained version information objects. * * @return the number of version information objects */ public int size() { return infos.size(); } /** * Removes the specified model information object. * @param index the index of the object to be returned * @return the removed object * @throws IndexOutOfBoundsException if <code>index&lt;0 * || index&gt;={@link #size()}</code> */ public ModelInfo<M> remove(int index) { return infos.remove(index); } /** * Removes all stored model information objects. */ public void clear() { infos.clear(); } /** * Removes the specified model information object. * @param info the information object to be removed * @return <code>true</code> if successful <code>false</code> else */ public boolean remove(ModelInfo<M> info) { return infos.remove(info); } /** * Returns the version all information objects in this instance * are assigned to. * * @return the version */ public Version getVersion() { return version; } /** * Returns the model information with the exact match to <code>uri</code>. * * @param uri the URI to match with (may be <b>null</b> then the first * information object is returned) * @return the matching model information (or <b>null</b> if none matches) */ public List<ModelInfo<M>> getByEqualUri(URI uri) { List<ModelInfo<M>> result = null; if (null != uri) { uri = uri.normalize(); int size = infos.size(); for (int i = 0; i < size; i++) { ModelInfo<M> info = infos.get(i); if (null != info.getLocation() && uri.equals(info.getLocation())) { if (null == result) { result = new ArrayList<ModelInfo<M>>(); } result.add(info); } } } return result; } /** * Returns the model information with the closest match * to <code>uri</code>, i.e. in closest in the same hierarchy path. * * @param uri the URI to match with (may be <b>null</b> then the first * information object is returned) * @param modelPath additional URIs prefixes which shall be considered for importing, * similar to the Java classpath, may be <b>null</b> * @return the matching model information (or <b>null</b> if none matches) */ public ModelInfo<M> getByClosestUri(URI uri, List<String> modelPath) { return getByClosestUri(infos, uri, modelPath); } /** * Returns the model information from <code>infos</code> with the closest match * to <code>uri</code>, i.e. in closest in the same hierarchy path. * * @param <M> the model type * @param infos the information objects to be considered * @param uri the URI to match with (may be <b>null</b> then the first * information object is returned) * @param modelPath additional URIs prefixes which shall be considered for importing, * similar to the Java classpath, may be <b>null</b> * @return the matching model information (or <b>null</b> if none matches) */ public static <M extends IModel> ModelInfo<M> getByClosestUri(List<ModelInfo<M>> infos, URI uri, List<String> modelPath) { ModelInfo<M> result = null; int size = infos.size(); if (size > 0) { if (null == uri/* || null == version*/) { result = infos.get(0); } else { // precedence to same file for (int i = 0; null == result && i < size; i++) { ModelInfo<M> info = infos.get(i); if (isSame(uri, info.getLocation())) { result = info; } } // precedence to own hierarchy String searchUriText = pathWithoutLastFragment(uri.normalize()); if (null == result) { // search according to hierarchical IVML convention result = search(infos, searchUriText, modelPath); // this may fail, in particular for parent projects imported according to EASy convention if (null == result) { result = searchOnParentLevel(infos, uri, modelPath); } // search in folders on the same level if (null == result) { result = searchOnSameFolderLevel(infos, uri, modelPath); } } // containment in model path if (null != modelPath) { for (int i = 0; null == result && i < size; i++) { ModelInfo<M> info = infos.get(i); for (int m = 0; null == result && m < modelPath.size(); m++) { if (isMatching(info.getLocation().toString(), modelPath.get(m), false)) { result = info; } } } } } } return result; } /** * Searches for the best match according to the IVML search conventions, first down along the given * URI, then up along the hierarchy. * * @param <M> the model type * @param infos the information objects to be considered * @param searchUriText the search folder URI as text * @param modelPath additional URIs prefixes which shall be considered for importing, * similar to the Java classpath, may be <b>null</b> * @return the matching model information (or <b>null</b> if none matches) */ private static <M extends IModel> ModelInfo<M> search(List<ModelInfo<M>> infos, String searchUriText, List<String> modelPath) { ModelInfo<M> result = null; int matchLength = 0; // 0 == b: down, 1 == b up in URI hierarchy for (int b = 0; null == result && 0 == matchLength && b < 2; b++) { int size = infos.size(); for (int i = 0; i < size; i++) { ModelInfo<M> info = infos.get(i); URI infoUri = info.getLocation(); if (null == infoUri) { continue; } String infoUriText = pathWithoutLastFragment(infoUri); if (isMatching(searchUriText, modelPath, infoUriText, 0 == b)) { // the first match is a candidate boolean isBestMatch = (0 == matchLength); // down, then minimize match length isBestMatch |= (0 == b && infoUriText.length() < matchLength); // up, then maximize match length isBestMatch |= (1 == b && infoUriText.length() > matchLength); if (isBestMatch) { result = infos.get(i); matchLength = infoUriText.length(); } } } } return result; } /** * Searches for the best match within the parent-parent folders of <code>uri</code> if that folder starts with * ".". This enables cross-links among parent models according to the convention EASy places imported IVML files. * * @param <M> the model type * @param infos the information objects to be considered * @param uri the URI to start searching * @param modelPath additional URIs prefixes which shall be considered for importing, * similar to the Java classpath, may be <b>null</b> * @return the matching model information (or <b>null</b> if none matches) */ private static <M extends IModel> ModelInfo<M> searchOnParentLevel(List<ModelInfo<M>> infos, URI uri, List<String> modelPath) { ModelInfo<M> result = null; if (isFileScheme(uri)) { File uriFile = new File(uri); File uriParent = uriFile.getParentFile(); File parent = uriParent; // step two levels up... // uri = EASy/.core/core.ivml; uri-parent = EASy/.core; uri-parent-parent = EASy if (null != parent) { if (parent.getName().startsWith(".")) { // do not consider other parents, EASy-folder not known here! parent = parent.getParentFile(); } else { parent = null; } } if (null != parent) { File[] siblings = parent.listFiles(); if (null != siblings) { for (int s = 0; null == result && s < siblings.length; s++) { File sibling = siblings[s]; if (sibling.isDirectory() && !sibling.equals(uriParent)) { URI siblingUri = sibling.toURI().normalize(); result = search(infos, siblingUri.toString(), modelPath); } } } } } return result; } /** * Search in folders on the level of the parent folder of <code>uri</code>. * * @param <M> the model type * @param infos the information objects to be considered * @param uri the URI to start searching * @param modelPath additional URIs prefixes which shall be considered for importing, * similar to the Java classpath, may be <b>null</b> * @return the matching model information but only if this is unique */ private static <M extends IModel> ModelInfo<M> searchOnSameFolderLevel(List<ModelInfo<M>> infos, URI uri, List<String> modelPath) { ModelInfo<M> result = null; if (isFileScheme(uri)) { List<ModelInfo<M>> tmp = new ArrayList<ModelInfo<M>>(); File uriFile = new File(uri).getParentFile(); File searchFolder = uriFile.getParentFile(); if (null != searchFolder) { File[] files = searchFolder.listFiles(); for (int f = 0; null != files && f < files.length; f++) { File file = files[f]; if (file.isDirectory() && !file.equals(uriFile)) { String searchUriText = file.toURI().normalize().toString(); ModelInfo<M> searchResult = search(infos, searchUriText, modelPath); if (null != searchResult) { tmp.add(searchResult); } } } } if (1 == tmp.size()) { result = tmp.get(0); } // else -> result = null; // if not found or multiple are found } return result; } /** * Returns whether the given URI is a file (file scheme). * * @param uri the URI to test for * @return <code>true</code> if it is a file, <code>false</code> else */ public static boolean isFileScheme(URI uri) { return "file".equals(uri.getScheme()); } /** * Checks whether the <code>searchUriText</code> (with precedence) ore one of the * <code>modelPath</code> URI paths match <code>importUri</code>, i.e. whether * <code>importUri</code> is an appropriate URI for import. * * @param searchUriText the textual URI of the model stating the import * @param modelPath additional URI paths, may be <b>null</b> * @param importUriText the URI path of the model being considered for import * @param contained prefer contained or containing URIs * @return <code>true</code> if the specified data match, <code>false</code> if not */ private static boolean isMatching(String searchUriText, List<String> modelPath, String importUriText, boolean contained) { boolean matches = isMatching(searchUriText, importUriText, contained); if (!matches && null != modelPath) { int size = modelPath.size(); for (int p = 0; !matches && p < size; p++) { matches = isMatching(searchUriText, modelPath.get(p), contained); } } return matches; } /** * Checks whether the <code>searchUriText</code> and <code>importUri</code> match. * * @param searchUriText the textual URI of the model stating the import * @param importUriText the URI path of the model being considered for import * @param contained prefer contained or containing URIs * @return <code>true</code> if the specified data match, <code>false</code> if not */ private static boolean isMatching(String searchUriText, String importUriText, boolean contained) { return contained ? importUriText.startsWith(searchUriText) : searchUriText.startsWith(importUriText); } /** * Returns the prefix path of the given <code>uri</code> without the last fragment. * * @param uri the URI to be considered * @return the prefix path if possible, the <code>uri</code> else */ public static String pathWithoutLastFragment(URI uri) { String uriText = uri.toString(); int pos = uriText.lastIndexOf('/'); if (pos > 0) { uriText = uriText.substring(0, pos + 1); } return uriText; } /** * Adds all model information objects to the given <code>list</code>. * * @param list the list to be modified as a side effect (may be <b>null</b> * then a list is created) * @return <code>list</code> or the created list */ public List<ModelInfo<M>> toList(List<ModelInfo<M>> list) { if (null == list) { list = new ArrayList<ModelInfo<M>>(); } for (int i = 0; i < infos.size(); i++) { list.add(infos.get(i)); } return list; } /** * Returns the textual representation of this instance. * * @return the textual representation */ public String toString() { return version + " " + infos; } /** * Finds a model information object based on a give URI. * * @param uri the URI to find the information object * @return the information object or <b>null</b> if not found */ public ModelInfo<M> find(URI uri) { ModelInfo<M> result = null; if (null != uri) { int size = infos.size(); for (int i = 0; null == result && i < size; i++) { ModelInfo<M> info = infos.get(i); if (uri.equals(info.getLocation())) { result = info; } } } return result; } /** * Retrieves the version model information container with the specified version. * * @param <M> the specific type of model * * @param infos a list of model information containers (may be <b>null</b>) * @param version the version to retrieve * @return the first matching container */ public static <M extends IModel> VersionedModelInfos<M> find(List<VersionedModelInfos<M>> infos, Version version) { VersionedModelInfos<M> result = null; if (null != infos) { for (int i = 0; null == result && i < infos.size(); i++) { VersionedModelInfos<M> info = infos.get(i); if (Version.equals(info.getVersion(), version)) { result = info; } } } return result; } /** * Returns the model information object with highest version number from <code>list</code>. * Unspecified versions are treated as implicit minimum. * * @param <M> the actual model type * @param list the list of model information objects to determine the maximum from (may be <b>null</b>) * @return the maximum version */ public static <M extends IModel> ModelInfo<M> maxVersion(List<ModelInfo<M>> list) { ModelInfo<M> result = null; if (null != list) { Version highest = null; for (int i = 0, n = list.size(); i < n; i++) { ModelInfo<M> tmp = list.get(i); Version tmpVersion = tmp.getVersion(); if (null == result || Version.compare(tmpVersion, highest) > 0) { result = tmp; highest = tmpVersion; } } } return result; } }
SSEHUB/EASyProducer
Plugins/VarModel/Utils/src/net/ssehub/easy/basics/modelManagement/VersionedModelInfos.java
Java
apache-2.0
21,315
/* * 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.flink.table.runtime.match; import org.apache.flink.cep.EventComparator; import org.apache.flink.table.dataformat.BaseRow; import org.apache.flink.table.generated.GeneratedRecordComparator; import org.apache.flink.table.generated.RecordComparator; /** * An implementation of {@link EventComparator} based on a generated {@link RecordComparator}. */ public class BaseRowEventComparator implements EventComparator<BaseRow> { private static final long serialVersionUID = 1L; private final GeneratedRecordComparator generatedComparator; private transient RecordComparator comparator; public BaseRowEventComparator(GeneratedRecordComparator generatedComparator) { this.generatedComparator = generatedComparator; } @Override public int compare(BaseRow row1, BaseRow row2) { if (comparator == null) { comparator = generatedComparator.newInstance( Thread.currentThread().getContextClassLoader()); } return comparator.compare(row1, row2); } }
shaoxuan-wang/flink
flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/match/BaseRowEventComparator.java
Java
apache-2.0
1,790
<?php /** * Created by JetBrains PhpStorm. * User: occul_000 * Date: 03/03/13 * Time: 19:45 * To change this template use File | Settings | File Templates. */ ?> <!DOCTYPE html> <html> <head> <title>AnfShift</title> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <link rel="stylesheet" href="../docs/assets/css/bootstrap.css"> <meta charset="utf-8"> <link rel="stylesheet" href="../docs/assets/css/style.css"> </head> <body> <header> <div class="navbar navbar-static-top"> <div class="navbar-inner"> <div class="container"> <a class="brand" href="#">Abercrombie & Fitch</a> <ul class="nav pull-right"> <a href="login.php" class="btn btn-large btn-primary">Sign in</a> </ul> </div> </div> </div> </header> <section> <div class="container"> <div class="info"> <h3>Exchange shift,</h3> <h3>Open shift.</h3> <p class="lead">only for associates</p> </div> <div class="container-form"> <form class="form-horizontal" action="../controller/check_register.php" method="POST" > <div class="control-group"> <div class="controls"> <input type="text" name="firstname" placeholder="Firstname" required> </div> </div> <div class="control-group"> <div class="controls"> <input type="text" name="lastname" placeholder="Lastname" required> </div> </div> <div class="control-group"> <div class="controls"> <input type="email" name="email" placeholder="E-mail" required> </div> </div> <div class="control-group"> <div class="controls"> <input type="password" name="password" placeholder="Password" required> </div> </div> <div class="control-group"> <div class="controls"> <input type="password" name="confirmPassword" placeholder="Confirm Password" required> </div> </div> <div class="control-group"> <div class="controls"> <select name="job" required> <option value="cashier">Cashier</option> <option value="impact_1">Impact 1</option> <option value="impact_2">Impact 2</option> <option value="model">Model</option> <option value="ops">OPS</option> <option value="stylist">Stylist</option> </select> </div> </div> <div class="control-group"> <div class="controls"> <button type="submit" class="btn btn-large btn-success">Sign up</button> </div> </div> </form> </div> </div> </body> </html>
GuillaumeOcculy/anfshift_paris
view/register.php
PHP
apache-2.0
2,939
 using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Nest { [JsonObject] public class ClusterIndicesStats { [JsonProperty("completion")] public CompletionStats Completion { get; internal set; } [JsonProperty("count")] public long Count { get; internal set; } [JsonProperty("docs")] public DocStats Documents { get; internal set; } [JsonProperty("fielddata")] public FielddataStats Fielddata { get; internal set; } [JsonProperty("percolate")] public PercolateStats Percolate { get; internal set; } [JsonProperty("query_cache")] public QueryCacheStats QueryCache { get; internal set; } [JsonProperty("segments")] public SegmentsStats Segments { get; internal set; } [JsonProperty("shards")] public ClusterIndicesShardsStats Shards { get; internal set; } [JsonProperty("store")] public StoreStats Store { get; internal set; } } [JsonObject] public class ClusterIndicesShardsStats { [JsonProperty("total")] public double Total { get; internal set; } [JsonProperty("primaries")] public double Primaries { get; internal set; } [JsonProperty("replication")] public double Replication { get; internal set; } [JsonProperty("index")] public ClusterIndicesShardsIndexStats Index { get; internal set; } } [JsonObject] public class ClusterIndicesShardsIndexStats { [JsonProperty("shards")] public ClusterShardMetrics Shards { get; internal set; } [JsonProperty("primaries")] public ClusterShardMetrics Primaries { get; internal set; } [JsonProperty("replication")] public ClusterShardMetrics Replication { get; internal set; } } [JsonObject] public class ClusterShardMetrics { [JsonProperty("min")] public double Min { get; internal set; } [JsonProperty("max")] public double Max { get; internal set; } [JsonProperty("avg")] public double Avg { get; internal set; } } }
jonyadamit/elasticsearch-net
src/Nest/Cluster/ClusterStats/ClusterIndicesStats.cs
C#
apache-2.0
1,939
// 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.cloudstack.api.command.admin.host; import java.util.ArrayList; import java.util.List; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.ClusterResponse; import org.apache.cloudstack.api.response.HostResponse; import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.PodResponse; import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.log4j.Logger; import com.cloud.exception.DiscoveryException; import com.cloud.host.Host; import com.cloud.user.Account; @APICommand(name = "addHost", description="Adds a new host.", responseObject=HostResponse.class) public class AddHostCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(AddHostCmd.class.getName()); private static final String s_name = "addhostresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name=ApiConstants.CLUSTER_ID, type=CommandType.UUID, entityType=ClusterResponse.class, description="the cluster ID for the host") private Long clusterId; @Parameter(name=ApiConstants.CLUSTER_NAME, type=CommandType.STRING, description="the cluster name for the host") private String clusterName; @Parameter(name=ApiConstants.PASSWORD, type=CommandType.STRING, required=true, description="the password for the host") private String password; @Parameter(name=ApiConstants.POD_ID, type=CommandType.UUID, entityType=PodResponse.class, required=true, description="the Pod ID for the host") private Long podId; @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required=true, description="the host URL") private String url; @Parameter(name=ApiConstants.USERNAME, type=CommandType.STRING, required=true, description="the username for the host") private String username; @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType=ZoneResponse.class, required=true, description="the Zone ID for the host") private Long zoneId; @Parameter(name=ApiConstants.HYPERVISOR, type=CommandType.STRING, required=true, description="hypervisor type of the host") private String hypervisor; @Parameter(name=ApiConstants.ALLOCATION_STATE, type=CommandType.STRING, description="Allocation state of this Host for allocation of new resources") private String allocationState; @Parameter(name=ApiConstants.HOST_TAGS, type=CommandType.LIST, collectionType=CommandType.STRING, description="list of tags to be added to the host") private List<String> hostTags; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public Long getClusterId() { return clusterId; } public String getClusterName() { return clusterName; } public String getPassword() { return password; } public Long getPodId() { return podId; } public String getUrl() { return url; } public String getUsername() { return username; } public Long getZoneId() { return zoneId; } public String getHypervisor() { return hypervisor; } public List<String> getHostTags() { return hostTags; } public String getAllocationState() { return allocationState; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public String getCommandName() { return s_name; } @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } @Override public void execute(){ try { List<? extends Host> result = _resourceService.discoverHosts(this); ListResponse<HostResponse> response = new ListResponse<HostResponse>(); List<HostResponse> hostResponses = new ArrayList<HostResponse>(); if (result != null && result.size() > 0) { for (Host host : result) { HostResponse hostResponse = _responseGenerator.createHostResponse(host); hostResponses.add(hostResponse); } } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add host"); } response.setResponses(hostResponses); response.setResponseName(getCommandName()); this.setResponseObject(response); } catch (DiscoveryException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } }
mufaddalq/cloudstack-datera-driver
api/src/org/apache/cloudstack/api/command/admin/host/AddHostCmd.java
Java
apache-2.0
5,997
// Copyright 2015 PLUMgrid // // 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 iovplug type Config struct { Subnet string Socket string Interface string Gateway string }
drzaeus77/docker-plugin
iovplug/config.go
GO
apache-2.0
694
sap.ui.define([ "sap/ui/core/UIComponent", "sap/ui/core/mvc/Controller", "sap/ui/core/routing/History", "sap/ui/model/json/JSONModel" ], function (UIComponent, Controller, History, JSONModel) { "use strict"; return Controller.extend("sap.ui.core.sample.odata.v4.MusicArtists.PublicationObjectPage", { _onObjectMatched : function (oEvent) { var oEventArguments = oEvent.getParameter("arguments"), oView = this.getView(), oPublicationContext = oView.getModel() .bindContext("/" + oEventArguments.artistPath + "/" + oEventArguments.publicationPath) .getBoundContext(); oView.setBindingContext(oPublicationContext); oPublicationContext.requestObject("IsActiveEntity").then(function (bIsActiveEntity) { oView.getModel("ui-op").setProperty("/bEditMode", !bIsActiveEntity); }); }, onBack : function () { var sPreviousHash = History.getInstance().getPreviousHash(); this.getView().getModel("ui-op").setProperty("/bEditMode", false); if (sPreviousHash !== undefined) { window.history.go(-1); } else { this.getOwnerComponent().getRouter().navTo("masterList", null, true); } }, onInit : function () { var oRouter = UIComponent.getRouterFor(this); oRouter.getRoute("publicationObjectPage") .attachPatternMatched(this._onObjectMatched, this); this.getView().setModel(new JSONModel({bEditMode : false}), "ui-op"); } }); });
SAP/openui5
src/sap.ui.core/test/sap/ui/core/demokit/sample/odata/v4/MusicArtists/PublicationObjectPage.controller.js
JavaScript
apache-2.0
1,423
var autils = require('../../AUtils'); var osTool = require('../../osTools'); var shelljs = require('shelljs'); var GenericDiffReporterBase = require('../GenericDiffReporterBase'); class Reporter extends GenericDiffReporterBase { constructor() { super("BeyondCompare"); var app = null; if (osTool.platform.isMac) { try { app = shelljs.ls('/Applications/Beyond Compare.app/Contents/MacOS/bcomp')[0]; } catch (err) { console.error(err); } app = app || autils.searchForExecutable("bcomp"); } else if (osTool.platform.isWindows) { app = autils.searchForExecutable("Beyond Compare 4", "BCompare.exe") || autils.searchForExecutable("Beyond Compare 3", "BCompare.exe"); } app = app || autils.searchForExecutable("bcomp"); this.exePath = app; } } module.exports = Reporter;
approvals/Approvals.NodeJS
lib/Reporting/Reporters/beyondcompareReporter.js
JavaScript
apache-2.0
860
/** * Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.financial.analytics.model.black; import static com.opengamma.engine.value.ValueRequirementNames.POSITION_GAMMA; import java.util.Collections; import java.util.Set; import org.threeten.bp.Instant; import com.google.common.collect.Iterables; import com.opengamma.analytics.financial.forex.method.FXMatrix; import com.opengamma.analytics.financial.interestrate.InstrumentDerivative; import com.opengamma.analytics.financial.interestrate.InstrumentDerivativeVisitor; import com.opengamma.analytics.financial.provider.calculator.blackstirfutures.PositionGammaSTIRFutureOptionCalculator; import com.opengamma.analytics.financial.provider.description.interestrate.BlackSTIRFuturesProviderInterface; import com.opengamma.engine.ComputationTarget; import com.opengamma.engine.function.CompiledFunctionDefinition; import com.opengamma.engine.function.FunctionCompilationContext; import com.opengamma.engine.function.FunctionExecutionContext; import com.opengamma.engine.function.FunctionInputs; import com.opengamma.engine.value.ComputedValue; import com.opengamma.engine.value.ValueProperties; import com.opengamma.engine.value.ValueRequirement; import com.opengamma.engine.value.ValueSpecification; /** * Calculates the position gamma of interest rate future options using a Black surface and curves constructed using the discounting method. */ public class BlackDiscountingPositionGammaIRFutureOptionFunction extends BlackDiscountingIRFutureOptionFunction { /** The position gamma calculator */ private static final InstrumentDerivativeVisitor<BlackSTIRFuturesProviderInterface, Double> CALCULATOR = PositionGammaSTIRFutureOptionCalculator .getInstance(); /** * Sets the value requirement to {@link com.opengamma.engine.value.ValueRequirementNames#POSITION_GAMMA}. */ public BlackDiscountingPositionGammaIRFutureOptionFunction() { super(POSITION_GAMMA); } @Override public CompiledFunctionDefinition compile(final FunctionCompilationContext context, final Instant atInstant) { return new BlackDiscountingCompiledFunction(getTargetToDefinitionConverter(context), getDefinitionToDerivativeConverter(context), true) { @Override protected Set<ComputedValue> getValues(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target, final Set<ValueRequirement> desiredValues, final InstrumentDerivative derivative, final FXMatrix fxMatrix) { final BlackSTIRFuturesProviderInterface blackData = getBlackSurface(executionContext, inputs, target, fxMatrix); final double positionGamma = derivative.accept(CALCULATOR, blackData); final ValueRequirement desiredValue = Iterables.getOnlyElement(desiredValues); final ValueProperties properties = desiredValue.getConstraints().copy().get(); final ValueSpecification spec = new ValueSpecification(POSITION_GAMMA, target.toSpecification(), properties); return Collections.singleton(new ComputedValue(spec, positionGamma)); } }; } }
McLeodMoores/starling
projects/financial/src/main/java/com/opengamma/financial/analytics/model/black/BlackDiscountingPositionGammaIRFutureOptionFunction.java
Java
apache-2.0
3,204
// Copyright 2016 The Oklog 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 ulid import ( "bufio" "bytes" "database/sql/driver" "encoding/binary" "errors" "io" "math" "math/bits" "math/rand" "time" ) /* An ULID is a 16 byte Universally Unique Lexicographically Sortable Identifier The components are encoded as 16 octets. Each component is encoded with the MSB first (network byte order). 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | 32_bit_uint_time_high | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | 16_bit_uint_time_low | 16_bit_uint_random | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | 32_bit_uint_random | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | 32_bit_uint_random | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ type ULID [16]byte var ( // ErrDataSize is returned when parsing or unmarshaling ULIDs with the wrong // data size. ErrDataSize = errors.New("ulid: bad data size when unmarshaling") // ErrInvalidCharacters is returned when parsing or unmarshaling ULIDs with // invalid Base32 encodings. ErrInvalidCharacters = errors.New("ulid: bad data characters when unmarshaling") // ErrBufferSize is returned when marshalling ULIDs to a buffer of insufficient // size. ErrBufferSize = errors.New("ulid: bad buffer size when marshaling") // ErrBigTime is returned when constructing an ULID with a time that is larger // than MaxTime. ErrBigTime = errors.New("ulid: time too big") // ErrOverflow is returned when unmarshaling a ULID whose first character is // larger than 7, thereby exceeding the valid bit depth of 128. ErrOverflow = errors.New("ulid: overflow when unmarshaling") // ErrMonotonicOverflow is returned by a Monotonic entropy source when // incrementing the previous ULID's entropy bytes would result in overflow. ErrMonotonicOverflow = errors.New("ulid: monotonic entropy overflow") // ErrScanValue is returned when the value passed to scan cannot be unmarshaled // into the ULID. ErrScanValue = errors.New("ulid: source value must be a string or byte slice") ) // MonotonicReader is an interface that should yield monotonically increasing // entropy into the provided slice for all calls with the same ms parameter. If // a MonotonicReader is provided to the New constructor, its MonotonicRead // method will be used instead of Read. type MonotonicReader interface { io.Reader MonotonicRead(ms uint64, p []byte) error } // New returns an ULID with the given Unix milliseconds timestamp and an // optional entropy source. Use the Timestamp function to convert // a time.Time to Unix milliseconds. // // ErrBigTime is returned when passing a timestamp bigger than MaxTime. // Reading from the entropy source may also return an error. // // Safety for concurrent use is only dependent on the safety of the // entropy source. func New(ms uint64, entropy io.Reader) (id ULID, err error) { if err = id.SetTime(ms); err != nil { return id, err } switch e := entropy.(type) { case nil: return id, err case MonotonicReader: err = e.MonotonicRead(ms, id[6:]) default: _, err = io.ReadFull(e, id[6:]) } return id, err } // MustNew is a convenience function equivalent to New that panics on failure // instead of returning an error. func MustNew(ms uint64, entropy io.Reader) ULID { id, err := New(ms, entropy) if err != nil { panic(err) } return id } // Parse parses an encoded ULID, returning an error in case of failure. // // ErrDataSize is returned if the len(ulid) is different from an encoded // ULID's length. Invalid encodings produce undefined ULIDs. For a version that // returns an error instead, see ParseStrict. func Parse(ulid string) (id ULID, err error) { return id, parse([]byte(ulid), false, &id) } // ParseStrict parses an encoded ULID, returning an error in case of failure. // // It is like Parse, but additionally validates that the parsed ULID consists // only of valid base32 characters. It is slightly slower than Parse. // // ErrDataSize is returned if the len(ulid) is different from an encoded // ULID's length. Invalid encodings return ErrInvalidCharacters. func ParseStrict(ulid string) (id ULID, err error) { return id, parse([]byte(ulid), true, &id) } func parse(v []byte, strict bool, id *ULID) error { // Check if a base32 encoded ULID is the right length. if len(v) != EncodedSize { return ErrDataSize } // Check if all the characters in a base32 encoded ULID are part of the // expected base32 character set. if strict && (dec[v[0]] == 0xFF || dec[v[1]] == 0xFF || dec[v[2]] == 0xFF || dec[v[3]] == 0xFF || dec[v[4]] == 0xFF || dec[v[5]] == 0xFF || dec[v[6]] == 0xFF || dec[v[7]] == 0xFF || dec[v[8]] == 0xFF || dec[v[9]] == 0xFF || dec[v[10]] == 0xFF || dec[v[11]] == 0xFF || dec[v[12]] == 0xFF || dec[v[13]] == 0xFF || dec[v[14]] == 0xFF || dec[v[15]] == 0xFF || dec[v[16]] == 0xFF || dec[v[17]] == 0xFF || dec[v[18]] == 0xFF || dec[v[19]] == 0xFF || dec[v[20]] == 0xFF || dec[v[21]] == 0xFF || dec[v[22]] == 0xFF || dec[v[23]] == 0xFF || dec[v[24]] == 0xFF || dec[v[25]] == 0xFF) { return ErrInvalidCharacters } // Check if the first character in a base32 encoded ULID will overflow. This // happens because the base32 representation encodes 130 bits, while the // ULID is only 128 bits. // // See https://github.com/oklog/ulid/issues/9 for details. if v[0] > '7' { return ErrOverflow } // Use an optimized unrolled loop (from https://github.com/RobThree/NUlid) // to decode a base32 ULID. // 6 bytes timestamp (48 bits) (*id)[0] = (dec[v[0]] << 5) | dec[v[1]] (*id)[1] = (dec[v[2]] << 3) | (dec[v[3]] >> 2) (*id)[2] = (dec[v[3]] << 6) | (dec[v[4]] << 1) | (dec[v[5]] >> 4) (*id)[3] = (dec[v[5]] << 4) | (dec[v[6]] >> 1) (*id)[4] = (dec[v[6]] << 7) | (dec[v[7]] << 2) | (dec[v[8]] >> 3) (*id)[5] = (dec[v[8]] << 5) | dec[v[9]] // 10 bytes of entropy (80 bits) (*id)[6] = (dec[v[10]] << 3) | (dec[v[11]] >> 2) (*id)[7] = (dec[v[11]] << 6) | (dec[v[12]] << 1) | (dec[v[13]] >> 4) (*id)[8] = (dec[v[13]] << 4) | (dec[v[14]] >> 1) (*id)[9] = (dec[v[14]] << 7) | (dec[v[15]] << 2) | (dec[v[16]] >> 3) (*id)[10] = (dec[v[16]] << 5) | dec[v[17]] (*id)[11] = (dec[v[18]] << 3) | dec[v[19]]>>2 (*id)[12] = (dec[v[19]] << 6) | (dec[v[20]] << 1) | (dec[v[21]] >> 4) (*id)[13] = (dec[v[21]] << 4) | (dec[v[22]] >> 1) (*id)[14] = (dec[v[22]] << 7) | (dec[v[23]] << 2) | (dec[v[24]] >> 3) (*id)[15] = (dec[v[24]] << 5) | dec[v[25]] return nil } // MustParse is a convenience function equivalent to Parse that panics on failure // instead of returning an error. func MustParse(ulid string) ULID { id, err := Parse(ulid) if err != nil { panic(err) } return id } // MustParseStrict is a convenience function equivalent to ParseStrict that // panics on failure instead of returning an error. func MustParseStrict(ulid string) ULID { id, err := ParseStrict(ulid) if err != nil { panic(err) } return id } // Bytes returns bytes slice representation of ULID. func (id ULID) Bytes() []byte { return id[:] } // String returns a lexicographically sortable string encoded ULID // (26 characters, non-standard base 32) e.g. 01AN4Z07BY79KA1307SR9X4MV3. // Format: tttttttttteeeeeeeeeeeeeeee where t is time and e is entropy. func (id ULID) String() string { ulid := make([]byte, EncodedSize) _ = id.MarshalTextTo(ulid) return string(ulid) } // MarshalBinary implements the encoding.BinaryMarshaler interface by // returning the ULID as a byte slice. func (id ULID) MarshalBinary() ([]byte, error) { ulid := make([]byte, len(id)) return ulid, id.MarshalBinaryTo(ulid) } // MarshalBinaryTo writes the binary encoding of the ULID to the given buffer. // ErrBufferSize is returned when the len(dst) != 16. func (id ULID) MarshalBinaryTo(dst []byte) error { if len(dst) != len(id) { return ErrBufferSize } copy(dst, id[:]) return nil } // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface by // copying the passed data and converting it to an ULID. ErrDataSize is // returned if the data length is different from ULID length. func (id *ULID) UnmarshalBinary(data []byte) error { if len(data) != len(*id) { return ErrDataSize } copy((*id)[:], data) return nil } // Encoding is the base 32 encoding alphabet used in ULID strings. const Encoding = "0123456789ABCDEFGHJKMNPQRSTVWXYZ" // MarshalText implements the encoding.TextMarshaler interface by // returning the string encoded ULID. func (id ULID) MarshalText() ([]byte, error) { ulid := make([]byte, EncodedSize) return ulid, id.MarshalTextTo(ulid) } // MarshalTextTo writes the ULID as a string to the given buffer. // ErrBufferSize is returned when the len(dst) != 26. func (id ULID) MarshalTextTo(dst []byte) error { // Optimized unrolled loop ahead. // From https://github.com/RobThree/NUlid if len(dst) != EncodedSize { return ErrBufferSize } // 10 byte timestamp dst[0] = Encoding[(id[0]&224)>>5] dst[1] = Encoding[id[0]&31] dst[2] = Encoding[(id[1]&248)>>3] dst[3] = Encoding[((id[1]&7)<<2)|((id[2]&192)>>6)] dst[4] = Encoding[(id[2]&62)>>1] dst[5] = Encoding[((id[2]&1)<<4)|((id[3]&240)>>4)] dst[6] = Encoding[((id[3]&15)<<1)|((id[4]&128)>>7)] dst[7] = Encoding[(id[4]&124)>>2] dst[8] = Encoding[((id[4]&3)<<3)|((id[5]&224)>>5)] dst[9] = Encoding[id[5]&31] // 16 bytes of entropy dst[10] = Encoding[(id[6]&248)>>3] dst[11] = Encoding[((id[6]&7)<<2)|((id[7]&192)>>6)] dst[12] = Encoding[(id[7]&62)>>1] dst[13] = Encoding[((id[7]&1)<<4)|((id[8]&240)>>4)] dst[14] = Encoding[((id[8]&15)<<1)|((id[9]&128)>>7)] dst[15] = Encoding[(id[9]&124)>>2] dst[16] = Encoding[((id[9]&3)<<3)|((id[10]&224)>>5)] dst[17] = Encoding[id[10]&31] dst[18] = Encoding[(id[11]&248)>>3] dst[19] = Encoding[((id[11]&7)<<2)|((id[12]&192)>>6)] dst[20] = Encoding[(id[12]&62)>>1] dst[21] = Encoding[((id[12]&1)<<4)|((id[13]&240)>>4)] dst[22] = Encoding[((id[13]&15)<<1)|((id[14]&128)>>7)] dst[23] = Encoding[(id[14]&124)>>2] dst[24] = Encoding[((id[14]&3)<<3)|((id[15]&224)>>5)] dst[25] = Encoding[id[15]&31] return nil } // Byte to index table for O(1) lookups when unmarshaling. // We use 0xFF as sentinel value for invalid indexes. var dec = [...]byte{ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0xFF, 0x12, 0x13, 0xFF, 0x14, 0x15, 0xFF, 0x16, 0x17, 0x18, 0x19, 0x1A, 0xFF, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0xFF, 0x12, 0x13, 0xFF, 0x14, 0x15, 0xFF, 0x16, 0x17, 0x18, 0x19, 0x1A, 0xFF, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, } // EncodedSize is the length of a text encoded ULID. const EncodedSize = 26 // UnmarshalText implements the encoding.TextUnmarshaler interface by // parsing the data as string encoded ULID. // // ErrDataSize is returned if the len(v) is different from an encoded // ULID's length. Invalid encodings produce undefined ULIDs. func (id *ULID) UnmarshalText(v []byte) error { return parse(v, false, id) } // Time returns the Unix time in milliseconds encoded in the ULID. // Use the top level Time function to convert the returned value to // a time.Time. func (id ULID) Time() uint64 { return uint64(id[5]) | uint64(id[4])<<8 | uint64(id[3])<<16 | uint64(id[2])<<24 | uint64(id[1])<<32 | uint64(id[0])<<40 } // maxTime is the maximum Unix time in milliseconds that can be // represented in an ULID. var maxTime = ULID{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}.Time() // MaxTime returns the maximum Unix time in milliseconds that // can be encoded in an ULID. func MaxTime() uint64 { return maxTime } // Now is a convenience function that returns the current // UTC time in Unix milliseconds. Equivalent to: // Timestamp(time.Now().UTC()) func Now() uint64 { return Timestamp(time.Now().UTC()) } // Timestamp converts a time.Time to Unix milliseconds. // // Because of the way ULID stores time, times from the year // 10889 produces undefined results. func Timestamp(t time.Time) uint64 { return uint64(t.Unix())*1000 + uint64(t.Nanosecond()/int(time.Millisecond)) } // Time converts Unix milliseconds in the format // returned by the Timestamp function to a time.Time. func Time(ms uint64) time.Time { s := int64(ms / 1e3) ns := int64((ms % 1e3) * 1e6) return time.Unix(s, ns) } // SetTime sets the time component of the ULID to the given Unix time // in milliseconds. func (id *ULID) SetTime(ms uint64) error { if ms > maxTime { return ErrBigTime } (*id)[0] = byte(ms >> 40) (*id)[1] = byte(ms >> 32) (*id)[2] = byte(ms >> 24) (*id)[3] = byte(ms >> 16) (*id)[4] = byte(ms >> 8) (*id)[5] = byte(ms) return nil } // Entropy returns the entropy from the ULID. func (id ULID) Entropy() []byte { e := make([]byte, 10) copy(e, id[6:]) return e } // SetEntropy sets the ULID entropy to the passed byte slice. // ErrDataSize is returned if len(e) != 10. func (id *ULID) SetEntropy(e []byte) error { if len(e) != 10 { return ErrDataSize } copy((*id)[6:], e) return nil } // Compare returns an integer comparing id and other lexicographically. // The result will be 0 if id==other, -1 if id < other, and +1 if id > other. func (id ULID) Compare(other ULID) int { return bytes.Compare(id[:], other[:]) } // Scan implements the sql.Scanner interface. It supports scanning // a string or byte slice. func (id *ULID) Scan(src interface{}) error { switch x := src.(type) { case nil: return nil case string: return id.UnmarshalText([]byte(x)) case []byte: return id.UnmarshalBinary(x) } return ErrScanValue } // Value implements the sql/driver.Valuer interface, returning the ULID as a // slice of bytes, by invoking MarshalBinary. If your use case requires a string // representation instead, you can create a wrapper type that calls String() // instead. // // type stringValuer ulid.ULID // // func (v stringValuer) Value() (driver.Value, error) { // return ulid.ULID(v).String(), nil // } // // // Example usage. // db.Exec("...", stringValuer(id)) // // All valid ULIDs, including zero-value ULIDs, return a valid Value with a nil // error. If your use case requires zero-value ULIDs to return a non-nil error, // you can create a wrapper type that special-cases this behavior. // // var zeroValueULID ulid.ULID // // type invalidZeroValuer ulid.ULID // // func (v invalidZeroValuer) Value() (driver.Value, error) { // if ulid.ULID(v).Compare(zeroValueULID) == 0 { // return nil, fmt.Errorf("zero value") // } // return ulid.ULID(v).Value() // } // // // Example usage. // db.Exec("...", invalidZeroValuer(id)) // func (id ULID) Value() (driver.Value, error) { return id.MarshalBinary() } // Monotonic returns an entropy source that is guaranteed to yield // strictly increasing entropy bytes for the same ULID timestamp. // On conflicts, the previous ULID entropy is incremented with a // random number between 1 and `inc` (inclusive). // // The provided entropy source must actually yield random bytes or else // monotonic reads are not guaranteed to terminate, since there isn't // enough randomness to compute an increment number. // // When `inc == 0`, it'll be set to a secure default of `math.MaxUint32`. // The lower the value of `inc`, the easier the next ULID within the // same millisecond is to guess. If your code depends on ULIDs having // secure entropy bytes, then don't go under this default unless you know // what you're doing. // // The returned type isn't safe for concurrent use. func Monotonic(entropy io.Reader, inc uint64) *MonotonicEntropy { m := MonotonicEntropy{ Reader: bufio.NewReader(entropy), inc: inc, } if m.inc == 0 { m.inc = math.MaxUint32 } if rng, ok := entropy.(*rand.Rand); ok { m.rng = rng } return &m } // MonotonicEntropy is an opaque type that provides monotonic entropy. type MonotonicEntropy struct { io.Reader ms uint64 inc uint64 entropy uint80 rand [8]byte rng *rand.Rand } // MonotonicRead implements the MonotonicReader interface. func (m *MonotonicEntropy) MonotonicRead(ms uint64, entropy []byte) (err error) { if !m.entropy.IsZero() && m.ms == ms { err = m.increment() m.entropy.AppendTo(entropy) } else if _, err = io.ReadFull(m.Reader, entropy); err == nil { m.ms = ms m.entropy.SetBytes(entropy) } return err } // increment the previous entropy number with a random number // of up to m.inc (inclusive). func (m *MonotonicEntropy) increment() error { if inc, err := m.random(); err != nil { return err } else if m.entropy.Add(inc) { return ErrMonotonicOverflow } return nil } // random returns a uniform random value in [1, m.inc), reading entropy // from m.Reader. When m.inc == 0 || m.inc == 1, it returns 1. // Adapted from: https://golang.org/pkg/crypto/rand/#Int func (m *MonotonicEntropy) random() (inc uint64, err error) { if m.inc <= 1 { return 1, nil } // Fast path for using a underlying rand.Rand directly. if m.rng != nil { // Range: [1, m.inc) return 1 + uint64(m.rng.Int63n(int64(m.inc))), nil } // bitLen is the maximum bit length needed to encode a value < m.inc. bitLen := bits.Len64(m.inc) // byteLen is the maximum byte length needed to encode a value < m.inc. byteLen := uint(bitLen+7) / 8 // msbitLen is the number of bits in the most significant byte of m.inc-1. msbitLen := uint(bitLen % 8) if msbitLen == 0 { msbitLen = 8 } for inc == 0 || inc >= m.inc { if _, err = io.ReadFull(m.Reader, m.rand[:byteLen]); err != nil { return 0, err } // Clear bits in the first byte to increase the probability // that the candidate is < m.inc. m.rand[0] &= uint8(int(1<<msbitLen) - 1) // Convert the read bytes into an uint64 with byteLen // Optimized unrolled loop. switch byteLen { case 1: inc = uint64(m.rand[0]) case 2: inc = uint64(binary.LittleEndian.Uint16(m.rand[:2])) case 3, 4: inc = uint64(binary.LittleEndian.Uint32(m.rand[:4])) case 5, 6, 7, 8: inc = uint64(binary.LittleEndian.Uint64(m.rand[:8])) } } // Range: [1, m.inc) return 1 + inc, nil } type uint80 struct { Hi uint16 Lo uint64 } func (u *uint80) SetBytes(bs []byte) { u.Hi = binary.BigEndian.Uint16(bs[:2]) u.Lo = binary.BigEndian.Uint64(bs[2:]) } func (u *uint80) AppendTo(bs []byte) { binary.BigEndian.PutUint16(bs[:2], u.Hi) binary.BigEndian.PutUint64(bs[2:], u.Lo) } func (u *uint80) Add(n uint64) (overflow bool) { lo, hi := u.Lo, u.Hi if u.Lo += n; u.Lo < lo { u.Hi++ } return u.Hi < hi } func (u uint80) IsZero() bool { return u.Hi == 0 && u.Lo == 0 }
oklog/ulid
ulid.go
GO
apache-2.0
20,673
/* Copyright 2014-2016 Intel Corporation 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 apple.uikit; import apple.NSObject; import apple.foundation.NSArray; import apple.foundation.NSCoder; import apple.foundation.NSMethodSignature; import apple.foundation.NSSet; import apple.foundation.protocol.NSCopying; import apple.foundation.protocol.NSMutableCopying; import apple.foundation.protocol.NSSecureCoding; import org.moe.natj.c.ann.FunctionPtr; import org.moe.natj.general.NatJ; import org.moe.natj.general.Pointer; import org.moe.natj.general.ann.Generated; import org.moe.natj.general.ann.Library; import org.moe.natj.general.ann.Mapped; import org.moe.natj.general.ann.MappedReturn; import org.moe.natj.general.ann.NFloat; import org.moe.natj.general.ann.NInt; import org.moe.natj.general.ann.NUInt; import org.moe.natj.general.ann.Owned; import org.moe.natj.general.ann.Runtime; import org.moe.natj.general.ptr.VoidPtr; import org.moe.natj.objc.Class; import org.moe.natj.objc.ObjCRuntime; import org.moe.natj.objc.SEL; import org.moe.natj.objc.ann.ObjCClassBinding; import org.moe.natj.objc.ann.ProtocolClassMethod; import org.moe.natj.objc.ann.Selector; import org.moe.natj.objc.map.ObjCObjectMapper; /** * NSParagraphStyle */ @Generated @Library("UIKit") @Runtime(ObjCRuntime.class) @ObjCClassBinding public class NSParagraphStyle extends NSObject implements NSCopying, NSMutableCopying, NSSecureCoding { static { NatJ.register(); } @Generated protected NSParagraphStyle(Pointer peer) { super(peer); } @Generated @Selector("accessInstanceVariablesDirectly") public static native boolean accessInstanceVariablesDirectly(); @Generated @Owned @Selector("alloc") public static native NSParagraphStyle alloc(); @Owned @Generated @Selector("allocWithZone:") public static native NSParagraphStyle allocWithZone(VoidPtr zone); @Generated @Selector("automaticallyNotifiesObserversForKey:") public static native boolean automaticallyNotifiesObserversForKey(String key); @Generated @Selector("cancelPreviousPerformRequestsWithTarget:") public static native void cancelPreviousPerformRequestsWithTarget(@Mapped(ObjCObjectMapper.class) Object aTarget); @Generated @Selector("cancelPreviousPerformRequestsWithTarget:selector:object:") public static native void cancelPreviousPerformRequestsWithTargetSelectorObject( @Mapped(ObjCObjectMapper.class) Object aTarget, SEL aSelector, @Mapped(ObjCObjectMapper.class) Object anArgument); @Generated @Selector("classFallbacksForKeyedArchiver") public static native NSArray<String> classFallbacksForKeyedArchiver(); @Generated @Selector("classForKeyedUnarchiver") public static native Class classForKeyedUnarchiver(); @Generated @Selector("debugDescription") public static native String debugDescription_static(); /** * This class property returns a shared and cached NSParagraphStyle instance with the default style settings, with same value as the result of [[NSParagraphStyle alloc] init]. */ @Generated @Selector("defaultParagraphStyle") public static native NSParagraphStyle defaultParagraphStyle(); /** * languageName is in ISO lang region format */ @Generated @Selector("defaultWritingDirectionForLanguage:") @NInt public static native long defaultWritingDirectionForLanguage(String languageName); @Generated @Selector("description") public static native String description_static(); @Generated @Selector("hash") @NUInt public static native long hash_static(); @Generated @Selector("instanceMethodForSelector:") @FunctionPtr(name = "call_instanceMethodForSelector_ret") public static native NSObject.Function_instanceMethodForSelector_ret instanceMethodForSelector(SEL aSelector); @Generated @Selector("instanceMethodSignatureForSelector:") public static native NSMethodSignature instanceMethodSignatureForSelector(SEL aSelector); @Generated @Selector("instancesRespondToSelector:") public static native boolean instancesRespondToSelector(SEL aSelector); @Generated @Selector("isSubclassOfClass:") public static native boolean isSubclassOfClass(Class aClass); @Generated @Selector("keyPathsForValuesAffectingValueForKey:") public static native NSSet<String> keyPathsForValuesAffectingValueForKey(String key); @Generated @Owned @Selector("new") public static native NSParagraphStyle new_objc(); @Generated @Selector("resolveClassMethod:") public static native boolean resolveClassMethod(SEL sel); @Generated @Selector("resolveInstanceMethod:") public static native boolean resolveInstanceMethod(SEL sel); @Generated @Selector("setVersion:") public static native void setVersion_static(@NInt long aVersion); @Generated @Selector("superclass") public static native Class superclass_static(); @Generated @Selector("supportsSecureCoding") public static native boolean supportsSecureCoding(); @Generated @Selector("version") @NInt public static native long version_static(); @Generated @Selector("alignment") @NInt public native long alignment(); /** * Tightens inter-character spacing in attempt to fit lines wider than the available space if the line break mode is one of the truncation modes before starting to truncate. NO by default. The maximum amount of tightening performed is determined by the system based on contexts such as font, line width, etc. */ @Generated @Selector("allowsDefaultTighteningForTruncation") public native boolean allowsDefaultTighteningForTruncation(); @Generated @Selector("baseWritingDirection") @NInt public native long baseWritingDirection(); @Generated @Owned @Selector("copyWithZone:") @MappedReturn(ObjCObjectMapper.class) public native Object copyWithZone(VoidPtr zone); /** * The default tab interval used for locations beyond the last element in tabStops */ @Generated @Selector("defaultTabInterval") @NFloat public native double defaultTabInterval(); @Generated @Selector("encodeWithCoder:") public native void encodeWithCoder(NSCoder coder); /** * Distance from margin to edge appropriate for text direction */ @Generated @Selector("firstLineHeadIndent") @NFloat public native double firstLineHeadIndent(); /** * Distance from margin to front edge of paragraph */ @Generated @Selector("headIndent") @NFloat public native double headIndent(); /** * Specifies the threshold for hyphenation. Valid values lie between 0.0 and 1.0 inclusive. Hyphenation will be attempted when the ratio of the text width as broken without hyphenation to the width of the line fragment is less than the hyphenation factor. When this takes on its default value of 0.0, the layout manager's hyphenation factor is used instead. When both are 0.0, hyphenation is disabled. */ @Generated @Selector("hyphenationFactor") public native float hyphenationFactor(); @Generated @Selector("init") public native NSParagraphStyle init(); @Generated @Selector("initWithCoder:") public native NSParagraphStyle initWithCoder(NSCoder coder); @Generated @Selector("lineBreakMode") @NInt public native long lineBreakMode(); /** * Natural line height is multiplied by this factor (if positive) before being constrained by minimum and maximum line height. */ @Generated @Selector("lineHeightMultiple") @NFloat public native double lineHeightMultiple(); /** * "Leading": distance between the bottom of one line fragment and top of next (applied between lines in the same container). This value is included in the line fragment heights in layout manager. */ @Generated @Selector("lineSpacing") @NFloat public native double lineSpacing(); /** * 0 implies no maximum. */ @Generated @Selector("maximumLineHeight") @NFloat public native double maximumLineHeight(); /** * Line height is the distance from bottom of descenders to top of ascenders; basically the line fragment height. Does not include lineSpacing (which is added after this computation). */ @Generated @Selector("minimumLineHeight") @NFloat public native double minimumLineHeight(); @Owned @Generated @Selector("mutableCopyWithZone:") @MappedReturn(ObjCObjectMapper.class) public native Object mutableCopyWithZone(VoidPtr zone); /** * Distance between the bottom of this paragraph and top of next (or the beginning of its paragraphSpacingBefore, if any). */ @Generated @Selector("paragraphSpacing") @NFloat public native double paragraphSpacing(); /** * Distance between the bottom of the previous paragraph (or the end of its paragraphSpacing, if any) and the top of this paragraph. */ @Generated @Selector("paragraphSpacingBefore") @NFloat public native double paragraphSpacingBefore(); @Generated @ProtocolClassMethod("supportsSecureCoding") public boolean _supportsSecureCoding() { return supportsSecureCoding(); } /** * An array of NSTextTabs. Contents should be ordered by location. The default value is an array of 12 left-aligned tabs at 28pt interval */ @Generated @Selector("tabStops") public native NSArray<? extends NSTextTab> tabStops(); /** * Distance from margin to back edge of paragraph; if negative or 0, from other margin */ @Generated @Selector("tailIndent") @NFloat public native double tailIndent(); /** * Specifies the line break strategies that may be used for laying out the paragraph. The default value is NSLineBreakStrategyNone. */ @Generated @Selector("lineBreakStrategy") @NUInt public native long lineBreakStrategy(); /** * A property controlling the hyphenation behavior for the paragraph associated with the paragraph style. The exact hyphenation logic is dynamically determined by the layout context such as language, platform, etc. When YES, it affects the return value from -hyphenationFactor when the property is set to 0.0. */ @Generated @Selector("usesDefaultHyphenation") public native boolean usesDefaultHyphenation(); }
multi-os-engine/moe-core
moe.apple/moe.platform.ios/src/main/java/apple/uikit/NSParagraphStyle.java
Java
apache-2.0
11,103
/* * Copyright 2004-2011 the Seasar Foundation and the Others. * * 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.seasar.dao.node; import org.seasar.dao.CommandContext; import org.seasar.dao.IllegalBoolExpressionRuntimeException; import org.seasar.framework.util.OgnlUtil; /** * @author higa * */ public class IfNode extends ContainerNode { private String expression; private Object parsedExpression; private ElseNode elseNode; public IfNode(String expression) { this.expression = expression; this.parsedExpression = OgnlUtil.parseExpression(expression); } public String getExpression() { return expression; } public ElseNode getElseNode() { return elseNode; } public void setElseNode(ElseNode elseNode) { this.elseNode = elseNode; } /** * @see org.seasar.dao.Node#accept(org.seasar.dao.QueryContext) */ public void accept(CommandContext ctx) { Object result = OgnlUtil.getValue(parsedExpression, ctx); if (result instanceof Boolean) { if (((Boolean) result).booleanValue()) { super.accept(ctx); ctx.setEnabled(true); } else if (elseNode != null) { elseNode.accept(ctx); ctx.setEnabled(true); } } else { throw new IllegalBoolExpressionRuntimeException(expression); } } }
seasarorg/s2dao
s2-dao/src/main/java/org/seasar/dao/node/IfNode.java
Java
apache-2.0
2,029
/** * Copyright (c) 2013-2019 Contributors to the Eclipse Foundation * * <p> See the NOTICE file distributed with this work for additional information regarding copyright * ownership. All rights reserved. This program and the accompanying materials are made available * under the terms of the Apache License, Version 2.0 which accompanies this distribution and is * available at http://www.apache.org/licenses/LICENSE-2.0.txt */ package org.locationtech.geowave.mapreduce; import org.apache.hadoop.io.Writable; import org.locationtech.geowave.core.store.api.DataTypeAdapter; /** * This is an interface that extends data adapter to allow map reduce jobs to easily convert hadoop * writable objects to and from the geowave native representation of the objects. This allow for * generally applicable map reduce jobs to be written using base classes for the mapper that can * handle translations. * * @param <T> the native type * @param <W> the writable type */ public interface HadoopDataAdapter<T, W extends Writable> extends DataTypeAdapter<T> { public HadoopWritableSerializer<T, W> createWritableSerializer(); }
spohnan/geowave
core/mapreduce/src/main/java/org/locationtech/geowave/mapreduce/HadoopDataAdapter.java
Java
apache-2.0
1,132
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.exoplayer; import com.google.android.exoplayer.util.Util; import android.annotation.SuppressLint; import android.annotation.TargetApi; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * Encapsulates the information describing the format of media data, be it audio * or video. */ public class MediaFormat { public static final int NO_VALUE = -1; public final String mimeType; public final int maxInputSize; public final int width; public final int height; public final int channelCount; public final int sampleRate; private int maxWidth; private int maxHeight; public final List<byte[]> initializationData; // Lazy-initialized hashcode. private int hashCode; // Possibly-lazy-initialized framework media format. private android.media.MediaFormat frameworkMediaFormat; @TargetApi(16) public static MediaFormat createFromFrameworkMediaFormatV16(android.media.MediaFormat format) { return new MediaFormat(format); } public static MediaFormat createVideoFormat(String mimeType, int maxInputSize, int width, int height, List<byte[]> initializationData) { return new MediaFormat(mimeType, maxInputSize, width, height, NO_VALUE, NO_VALUE, initializationData); } public static MediaFormat createAudioFormat(String mimeType, int maxInputSize, int channelCount, int sampleRate, List<byte[]> initializationData) { return new MediaFormat(mimeType, maxInputSize, NO_VALUE, NO_VALUE, channelCount, sampleRate, initializationData); } @TargetApi(16) private MediaFormat(android.media.MediaFormat format) { this.frameworkMediaFormat = format; mimeType = format.getString(android.media.MediaFormat.KEY_MIME); maxInputSize = getOptionalIntegerV16(format, android.media.MediaFormat.KEY_MAX_INPUT_SIZE); width = getOptionalIntegerV16(format, android.media.MediaFormat.KEY_WIDTH); height = getOptionalIntegerV16(format, android.media.MediaFormat.KEY_HEIGHT); channelCount = getOptionalIntegerV16(format, android.media.MediaFormat.KEY_CHANNEL_COUNT); sampleRate = getOptionalIntegerV16(format, android.media.MediaFormat.KEY_SAMPLE_RATE); initializationData = new ArrayList<byte[]>(); for (int i = 0; format.containsKey("csd-" + i); i++) { ByteBuffer buffer = format.getByteBuffer("csd-" + i); byte[] data = new byte[buffer.limit()]; buffer.get(data); initializationData.add(data); buffer.flip(); } maxWidth = NO_VALUE; maxHeight = NO_VALUE; } private MediaFormat(String mimeType, int maxInputSize, int width, int height, int channelCount, int sampleRate, List<byte[]> initializationData) { this.mimeType = mimeType; this.maxInputSize = maxInputSize; this.width = width; this.height = height; this.channelCount = channelCount; this.sampleRate = sampleRate; this.initializationData = initializationData == null ? Collections.<byte[]> emptyList() : initializationData; maxWidth = NO_VALUE; maxHeight = NO_VALUE; } public void setMaxVideoDimensions(int maxWidth, int maxHeight) { this.maxWidth = maxWidth; this.maxHeight = maxHeight; if (frameworkMediaFormat != null) { maybeSetMaxDimensionsV16(frameworkMediaFormat); } } public int getMaxVideoWidth() { return maxWidth; } public int getMaxVideoHeight() { return maxHeight; } @Override public int hashCode() { if (hashCode == 0) { int result = 17; result = 31 * result + mimeType == null ? 0 : mimeType.hashCode(); result = 31 * result + maxInputSize; result = 31 * result + width; result = 31 * result + height; result = 31 * result + maxWidth; result = 31 * result + maxHeight; result = 31 * result + channelCount; result = 31 * result + sampleRate; for (int i = 0; i < initializationData.size(); i++) { result = 31 * result + Arrays.hashCode(initializationData.get(i)); } hashCode = result; } return hashCode; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } return equalsInternal((MediaFormat) obj, false); } public boolean equals(MediaFormat other, boolean ignoreMaxDimensions) { if (this == other) { return true; } if (other == null) { return false; } return equalsInternal(other, ignoreMaxDimensions); } private boolean equalsInternal(MediaFormat other, boolean ignoreMaxDimensions) { if (maxInputSize != other.maxInputSize || width != other.width || height != other.height || (!ignoreMaxDimensions && (maxWidth != other.maxWidth || maxHeight != other.maxHeight)) || channelCount != other.channelCount || sampleRate != other.sampleRate || !Util.areEqual(mimeType, other.mimeType) || initializationData.size() != other.initializationData.size()) { return false; } for (int i = 0; i < initializationData.size(); i++) { if (!Arrays.equals(initializationData.get(i), other.initializationData.get(i))) { return false; } } return true; } @Override public String toString() { return "MediaFormat(" + mimeType + ", " + maxInputSize + ", " + width + ", " + height + ", " + channelCount + ", " + sampleRate + ", " + maxWidth + ", " + maxHeight + ")"; } /** * @return A {@link MediaFormat} representation of this format. */ @TargetApi(16) public final android.media.MediaFormat getFrameworkMediaFormatV16() { if (frameworkMediaFormat == null) { android.media.MediaFormat format = new android.media.MediaFormat(); format.setString(android.media.MediaFormat.KEY_MIME, mimeType); maybeSetIntegerV16(format, android.media.MediaFormat.KEY_MAX_INPUT_SIZE, maxInputSize); maybeSetIntegerV16(format, android.media.MediaFormat.KEY_WIDTH, width); maybeSetIntegerV16(format, android.media.MediaFormat.KEY_HEIGHT, height); maybeSetIntegerV16(format, android.media.MediaFormat.KEY_CHANNEL_COUNT, channelCount); maybeSetIntegerV16(format, android.media.MediaFormat.KEY_SAMPLE_RATE, sampleRate); for (int i = 0; i < initializationData.size(); i++) { format.setByteBuffer("csd-" + i, ByteBuffer.wrap(initializationData.get(i))); } maybeSetMaxDimensionsV16(format); frameworkMediaFormat = format; } return frameworkMediaFormat; } @SuppressLint("InlinedApi") @TargetApi(16) private final void maybeSetMaxDimensionsV16(android.media.MediaFormat format) { maybeSetIntegerV16(format, android.media.MediaFormat.KEY_MAX_WIDTH, maxWidth); maybeSetIntegerV16(format, android.media.MediaFormat.KEY_MAX_HEIGHT, maxHeight); } @TargetApi(16) private static final void maybeSetIntegerV16(android.media.MediaFormat format, String key, int value) { if (value != NO_VALUE) { format.setInteger(key, value); } } @TargetApi(16) private static final int getOptionalIntegerV16(android.media.MediaFormat format, String key) { return format.containsKey(key) ? format.getInteger(key) : NO_VALUE; } }
summerpulse/amlexo
src/com/google/android/exoplayer/MediaFormat.java
Java
apache-2.0
8,647
/** * Copyright 2010 Wealthfront 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 com.kaching.platform.testing; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Under the regime of {@link LessIOSecurityManager}, only classes annotated * with this annotation may use the DNS system to resolve hostnames or IP * addresses. * * Annotating a class with {@link AllowNetworkMulticast}, * {@link AllowNetworkListen}, or {@link AllowNetworkAccess}, implies permission * to use the DNS system as described above. */ @Retention(RUNTIME) @Target(TYPE) public @interface AllowDNSResolution { }
wealthfront/kawala
kawala-testing/src/main/java/com/kaching/platform/testing/AllowDNSResolution.java
Java
apache-2.0
1,246
package com.google.api.ads.dfp.jaxws.v201511; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for SwiffyConversionError.Reason. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="SwiffyConversionError.Reason"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="SERVER_ERROR"/> * &lt;enumeration value="INVALID_FLASH_FILE"/> * &lt;enumeration value="UNSUPPORTED_FLASH"/> * &lt;enumeration value="UNKNOWN"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "SwiffyConversionError.Reason") @XmlEnum public enum SwiffyConversionErrorReason { /** * * Indicates the Swiffy service has an internal error that prevents the flash * asset being converted. * * */ SERVER_ERROR, /** * * Indicates the uploaded flash asset is not a valid flash file. * * */ INVALID_FLASH_FILE, /** * * Indicates the Swiffy service currently does not support converting this * flash asset. * * */ UNSUPPORTED_FLASH, /** * * The value returned if the actual value is not exposed by the requested API version. * * */ UNKNOWN; public String value() { return name(); } public static SwiffyConversionErrorReason fromValue(String v) { return valueOf(v); } }
gawkermedia/googleads-java-lib
modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201511/SwiffyConversionErrorReason.java
Java
apache-2.0
1,709
"""REST API for DP.LA Service Hub BIBCAT Aggregator Feed""" __author__ = "Jeremy Nelson, Mike Stabile" import click import datetime import json import math import os import pkg_resources import xml.etree.ElementTree as etree import requests import rdflib import urllib.parse import reports import bibcat.rml.processor as processor from zipfile import ZipFile, ZIP_DEFLATED from elasticsearch_dsl import Search, Q from flask import abort, Flask, jsonify, request, render_template, Response from flask import flash, url_for from flask import flash #from flask_cache import Cache from resync import CapabilityList, ResourceDump, ResourceDumpManifest from resync import ResourceList from resync.resource import Resource from resync.resource_list import ResourceListDupeError from resync.dump import Dump app = Flask(__name__, instance_relative_config=True) app.config.from_pyfile('config.py') from rdfframework.rml import RmlManager from rdfframework.configuration import RdfConfigManager from rdfframework.datamanager import DefinitionManager from rdfframework.datatypes import RdfNsManager RmlManager().register_defs([('package_all', 'bibcat.maps')]) # Define vocabulary and definition file locations DefinitionManager().add_file_locations([('vocabularies', ['rdf', 'rdfs', 'owl', 'schema', 'bf', 'skos', 'dcterm']), ('package_all', 'bibcat.rdfw-definitions')]) # Register RDF namespaces to use RdfNsManager({'acl': '<http://www.w3.org/ns/auth/acl#>', 'bd': '<http://www.bigdata.com/rdf#>', 'bf': 'http://id.loc.gov/ontologies/bibframe/', 'dbo': 'http://dbpedia.org/ontology/', 'dbp': 'http://dbpedia.org/property/', 'dbr': 'http://dbpedia.org/resource/', 'dc': 'http://purl.org/dc/elements/1.1/', 'dcterm': 'http://purl.org/dc/terms/', 'dpla': 'http://dp.la/about/map/', 'edm': 'http://www.europeana.eu/schemas/edm/', 'es': 'http://knowledgelinks.io/ns/elasticsearch/', 'foaf': 'http://xmlns.com/foaf/0.1/', 'loc': 'http://id.loc.gov/authorities/', 'm21': '<http://knowledgelinks.io/ns/marc21/>', 'mads': '<http://www.loc.gov/mads/rdf/v1#>', 'mods': 'http://www.loc.gov/mods/v3#', 'ore': 'http://www.openarchives.org/ore/terms/', 'owl': 'http://www.w3.org/2002/07/owl#', 'relators': 'http://id.loc.gov/vocabulary/relators/', 'schema': 'http://schema.org/', 'skos': 'http://www.w3.org/2004/02/skos/core#', 'xsd': 'http://www.w3.org/2001/XMLSchema#'}) CONFIG_MANAGER = RdfConfigManager(app.config, verify=False) CONNECTIONS = CONFIG_MANAGER.conns BF = rdflib.Namespace("http://id.loc.gov/ontologies/bibframe/") W3C_DATE = "%Y-%m-%dT%H:%M:%SZ" __version__ = "1.0.0" #cache = Cache(app, config={"CACHE_TYPE": "filesystem", # "CACHE_DIR": os.path.join(PROJECT_BASE, "cache")}) def __run_query__(query): """Helper function returns results from sparql query""" result = requests.post(app.config.get("TRIPLESTORE_URL"), data={"query": query, "format": "json"}) if result.status_code < 400: return result.json().get('results').get('bindings') def __get_instances__(offset=0): """Helper function used by siteindex and resourcedump views Args: offset(int): offset number of records """ offset = int(offset)*50000 sparql = """ SELECT DISTINCT ?instance ?date WHERE {{ ?instance rdf:type bf:Instance . OPTIONAL {{ ?instance bf:generationProcess ?process . ?process bf:generationDate ?date . }} }} ORDER BY ?instance LIMIT 50000 OFFSET {0}""".format(offset) instances = CONNECTIONS.datastore.query(sparql) return instances def __get_mod_date__(entity_iri=None): if "MOD_DATE" in app.config: return app.config.get("MOD_DATE") return datetime.datetime.utcnow().strftime(W3C_DATE) def __generate_profile__(instance_uri): search = Search(using=CONNECTIONS.search.es).query( Q("term", uri="{}#Work".format(instance_uri))).source( ["bf_hasInstance.bf_hasItem.rml_map.map4_json_ld"]) result = search.execute() if len(result.hits.hits) < 1: #abort(404) #click.echo("{}#Work not found".format(instance_uri)) return if len(result.hits.hits[0]["_source"]) < 1: #abort(404) #click.echo("{}#Work missing _source".format(instance_uri)) return raw_map4 = result.hits.hits[0]["_source"]["bf_hasInstance"][0]\ ["bf_hasItem"][0]["rml_map"]["map4_json_ld"] return raw_map4 def __generate_resource_dump__(): r_dump = ResourceDump() r_dump.ln.append({"rel": "resourcesync", "href": url_for('capability_list')}) bindings = CONNECTIONS.datastore.query(""" SELECT (count(?s) as ?count) WHERE { ?s rdf:type bf:Instance . ?item bf:itemOf ?s . }""") count = int(bindings[0].get('count').get('value')) shards = math.ceil(count/50000) for i in range(0, shards): zip_info = __generate_zip_file__(i) try: zip_modified = datetime.datetime.fromtimestamp(zip_info.get('date')) last_mod = zip_modified.strftime("%Y-%m-%d") except TypeError: last_mod = zip_info.get('date')[0:10] click.echo("Total errors {:,}".format(len(zip_info.get('errors')))) r_dump.add( Resource(url_for('resource_zip', count=i*50000), lastmod=last_mod, mime_type="application/zip", length=zip_info.get("size") ) ) return r_dump def __generate_zip_file__(offset=0): start = datetime.datetime.utcnow() click.echo("Started at {}".format(start.ctime())) manifest = ResourceDumpManifest() manifest.modified = datetime.datetime.utcnow().isoformat() manifest.ln.append({"rel": "resourcesync", "href": url_for('capability_list')}) file_name = "{}-{:03}.zip".format( datetime.datetime.utcnow().toordinal(), offset) tmp_location = os.path.join(app.config.get("DIRECTORIES")[0].get("path"), "dump/{}".format(file_name)) if os.path.exists(tmp_location) is True: return {"date": os.path.getmtime(tmp_location), "size": os.path.getsize(tmp_location)} dump_zip = ZipFile(tmp_location, mode="w", compression=ZIP_DEFLATED, allowZip64=True) instances = __get_instances__(offset) errors = [] click.echo("Iterating through {:,} instances".format(len(instances))) for i,row in enumerate(instances): instance_iri = row.get("instance").get('value') key = instance_iri.split("/")[-1] if not "date" in row: last_mod = __get_mod_date__() else: last_mod = "{}".format(row.get("date").get("value")[0:10]) path = "resources/{}.json".format(key) if not i%25 and i > 0: click.echo(".", nl=False) if not i%100: click.echo("{:,}".format(i), nl=False) raw_json = __generate_profile__(instance_iri) if raw_json is None: errors.append(instance_iri) continue elif len(raw_json) < 1: click.echo(instance_iri, nl=False) break dump_zip.writestr(path, raw_json) manifest.add( Resource(instance_iri, lastmod=last_mod, length="{}".format(len(raw_json)), path=path)) dump_zip.writestr("manifest.xml", manifest.as_xml()) dump_zip.close() end = datetime.datetime.utcnow() zip_size = os.stat(tmp_location).st_size click.echo("Finished at {}, total time {} min, size={}".format( end.ctime(), (end-start).seconds / 60.0, i)) return {"date": datetime.datetime.utcnow().isoformat(), "size": zip_size, "errors": errors} @app.template_filter("pretty_num") def nice_number(raw_number): if raw_number is None: return '' return "{:,}".format(int(raw_number)) @app.errorhandler(404) def page_not_found(e): return render_template("404.html", error=e), 404 @app.route("/") def home(): """Default page""" result = CONNECTIONS.datastore.query( "SELECT (COUNT(*) as ?count) WHERE {?s ?p ?o }") count = result[0].get("count").get("value") if int(count) < 1: flash("Triplestore is empty, please load service hub RDF data") return render_template("index.html", version=__version__, count="{:,}".format(int(count))) @app.route("/reports/") @app.route("/reports/<path:name>") def reporting(name=None): if name is None: return render_template("reports/index.html") report_output = reports.report_router(name) if report_output is None: abort(404) return render_template( "reports/{0}.html".format(name), data=report_output) @app.route("/<path:type_of>/<path:name>") def authority_view(type_of, name=None): """Generates a RDF:Description view for Service Hub name, topic, agent, and other types of BIBFRAME entities Args: type_of(str): Type of entity name(str): slug of name, title, or other textual identifier """ if name is None: # Display brows view of authorities return "Browse display for {}".format(type_of) uri = "{0}{1}/{2}".format(app.config.get("BASE_URL"), type_of, name) entity_sparql = PREFIX + """ SELECT DISTINCT ?label ?value WHERE {{ <{entity}> rdf:type {type_of} . OPTIONAL {{ <{entity}> rdfs:label ?label }} OPTIONAL {{ <{entity}> rdf:value ?value }} }}""".format(entity=uri, type_of="bf:{}".format(type_of.title())) entity_results = __run_query__(entity_sparql) if len(entity_results) < 1: abort(404) entity_graph = rdflib.Graph() iri = rdflib.URIRef(uri) entity_graph.add((iri, rdflib.RDF.type, getattr(BF, type_of.title()))) for row in entity_results: if 'label' in row: literal = rdflib.Literal(row.get('label').get('value'), datatype=row.get('label').get('datatype')) entity_graph.add((iri, rdflib.RDFS.label, literal)) if 'value' in row: literal = rdflib.Literal(row.get('value').get('value'), datatype=row.get('value').get('datatype')) entity_graph.add((iri, rdflib.RDF.value, literal)) MAPv4_context["bf"] = str(BF) raw_entity = entity_graph.serialize(format='json-ld', context=MAPv4_context) return Response(raw_entity, mimetype="application/json") @app.route("/capabilitylist.xml") def capability_list(): cap_list = CapabilityList() cap_list.modified = __get_mod_date__() cap_list.ln.append({"href": url_for('capability_list'), "rel": "describedby", "type": "application/xml"}) cap_list.add(Resource(url_for('site_index'), capability="resourcelist")) cap_list.add(Resource(url_for('resource_dump'), capability="resourcedump")) return Response(cap_list.as_xml(), mimetype="text/xml") @app.route("/resourcedump.xml") def resource_dump(): xml = __generate_resource_dump__() return Response(xml.as_xml(), "text/xml") @app.route("/resourcedump-<int:count>.zip") def resource_zip(count): zip_location = os.path.join(app.config.get("DIRECTORIES")[0].get("path"), "dump/resour{}".format(file_name)) zip_location = os.path.join(PROJECT_BASE, "dump/{}.zip".format(count)) if not os.path.exists(zip_location): abort(404) return send_file(zip_location) @app.route("/siteindex.xml") #@cache.cached(timeout=86400) # Cached for 1 day def site_index(): """Generates siteindex XML, each sitemap has a maximum of 50k links dynamically generates the necessary number of sitemaps in the template""" result = CONNECTIONS.datastore.query("""SELECT (count(?work) as ?count) WHERE { ?work rdf:type bf:Work . ?instance bf:instanceOf ?work . ?item bf:itemOf ?instance . }""") count = int(result[0].get('count').get('value')) shards = math.ceil(count/50000) mod_date = app.config.get('MOD_DATE') if mod_date is None: mod_date=datetime.datetime.utcnow().strftime("%Y-%m-%d") xml = render_template("siteindex.xml", count=range(1, shards+1), last_modified=mod_date) return Response(xml, mimetype="text/xml") @app.route("/sitemap<int:offset>.xml", methods=["GET"]) #@cache.cached(timeout=86400) def sitemap(offset=0): if offset > 0: offset = offset - 1 instances = __get_instances__(offset) resource_list = ResourceList() dedups = 0 for i,row in enumerate(instances): instance = row.get('instance') if "date" in row: last_mod = row.get("date").get("value")[0:10] else: last_mod = datetime.datetime.utcnow().strftime( W3C_DATE) try: resource_list.add( Resource("{}.json".format(instance.get("value")), lastmod=last_mod) ) except ResourceListDupeError: dedups += 1 continue xml = resource_list.as_xml() return Response(xml, mimetype="text/xml") @app.route("/<path:uid>.json") def detail(uid=None): """Generates DPLA Map V4 JSON-LD""" if uid.startswith('favicon'): return '' click.echo("UID is {}".format(uid)) if uid is None: abort(404) uri = app.config.get("BASE_URL") + uid raw_map_4 = __generate_profile__(uri) return Response(raw_map_4, mimetype="application/json") if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')
KnowledgeLinks/dpla-service-hub
api.py
Python
apache-2.0
14,727
package ru.job4j.convertation; import java.util.ArrayList; import java.util.List; public class ConvertList { public ArrayList<Integer> toList(int[][] array) { ArrayList<Integer> list = new ArrayList<>(); for (int i = 0; i < array.length; i++) { for (int j = 0; j < array.length; j++) { list.add(array[i][j]); } } return list; } public int[][] toArray(ArrayList<Integer> list, int rows) { int[][] array = new int[rows][rows]; int mod = list.size() % rows; for (int i = 0; i < mod; i++) { list.add(0); } int[] arr = list.stream().mapToInt(i->i).toArray(); int temp = -1; for (int i = 0; i < arr.length; i++) { if ((i % rows) == 0) temp++; array[temp][i % rows] = arr[i]; } return array; } public List<Integer> convert(List<int[]> list) { List<Integer> result = new ArrayList<Integer>(); for (int i = 0; i < list.size(); i++) { for (Integer elem : list.get(i)) { result.add(elem); } } return result; } }
Clydeside/ALipatov
chapter_003/src/main/java/ru/job4j/convertation/ConvertList.java
Java
apache-2.0
1,197
/** * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved. */ package com.cn.jee.modules.qrtz.web; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.cn.jee.common.config.Global; import com.cn.jee.common.persistence.Page; import com.cn.jee.common.utils.StringUtils; import com.cn.jee.common.web.BaseController; import com.cn.jee.modules.qrtz.entity.QrtzJobDetails; import com.cn.jee.modules.qrtz.service.QrtzJobDetailsService; /** * 触发器Job明细Controller * * @author 1002360 * @version 2017-03-18 */ @Controller @RequestMapping(value = "${adminPath}/qrtz/qrtzJobDetails") public class QrtzJobDetailsController extends BaseController { @Autowired private QrtzJobDetailsService qrtzJobDetailsService; @ModelAttribute public QrtzJobDetails get(@RequestParam(value = "schedName", required = false) String schedName, @RequestParam(value = "jobName", required = false) String jobName, @RequestParam(value = "jobGroup", required = false) String jobGroup) { QrtzJobDetails entity = null; if (StringUtils.isNotBlank(schedName) && StringUtils.isNotBlank(jobName) && StringUtils.isNotBlank(jobGroup)) { entity = qrtzJobDetailsService.get(schedName, jobName, jobGroup); } if (entity == null) { entity = new QrtzJobDetails(); } return entity; } @RequiresPermissions("qrtz:qrtzJobDetails:view") @RequestMapping(value = { "list", "" }) public String list(QrtzJobDetails qrtzJobDetails, HttpServletRequest request, HttpServletResponse response, Model model) { Page<QrtzJobDetails> page = qrtzJobDetailsService.findPage(new Page<QrtzJobDetails>(request, response), qrtzJobDetails); model.addAttribute("page", page); return "modules/qrtz/qrtzJobDetailsList"; } @RequiresPermissions("qrtz:qrtzJobDetails:view") @RequestMapping(value = "form") public String form(QrtzJobDetails qrtzJobDetails, Model model) { model.addAttribute("qrtzJobDetails", qrtzJobDetails); return "modules/qrtz/qrtzJobDetailsForm"; } @RequiresPermissions("qrtz:qrtzJobDetails:edit") @RequestMapping(value = "save") public String save(QrtzJobDetails qrtzJobDetails, Model model, RedirectAttributes redirectAttributes) { if (!beanValidator(model, qrtzJobDetails)) { return form(qrtzJobDetails, model); } qrtzJobDetailsService.save(qrtzJobDetails); addMessage(redirectAttributes, "保存任务明细成功"); return "redirect:" + Global.getAdminPath() + "/qrtz/qrtzJobDetails/?repage"; } @RequiresPermissions("qrtz:qrtzJobDetails:edit") @RequestMapping(value = "delete") public String delete(QrtzJobDetails qrtzJobDetails, RedirectAttributes redirectAttributes) { qrtzJobDetailsService.delete(qrtzJobDetails); addMessage(redirectAttributes, "删除触发器Job明细成功"); return "redirect:" + Global.getAdminPath() + "/qrtz/qrtzJobDetails/?repage"; } }
copy4dev/jee-base
src/main/java/com/cn/jee/modules/qrtz/web/QrtzJobDetailsController.java
Java
apache-2.0
3,376
package gaia3d.domain; public enum YOrN { Y, N; }
Gaia3D/mago3d
mago3d-user/src/main/java/gaia3d/domain/YOrN.java
Java
apache-2.0
52
module ZAWS class External class AWSCLI class Commands class ELB class RegisterInstancesWithLoadBalancer def initialize(shellout=nil, awscli=nil) @shellout=shellout @awscli=awscli clear_settings self end def aws @aws ||= ZAWS::External::AWSCLI::Commands::AWS.new(self) @aws end def clear_settings @lbn=nil @instances=nil self end def instances(id) @instances=id self end def load_balancer_name(name) @lbn=name self end def get_command command = "elb register-instances-with-load-balancer" command = "#{command} --load-balancer-name #{@lbn}" if @lbn command = "#{command} --instances #{@instances}" if @instances return command end end end end end end end
zynxhealth/zaws
lib/zaws/external/awscli/commands/elb/register_instances_with_load_balancer.rb
Ruby
apache-2.0
1,154
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ /** * * @param {string} component - Component name * @param {object[]} collection - Array of objects describing available content * @return {object|false} Either a found item, or false. */ function componentHasDocs(component, collection) { const item = collection.filter((c) => `${c.fileSlug}.njk` === component); return item.length > 0 ? item[0] : false; } module.exports = (eleventy) => { eleventy.addFilter('componentHasDocs', componentHasDocs); };
chromeos/chromeos.dev
lib/filters/component-has-docs.js
JavaScript
apache-2.0
1,060
package com.github.obourgain.elasticsearch.http.handler.document.termvectors; import static com.github.obourgain.elasticsearch.http.TestFilesUtils.readFromClasspath; import static org.assertj.core.api.Assertions.assertThat; import org.elasticsearch.common.bytes.BytesArray; import org.junit.Test; import com.github.obourgain.elasticsearch.http.response.entity.TermVector; import com.github.obourgain.elasticsearch.http.response.entity.TermVectorTest; public class TermVectorResponseTest { @Test public void should_parse_response() throws Exception { String json = readFromClasspath("json/termvector/termvector_response.json"); TermVectorResponse response = new TermVectorResponse().parse(new BytesArray(json)); assertTermVectorResponse(response); } public static void assertTermVectorResponse(TermVectorResponse response) { assertThat(response.getId()).isEqualTo("1"); assertThat(response.getIndex()).isEqualTo("twitter"); assertThat(response.getType()).isEqualTo("tweet"); assertThat(response.getVersion()).isEqualTo(1); TermVector termVector = response.getTermVector(); TermVectorTest.assertTermVector(termVector); TermVectorTest.assertFieldStatistics(termVector); } }
obourgain/elasticsearch-http
src/test/java/com/github/obourgain/elasticsearch/http/handler/document/termvectors/TermVectorResponseTest.java
Java
apache-2.0
1,278
/* * Copyright (C) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.eyesfree.brailleback; import android.annotation.SuppressLint; import android.content.Context; import android.content.SharedPreferences; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; import android.os.Message; import android.os.PowerManager; import android.preference.PreferenceManager; import android.support.annotation.NonNull; import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat; import android.text.Spanned; import android.util.Log; import com.googlecode.eyesfree.braille.display.BrailleInputEvent; import com.googlecode.eyesfree.braille.display.Display; import com.googlecode.eyesfree.braille.display.DisplayClient; import com.googlecode.eyesfree.braille.translate.BrailleTranslator; import com.googlecode.eyesfree.braille.translate.TranslationResult; import com.googlecode.eyesfree.brailleback.wrapping.SimpleWrapStrategy; import com.googlecode.eyesfree.brailleback.wrapping.WordWrapStrategy; import com.googlecode.eyesfree.brailleback.wrapping.WrapStrategy; import com.googlecode.eyesfree.utils.AccessibilityNodeInfoUtils; import com.googlecode.eyesfree.utils.LogUtils; import com.googlecode.eyesfree.utils.SharedPreferencesUtils; import java.util.Arrays; import java.util.Comparator; /** * Keeps track of the current display content and handles panning. */ public class DisplayManager implements Display.OnConnectionStateChangeListener, Display.OnInputEventListener, TranslatorManager.OnTablesChangedListener, SharedPreferences.OnSharedPreferenceChangeListener { /** Dot pattern used to overlay characters under a selection. */ // TODO: Make customizable. private static final int SELECTION_DOTS = 0xC0; /** Dot pattern used to overlay characters in a focused element. */ // TODO: Make customizable. private static final int FOCUS_DOTS = 0xC0; private static final long BLINK_OFF_MILLIS = 800; private static final long BLINK_ON_MILLIS = 600; /** * Callback interface for notifying interested callers when the display is * panned out of the available content. A typical reaction to such an * event would be to move focus to a different area of the screen and * display it. */ public interface OnPanOverflowListener { void onPanLeftOverflow(Content content); void onPanRightOverflow(Content content); } /** * Listener for input events that also get information about the current * display content and position mapping for commands with a positional * argument. */ public interface OnMappedInputEventListener { /** * Handles an input {@code event} that was received when * {@code content} was present on the display. * * If the input event has a positional argument, it is mapped * according to the display pan position in the content so that * it corresponds to the character that the user touched. * * {@code event} and {@code content} are owned by the caller and may * not be referenced after this method returns. * * NOTE: Since the display is updated asynchronously, there is a chance * that the actual content on the display when the user invoked * the command is different from {@code content}. */ void onMappedInputEvent(BrailleInputEvent event, Content content); } /** * Builder-like class used to construct the content to put on the display. * * This object contains a {@link CharSequence} that represents what * characters to put on the display. This sequence can be a * {@link Spannable} so that the characters can be annotated with * information about cursors and focus which will affect how the content * is presented on the display. Arbitrary java objects may also be * included in the {@link Spannable} which can be used to determine what * action to take when the user invokes key commands related to a * particular position on the display (i.e. involving a cursor routing * key). In particular, {@link AccessibilityNodeInfoCompat}s may be * included, in which case they will be recycled by the * {@link Content#recycle} method. To facilitate movement outside the * bounds of the current {@link Content}, * {@link AccessibilityNodeInfoCompat}s that represent the extent of the * content can also be added, but in that case, they are not included in * the {@link Spannable}. */ public static class Content { /** * Pan strategy that moves the display to the leftmost position. * This is the default panning strategy. */ public static final int PAN_RESET = 0; /** * Pan strategy that positions the display so that it overlaps the * start of a selection or focus mark. Falls back on {@code PAN_RESET} * if there is no selection or focus. */ public static final int PAN_CURSOR = 1; /** * Pan strategy that tries to position the display close to the * position that corresponds to the panning position in the previously * displayed content. Spans of type * {@link AccessibilityNodeInfoCompat} are used to identify the * corresponding content in the old and new display content. * Falls back on {@code SPAN_CURSOR} if a corresponding position can't * be found. */ public static final int PAN_KEEP = 2; /** * Default contraction behaviour, allow contractions unless there is a * selection span in the content. */ public static final int CONTRACT_DEFAULT = 0; /** * Allow contraction, regardless of the presence of a selection * span. */ public static final int CONTRACT_ALWAYS_ALLOW = 1; private CharSequence text; private AccessibilityNodeInfoCompat firstNode; private AccessibilityNodeInfoCompat lastNode; private int panStrategy; private int contractionMode; private boolean splitParagraphs; private boolean editable = false; public Content() { } /** Shortcut to just set text for a one-off use. */ public Content(CharSequence textArg) { text = textArg; } public Content setText(CharSequence textArg) { text = textArg; return this; } public CharSequence getText() { return text; } public Spanned getSpanned() { if (text instanceof Spanned) { return (Spanned) text; } return null; } public Content setFirstNode(AccessibilityNodeInfoCompat node) { AccessibilityNodeInfoUtils.recycleNodes(firstNode); firstNode = AccessibilityNodeInfoCompat.obtain(node); return this; } public AccessibilityNodeInfoCompat getFirstNode() { return firstNode; } public Content setLastNode(AccessibilityNodeInfoCompat node) { AccessibilityNodeInfoUtils.recycleNodes(lastNode); lastNode = AccessibilityNodeInfoCompat.obtain(node); return this; } public AccessibilityNodeInfoCompat getLastNode() { return lastNode; } public Content setPanStrategy(int strategy) { panStrategy = strategy; return this; } public int getPanStrategy() { return panStrategy; } public Content setContractionMode(int mode) { contractionMode = mode; return this; } public int getContractionMode() { return contractionMode; } public Content setSplitParagraphs(boolean value) { splitParagraphs = value; return this; } public boolean isSplitParagraphs() { return splitParagraphs; } public Content setEditable(boolean value) { editable = value; return this; } public boolean isEditable() { return editable; } /** * Translates the text content, preserving any verbatim braille that is embedded in a * BrailleSpan. The current implementation of this method only handles the first BrailleSpan; * all subsequent BrailleSpans are ignored. * * @param translator The translator used for translating the subparts of the text without * embedded BrailleSpans. * @param cursorPosition The position of the cursor; if it occurs in a section of the text * without BrailleSpans, then the final cursor position in the output braille by the * translator. Otherwise, if the cursor occurs within a BrailleSpan section, the final * cursor position in the output braille is set to the first braille cell of the * BrailleSpan. * @param computerBrailleAtCursor This parameter is passed through to the translator; if * true,then contracted translators are instructed to translate the word under the cursor * using computer braille (instead of contracted braille) to make editing easier. * @return The result of translation, possibly empty, not null. */ public TranslationResult translateWithVerbatimBraille( BrailleTranslator translator, int cursorPosition, boolean computerBrailleAtCursor) { if (translator == null) { return createEmptyTranslation(text); } // Assume that we have at most one BrailleSpan since we currently // never add more than one BrailleSpan. // Also ignore BrailleSpans with zero-length span or no braille for // now because we don't currently add such BrailleSpans. DisplaySpans.BrailleSpan brailleSpan = null; int start = -1; int end = -1; if (text instanceof Spanned) { Spanned spanned = (Spanned) text; DisplaySpans.BrailleSpan[] spans = spanned.getSpans( 0, spanned.length(), DisplaySpans.BrailleSpan.class); if (spans.length > 1) { LogUtils.log(this, Log.WARN, "More than one BrailleSpan, handling first only"); } if (spans.length != 0) { int spanStart = spanned.getSpanStart(spans[0]); int spanEnd = spanned.getSpanEnd(spans[0]); if (spans[0].braille != null && spans[0].braille.length != 0 && spanStart < spanEnd) { brailleSpan = spans[0]; start = spanStart; end = spanEnd; } } } if (brailleSpan != null) { // Chunk the text into three sections: // left: [0, start) - needs translation // mid: [start, end) - use the literal braille provided // right: [end, length) - needs translation CharSequence left = text.subSequence(0, start); TranslationResult leftTrans = translator.translate( left.toString(), cursorPosition < start ? cursorPosition : -1, cursorPosition < start && computerBrailleAtCursor); CharSequence right = text.subSequence(end, text.length()); TranslationResult rightTrans = translator.translate( right.toString(), cursorPosition >= end ? cursorPosition - end : -1, cursorPosition >= end && computerBrailleAtCursor); // If one of the left or right translations is not valid, then // we will fall back by ignoring the BrailleSpan and // translating everything normally. (Chances are that // translating the whole text will fail also, but it wouldn't // hurt to try.) if (leftTrans == null || rightTrans == null) { LogUtils.log(this, Log.ERROR, "Could not translate left or right subtranslation, " + "falling back on default translation"); return translateOrDefault(translator, cursorPosition, computerBrailleAtCursor); } int startBraille = leftTrans.getCells().length; int endBraille = startBraille + brailleSpan.braille.length; int totalBraille = endBraille + rightTrans.getCells().length; // Copy braille cells. byte[] cells = new byte[totalBraille]; System.arraycopy(leftTrans.getCells(), 0, cells, 0, leftTrans.getCells().length); System.arraycopy(brailleSpan.braille, 0, cells, startBraille, brailleSpan.braille.length); System.arraycopy(rightTrans.getCells(), 0, cells, endBraille, rightTrans.getCells().length); // Copy text-to-braille indices. int[] leftTtb = leftTrans.getTextToBraillePositions(); int[] rightTtb = rightTrans.getTextToBraillePositions(); int[] textToBraille = new int[text.length()]; System.arraycopy(leftTtb, 0, textToBraille, 0, start); for (int i = start; i < end; ++i) { textToBraille[i] = startBraille; } for (int i = end; i < textToBraille.length; ++i) { textToBraille[i] = endBraille + rightTtb[i - end]; } // Copy braille-to-text indices. int[] leftBtt = leftTrans.getBrailleToTextPositions(); int[] rightBtt = rightTrans.getBrailleToTextPositions(); int[] brailleToText = new int[cells.length]; System.arraycopy(leftBtt, 0, brailleToText, 0, startBraille); for (int i = startBraille; i < endBraille; ++i) { brailleToText[i] = start; } for (int i = endBraille; i < totalBraille; ++i) { brailleToText[i] = end + rightBtt[i - endBraille]; } // Get cursor. int cursor; if (cursorPosition < 0) { cursor = -1; } else if (cursorPosition < start) { cursor = leftTrans.getCursorPosition(); } else if (cursorPosition < end) { cursor = startBraille; } else { cursor = endBraille + rightTrans.getCursorPosition(); } return new TranslationResult(cells, textToBraille, brailleToText, cursor); } return translateOrDefault(translator, cursorPosition, computerBrailleAtCursor); } private TranslationResult translateOrDefault( @NonNull BrailleTranslator translator, int cursorPosition, boolean computerBrailleAtCursor) { TranslationResult translation = translator.translate(text.toString(), cursorPosition, computerBrailleAtCursor); if (translation != null) { return translation; } return createEmptyTranslation(text); } public void recycle() { AccessibilityNodeInfoUtils.recycleNodes(firstNode, lastNode); firstNode = lastNode = null; DisplaySpans.recycleSpans(text); text = null; } @Override public String toString() { return String.format("DisplayManager.Content {text=%s}", getText()); } } private final TranslatorManager translatorManager; private final BrailleBackService context; // Not final, because it is initialized in the handler thread. private Display display; private final OnPanOverflowListener panOverflowListener; private final Display.OnConnectionStateChangeListener connectionStateChangeListener; private final OnMappedInputEventListener mappedInputEventListener; private final DisplayHandler displayHandler; private final CallbackHandler callbackHandler; private final HandlerThread handlerThread; private final PowerManager.WakeLock wakeLock; private final SharedPreferences sharedPreferences; // Read and written in display handler thread only. private boolean connected = false; private volatile boolean isSimulatedDisplay = false; /** * Cursor position last passed to the translate method of the translator. We use this because it * is more reliable than the position maps inside contracted words. In the common case where there * is just one selection/focus on the display at the same time, this gives better results. * Otherwise, we fall back on the position map, whic is also used for keeping the pan position. */ private int cursorPositionToTranslate = 0; private TranslationResult currentTranslationResult = createEmptyTranslation(null); /** Display content without overlays for cursors, focus etc. */ private byte[] brailleContent = new byte[0]; /** Braille content, potentially with dots overlaid for cursors and focus. */ private byte[] overlaidBrailleContent = brailleContent; private boolean overlaysOn; private WrapStrategy wrapStrategy; private final WrapStrategy editingWrapStrategy = new SimpleWrapStrategy(); private WrapStrategy preferredWrapStrategy = new SimpleWrapStrategy(); private Content currentContent = new Content(""); // Displayed content, already trimmed based on the display position. // Updated in updateDisplayedContent() and used in refresh(). private byte[] displayedBraille = new byte[0]; private byte[] displayedOverlaidBraille = new byte[0]; private CharSequence displayedText = ""; private int[] displayedBrailleToTextPositions = new int[0]; private boolean blinkNeeded = false; /** * Creates an instance of this class and starts the internal thread to connect to the braille * display service. {@code contextArg} is used to connect to the display service. {@code * translator} is used for braille translation. The various listeners will be called as * appropriate and on the same thread that was used to create this object. The current thread must * have a prepared looper. */ @SuppressLint("InvalidWakeLockTag") public DisplayManager( TranslatorManager translatorManagerArg, BrailleBackService contextArg, OnPanOverflowListener panOverflowListenerArg, Display.OnConnectionStateChangeListener connectionStateChangeListenerArg, OnMappedInputEventListener mappedInputEventListenerArg) { translatorManager = translatorManagerArg; translatorManager.addOnTablesChangedListener(this); context = contextArg; panOverflowListener = panOverflowListenerArg; connectionStateChangeListener = connectionStateChangeListenerArg; mappedInputEventListener = mappedInputEventListenerArg; PowerManager pm = (PowerManager) contextArg.getSystemService(Context.POWER_SERVICE); wakeLock = pm.newWakeLock( PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "BrailleBack"); handlerThread = new HandlerThread("DisplayManager") { @Override public void onLooperPrepared() { display = new OverlayDisplay(context, new DisplayClient(context)); display.setOnConnectionStateChangeListener(DisplayManager.this); display.setOnInputEventListener(DisplayManager.this); } }; handlerThread.start(); displayHandler = new DisplayHandler(handlerThread.getLooper()); callbackHandler = new CallbackHandler(); sharedPreferences = PreferenceManager.getDefaultSharedPreferences(contextArg); sharedPreferences.registerOnSharedPreferenceChangeListener(this); updateWrapStrategyFromPreferences(); } public void shutdown() { sharedPreferences.unregisterOnSharedPreferenceChangeListener(this); displayHandler.stop(); // Block on display shutdown. We need to make sure this finishes before // we can consider DisplayManager to be shut down. try { handlerThread.join(1000 /*milis*/); } catch (InterruptedException e) { LogUtils.log(this, Log.WARN, "Display handler shutdown interrupted"); } translatorManager.removeOnTablesChangedListener(this); } /** * Asynchronously updates the display to reflect {@code content}. * {@code content} must not be modified after this function is called, and * will eventually be recycled by the display manager. */ public void setContent(Content content) { if (content == null) { throw new NullPointerException("content can't be null"); } if (content.text == null) { throw new NullPointerException("content text is null"); } displayHandler.setContent(content); } /** Returns true if the current display is simulated. */ public boolean isSimulatedDisplay() { return isSimulatedDisplay; } /** * Marks selection spans in the overlaid braille, and returns the position * in braille where the first selection begins. If there are no selection * spans, returns -1. */ private int markSelection(Spanned spanned) { DisplaySpans.SelectionSpan[] spans = spanned.getSpans(0, spanned.length(), DisplaySpans.SelectionSpan.class); int selectionStart = -1; for (DisplaySpans.SelectionSpan span : spans) { int start = textToDisplayPosition( currentTranslationResult, cursorPositionToTranslate, spanned.getSpanStart(span)); int end = textToDisplayPosition( currentTranslationResult, cursorPositionToTranslate, spanned.getSpanEnd(span)); if (start == -1 || end == -1) { return -1; } if (start == end) { end = start + 1; } if (end > brailleContent.length) { extendContentForCursor(); } copyOverlaidContent(); for (int i = start; i < end && i < overlaidBrailleContent.length; ++i) { overlaidBrailleContent[i] |= (byte) SELECTION_DOTS; } if (selectionStart == -1) { selectionStart = start; } } return selectionStart; } /** * Makes sure that the overlaid content has its own copy. Call before * adding overlay dots. */ private void copyOverlaidContent() { if (overlaidBrailleContent == brailleContent) { overlaidBrailleContent = brailleContent.clone(); } } private void extendContentForCursor() { brailleContent = Arrays.copyOf(brailleContent, brailleContent.length + 1); // Always create a new copy of the overlaid content because there will // be a cursor, so we will need a copy anyway. overlaidBrailleContent = Arrays.copyOf(overlaidBrailleContent, overlaidBrailleContent.length + 1); } /** * Marks focus spans in the overlaid braille, and returns the position in * braille where the first focus begins. If there are no focus spans, * returns -1. */ private int markFocus(Spanned spanned) { DisplaySpans.FocusSpan[] spans = spanned.getSpans(0, spanned.length(), DisplaySpans.FocusSpan.class); int focusStart = -1; for (DisplaySpans.FocusSpan span : spans) { int start = textToDisplayPosition( currentTranslationResult, cursorPositionToTranslate, spanned.getSpanStart(span)); if (start >= 0 && start < overlaidBrailleContent.length) { copyOverlaidContent(); overlaidBrailleContent[start] |= (byte) FOCUS_DOTS; if (focusStart == -1) { focusStart = start; } } } return focusStart; } @Override public void onConnectionStateChanged(int state) { if (state == Display.STATE_CONNECTED) { connected = true; displayHandler.retranslate(); } else { connected = false; } isSimulatedDisplay = display.isSimulated(); callbackHandler.onConnectionStateChanged(state); } @Override public void onInputEvent(BrailleInputEvent event) { keepAwake(); LogUtils.log(this, Log.VERBOSE, "InputEvent: %s", event); // We're called from within the handler thread, so we forward // the call only if we are going to invoke the user's callback. switch (event.getCommand()) { case BrailleInputEvent.CMD_NAV_PAN_LEFT: panLeft(); break; case BrailleInputEvent.CMD_NAV_PAN_RIGHT: panRight(); break; default: sendMappedEvent(event); break; } } @Override public void onTablesChanged() { displayHandler.retranslate(); } private void sendMappedEvent(BrailleInputEvent event) { if (BrailleInputEvent.argumentType(event.getCommand()) == BrailleInputEvent.ARGUMENT_POSITION) { int oldArgument = event.getArgument(); // Offset argument by pan position and make sure it is less than // the next split position. int offsetArgument = oldArgument + wrapStrategy.getDisplayStart(); if (offsetArgument >= wrapStrategy.getDisplayEnd()) { // The event is outisde the currently displayed // content, drop the event. return; } // The mapped event argument is the translated offset argument. int newArgument = displayToTextPosition( currentTranslationResult, cursorPositionToTranslate, offsetArgument); // Create a new event if the argument actually differs. if (newArgument != oldArgument) { event = new BrailleInputEvent(event.getCommand(), newArgument, event.getEventTime()); } } callbackHandler.onMappedInputEvent(event); } private void panLeft() { if (wrapStrategy.panLeft()) { updateDisplayedContent(); } else { callbackHandler.onPanLeftOverflow(); } } private void panRight() { if (wrapStrategy.panRight()) { updateDisplayedContent(); } else { callbackHandler.onPanRightOverflow(); } } private class DisplayHandler extends Handler { private static final int MSG_SET_CONTENT = 1; private static final int MSG_RETRANSLATE = 2; private static final int MSG_PULSE = 3; private static final int MSG_STOP = 4; public DisplayHandler(Looper looper) { super(looper); } public void setContent(Content content) { obtainMessage(MSG_SET_CONTENT, content).sendToTarget(); } public void retranslate() { sendEmptyMessage(MSG_RETRANSLATE); } public void schedulePulse() { if (hasMessages(MSG_PULSE)) { return; } sendEmptyMessageDelayed(MSG_PULSE, overlaysOn ? BLINK_ON_MILLIS : BLINK_OFF_MILLIS); } public void cancelPulse() { removeMessages(MSG_PULSE); overlaysOn = true; } public void stop() { sendEmptyMessage(MSG_STOP); } @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_SET_CONTENT: handleSetContent((Content) msg.obj); break; case MSG_RETRANSLATE: handleRetranslate(); break; case MSG_PULSE: handlePulse(); break; case MSG_STOP: handleStop(); break; default: // Fall out. } } private void handleSetContent(Content content) { Content oldContent = currentContent; currentContent = content; updateWrapStrategy(); cursorPositionToTranslate = findCursorPosition(content); TranslationResult oldTranslationResult = currentTranslationResult; int oldDisplayStart = wrapStrategy.getDisplayStart(); translateCurrentContent(); cancelPulse(); // Adjust the pan position according to the panning strategy. // Setting the position to -1 below means that the cursor position // returned by markCursor() will be used instead; if the pan // position is >= 0, then the cursor position will be ignored. // If the pan position is -1 and the cursor position is also -1 // (no cursor), then the wrap strategy will reset the display to the // beginning of the line. int panPosition = -1; switch (content.panStrategy) { case Content.PAN_RESET: panPosition = 0; break; case Content.PAN_KEEP: if (oldContent != null) { // We don't align the display position to the size of // the display in this case so that content doesn't // jump around on the dipslay if content before the // current display position changes size. panPosition = findMatchingPanPosition( oldContent, content, oldTranslationResult, currentTranslationResult, oldDisplayStart); } break; case Content.PAN_CURSOR: break; default: LogUtils.log(this, Log.ERROR, "Unknown pan strategy: %d", content.panStrategy); } int cursorPosition = markCursor(); if (panPosition >= 0) { wrapStrategy.panTo(panPosition, false); } else { wrapStrategy.panTo(cursorPosition, true); } updateDisplayedContent(); if (oldContent != null) { // Have the callback handler recycle the old content so that // the thread in which the callbck handler is running is the // only thread modifying it. It is safe for the callback // thread to recycle the event when it receives this message // because the display handler thread will not send any more // input event containing this content and the events that // have already been sent will be processed by trhe callback // thread before the recycle message arrives because of the // guaranteed ordering of message handling. callbackHandler.recycleContent(oldContent); } } private void handleRetranslate() { if (currentContent == null) { return; } int oldTextPosition = displayToTextPosition( currentTranslationResult, cursorPositionToTranslate, wrapStrategy.getDisplayStart()); translateCurrentContent(); int panPosition = textToDisplayPosition( currentTranslationResult, cursorPositionToTranslate, oldTextPosition); int cursorPosition = markCursor(); if (panPosition >= 0) { wrapStrategy.panTo(panPosition, false); } else { wrapStrategy.panTo(cursorPosition, true); } cancelPulse(); updateDisplayedContent(); } private void handlePulse() { overlaysOn = !overlaysOn; refresh(); } private void handleStop() { display.shutdown(); handlerThread.quit(); } } private static class OnMappedInputEventArgs { public BrailleInputEvent event; public Content content; public OnMappedInputEventArgs(BrailleInputEvent eventArg, Content contentArg) { event = eventArg; content = contentArg; } } private class CallbackHandler extends Handler { private static final int MSG_ON_CONNECTION_STATE_CHANGED = 1; private static final int MSG_ON_MAPPED_INPUT_EVENT = 2; private static final int MSG_ON_PAN_LEFT_OVERFLOW = 3; private static final int MSG_ON_PAN_RIGHT_OVERFLOW = 4; private static final int MSG_RECYCLE_CONTENT = 5; public void onConnectionStateChanged(int state) { obtainMessage(MSG_ON_CONNECTION_STATE_CHANGED, state, 0) .sendToTarget(); } public void onMappedInputEvent(BrailleInputEvent event) { OnMappedInputEventArgs args = new OnMappedInputEventArgs(event, currentContent); obtainMessage(MSG_ON_MAPPED_INPUT_EVENT, args).sendToTarget(); } public void onPanLeftOverflow() { obtainMessage(MSG_ON_PAN_LEFT_OVERFLOW, currentContent).sendToTarget(); } public void onPanRightOverflow() { obtainMessage(MSG_ON_PAN_RIGHT_OVERFLOW, currentContent).sendToTarget(); } public void recycleContent(Content content) { obtainMessage(MSG_RECYCLE_CONTENT, content).sendToTarget(); } @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_ON_CONNECTION_STATE_CHANGED: handleOnConnectionStateChanged(msg.arg1); break; case MSG_ON_MAPPED_INPUT_EVENT: OnMappedInputEventArgs args = (OnMappedInputEventArgs) msg.obj; handleOnMappedInputEvent(args.event, args.content); break; case MSG_ON_PAN_LEFT_OVERFLOW: handleOnPanLeftOverflow((Content) msg.obj); break; case MSG_ON_PAN_RIGHT_OVERFLOW: handleOnPanRightOverflow((Content) msg.obj); break; case MSG_RECYCLE_CONTENT: handleRecycleContent((Content) msg.obj); break; default: // Fall out. } } private void handleOnConnectionStateChanged(int state) { connectionStateChangeListener.onConnectionStateChanged(state); } private void handleOnMappedInputEvent(BrailleInputEvent event, Content content) { mappedInputEventListener.onMappedInputEvent(event, content); } private void handleOnPanLeftOverflow(Content content) { panOverflowListener.onPanLeftOverflow(content); } private void handleOnPanRightOverflow(Content content) { panOverflowListener.onPanRightOverflow(content); } private void handleRecycleContent(Content content) { content.recycle(); } } private void translateCurrentContent() { // Use the current translator, whether contracted or uncontracted, for // editing text, but instruct contracted translaters to uncontract // the braille for the word under the cursor. BrailleTranslator translator = translatorManager.getTranslator(); currentTranslationResult = currentContent.translateWithVerbatimBraille( translator, cursorPositionToTranslate, uncontractBrailleAtCursor(currentContent)); // Make very sure we do not call getCells() on a null translation. // translateWithVerbatimBraille() currently should never return null. if (currentTranslationResult == null) { LogUtils.log(this, Log.ERROR, "currentTranslationResult is null"); currentTranslationResult = createEmptyTranslation(currentContent.getText()); } wrapStrategy.setContent(currentContent, currentTranslationResult, getNumTextCells()); brailleContent = currentTranslationResult.getCells(); overlaidBrailleContent = brailleContent; } private static TranslationResult createEmptyTranslation(CharSequence text) { int textLength = (text == null) ? 0 : text.length(); return new TranslationResult(new byte[0], new int[textLength], new int[0], 0); } /** * Marks the selection or focus cursor (in that priority), and returns the * position in braille of the selection or focus cursor if one exists. If no * selection or focus cursor exists, then returns -1. */ private int markCursor() { Spanned spanned = currentContent.getSpanned(); if (spanned != null) { int selectionPosition = markSelection(spanned); if (selectionPosition != -1) { return selectionPosition; } int focusPosition = markFocus(spanned); if (focusPosition != -1) { return focusPosition; } } return -1; } private void updateDisplayedContent() { if (!connected || currentContent == null) { return; } int displayStart = wrapStrategy.getDisplayStart(); int displayEnd = wrapStrategy.getDisplayEnd(); if (displayEnd < displayStart) { return; } // Compute equivalent text and mapping. int[] brailleToTextPositions = currentTranslationResult.getBrailleToTextPositions(); int textLeft = displayStart >= brailleToTextPositions.length ? 0 : brailleToTextPositions[displayStart]; int textRight = displayEnd >= brailleToTextPositions.length ? currentContent.text.length() : brailleToTextPositions[displayEnd]; // TODO: Prevent out of order brailleToTextPositions. if (textRight < textLeft) { textRight = textLeft; } StringBuilder newText = new StringBuilder(currentContent.text.subSequence(textLeft, textRight)); int[] trimmedBrailleToTextPositions = new int[displayEnd - displayStart]; for (int i = 0; i < trimmedBrailleToTextPositions.length; i++) { if (displayStart + i < brailleToTextPositions.length) { trimmedBrailleToTextPositions[i] = brailleToTextPositions[displayStart + i] - textLeft; } else { trimmedBrailleToTextPositions[i] = newText.length(); newText.append(' '); } } // Store all data needed by refresh(). displayedBraille = Arrays.copyOfRange(brailleContent, displayStart, displayEnd); if (brailleContent != overlaidBrailleContent) { displayedOverlaidBraille = Arrays.copyOfRange(overlaidBrailleContent, displayStart, displayEnd); } else { displayedOverlaidBraille = displayedBraille; } displayedText = newText.toString(); displayedBrailleToTextPositions = trimmedBrailleToTextPositions; blinkNeeded = blinkNeeded(); refresh(); } private void refresh() { if (!connected) { return; } byte[] toDisplay = overlaysOn ? displayedOverlaidBraille : displayedBraille; display.displayDots(toDisplay, displayedText, displayedBrailleToTextPositions); if (blinkNeeded) { displayHandler.schedulePulse(); } else { displayHandler.cancelPulse(); } } /** * Returns {@code true} if the current display content is such that it * requires blinking. */ private boolean blinkNeeded() { if (brailleContent == overlaidBrailleContent) { return false; } int start = wrapStrategy.getDisplayStart(); int end = wrapStrategy.getDisplayEnd(); for (int i = start; i < end; ++i) { if (brailleContent[i] != overlaidBrailleContent[i]) { return true; } } return false; } /** * Keeps the phone awake as if there was a 'user activity' registered * by the system. */ private void keepAwake() { // Acquiring the lock and immediately releasing it keesp the phone // awake. We don't use aqcuire() with a timeout because it just // adds an unnecessary context switch. wakeLock.acquire(); wakeLock.release(); } /** * Returns the size of the connected display, or {@code 1} if * no display is connected. */ private int getNumTextCells() { if (!connected) { return 1; } return display.getDisplayProperties().getNumTextCells(); } private int findMatchingPanPosition( Content oldContent, Content newContent, TranslationResult oldTranslationResult, TranslationResult newTranslationResult, int oldDisplayPosition) { Spanned oldSpanned = oldContent.getSpanned(); Spanned newSpanned = newContent.getSpanned(); if (oldSpanned == null || newSpanned == null) { return -1; } // Map the current display start and past-the-end positions // to the corresponding input positions. int oldTextStart = displayToTextPosition(oldTranslationResult, -1 /*cursorPosition*/, oldDisplayPosition); int oldTextEnd = displayToTextPosition(oldTranslationResult, -1 /*cursorPosition*/, oldDisplayPosition + getNumTextCells()); // Find the nodes that overlap with the display. AccessibilityNodeInfoCompat[] displayedNodes = oldSpanned.getSpans(oldTextStart, oldTextEnd, AccessibilityNodeInfoCompat.class); Arrays.sort(displayedNodes, new ByDistanceComparator(oldSpanned, oldTextStart)); // Find corresponding node in new content. for (AccessibilityNodeInfoCompat oldNode : displayedNodes) { AccessibilityNodeInfoCompat newNode = (AccessibilityNodeInfoCompat) DisplaySpans.getEqualSpan(newSpanned, oldNode); if (newNode == null) { continue; } int oldDisplayStart = textToDisplayPosition(oldTranslationResult, -1 /*cursorPosition*/, oldSpanned.getSpanStart(oldNode)); int newDisplayStart = textToDisplayPosition(newTranslationResult, -1 /*cursorPosition*/, newSpanned.getSpanStart(newNode)); // TODO: If crashes happen here, return -1 when *DisplayStart == -1. // Offset position according to diff in node position. int newDisplayPosition = oldDisplayPosition + (newDisplayStart - oldDisplayStart); return newDisplayPosition; } return -1; } private static class ByDistanceComparator implements Comparator<AccessibilityNodeInfoCompat> { private final Spanned spanned; private final int start; public ByDistanceComparator(Spanned spannedArg, int startArg) { spanned = spannedArg; start = startArg; } @Override public int compare( AccessibilityNodeInfoCompat a, AccessibilityNodeInfoCompat b) { int aStart = spanned.getSpanStart(a); int bStart = spanned.getSpanStart(b); int aDist = Math.abs(start - aStart); int bDist = Math.abs(start - bStart); if (aDist != bDist) { return aDist - bDist; } // They are on the same distance, compare by length. int aLength = aStart + spanned.getSpanEnd(a); int bLength = bStart + spanned.getSpanEnd(b); return aLength - bLength; } } /** Returns braille character index of a text character index. May return -1. */ private static int textToDisplayPosition( TranslationResult translationResult, int cursorPosition, int textPosition) { if (textPosition == cursorPosition) { return translationResult.getCursorPosition(); // May return -1? } int[] posMap = translationResult.getTextToBraillePositions(); // May include -1? // Any position past-the-end of the position map maps to the // corresponding past-the-end position in the braille. if (textPosition >= posMap.length) { return translationResult.getBrailleToTextPositions().length; } return posMap[textPosition]; } private static int displayToTextPosition( TranslationResult translationResult, int cursorPosition, int displayPosition) { if (displayPosition == translationResult.getCursorPosition()) { return cursorPosition; } int[] posMap = translationResult.getBrailleToTextPositions(); // Any position past-the-end of the position map maps to the // corresponding past-the-end position in the braille. if (displayPosition >= posMap.length) { return translationResult.getTextToBraillePositions().length; } return posMap[displayPosition]; } private static int findCursorPosition(Content content) { Spanned spanned = content.getSpanned(); if (spanned == null) { return -1; } DisplaySpans.SelectionSpan[] selectionSpans = spanned.getSpans(0, spanned.length(), DisplaySpans.SelectionSpan.class); if (selectionSpans.length > 0) { return spanned.getSpanStart(selectionSpans[0]); } DisplaySpans.FocusSpan[] focusSpans = spanned.getSpans(0, spanned.length(), DisplaySpans.FocusSpan.class); if (focusSpans.length > 0) { return spanned.getSpanStart(focusSpans[0]); } return -1; } private boolean uncontractBrailleAtCursor(Content content) { if (content.getContractionMode() == Content.CONTRACT_ALWAYS_ALLOW) { return false; } Spanned spanned = content.getSpanned(); if (spanned == null) { return false; } DisplaySpans.SelectionSpan[] selectionSpans = spanned.getSpans(0, spanned.length(), DisplaySpans.SelectionSpan.class); return selectionSpans.length != 0; } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferencesArg, String s) { String wordWrapPrefKey = context.getString(R.string.pref_braille_word_wrap_key); if (s != null && s.equals(wordWrapPrefKey)) { updateWrapStrategyFromPreferences(); } } private void updateWrapStrategyFromPreferences() { boolean wrap = SharedPreferencesUtils.getBooleanPref( sharedPreferences, context.getResources(), R.string.pref_braille_word_wrap_key, R.bool.pref_braille_word_wrap_default); preferredWrapStrategy = wrap ? new WordWrapStrategy() : new SimpleWrapStrategy(); updateWrapStrategy(); displayHandler.retranslate(); } private void updateWrapStrategy() { boolean contentEditable = currentContent != null && currentContent.isEditable(); boolean imeOpen = context != null && context.imeNavigationMode != null && context.imeNavigationMode.isImeOpen(); boolean editing = contentEditable && imeOpen; wrapStrategy = editing ? editingWrapStrategy : preferredWrapStrategy; } }
google/brailleback
braille/brailleback/src/com/googlecode/eyesfree/brailleback/DisplayManager.java
Java
apache-2.0
48,343
/* * 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.hyracks.storage.am.lsm.invertedindex.util; import static org.junit.Assert.fail; import java.io.ByteArrayInputStream; import java.io.DataInput; import java.io.DataInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.SortedSet; import java.util.TreeSet; import org.apache.hyracks.api.dataflow.value.IBinaryComparatorFactory; import org.apache.hyracks.api.dataflow.value.ISerializerDeserializer; import org.apache.hyracks.api.exceptions.ErrorCode; import org.apache.hyracks.api.exceptions.HyracksDataException; import org.apache.hyracks.data.std.primitive.IntegerPointable; import org.apache.hyracks.data.std.util.GrowableArray; import org.apache.hyracks.dataflow.common.comm.io.ArrayTupleBuilder; import org.apache.hyracks.dataflow.common.comm.io.ArrayTupleReference; import org.apache.hyracks.dataflow.common.data.accessors.ITupleReference; import org.apache.hyracks.dataflow.common.data.marshalling.IntegerSerializerDeserializer; import org.apache.hyracks.dataflow.common.data.marshalling.ShortSerializerDeserializer; import org.apache.hyracks.dataflow.common.data.marshalling.UTF8StringSerializerDeserializer; import org.apache.hyracks.storage.am.btree.OrderedIndexTestUtils; import org.apache.hyracks.storage.am.btree.impls.RangePredicate; import org.apache.hyracks.storage.am.common.CheckTuple; import org.apache.hyracks.storage.am.common.datagen.DocumentStringFieldValueGenerator; import org.apache.hyracks.storage.am.common.datagen.IFieldValueGenerator; import org.apache.hyracks.storage.am.common.datagen.PersonNameFieldValueGenerator; import org.apache.hyracks.storage.am.common.datagen.SortedIntegerFieldValueGenerator; import org.apache.hyracks.storage.am.common.datagen.TupleGenerator; import org.apache.hyracks.storage.am.common.impls.NoOpOperationCallback; import org.apache.hyracks.storage.am.common.tuples.PermutingTupleReference; import org.apache.hyracks.storage.am.lsm.invertedindex.api.IInvertedIndex; import org.apache.hyracks.storage.am.lsm.invertedindex.api.IInvertedIndexAccessor; import org.apache.hyracks.storage.am.lsm.invertedindex.api.IInvertedIndexSearchModifier; import org.apache.hyracks.storage.am.lsm.invertedindex.api.IInvertedListCursor; import org.apache.hyracks.storage.am.lsm.invertedindex.common.LSMInvertedIndexTestHarness; import org.apache.hyracks.storage.am.lsm.invertedindex.search.InvertedIndexSearchPredicate; import org.apache.hyracks.storage.am.lsm.invertedindex.tokenizers.DelimitedUTF8StringBinaryTokenizerFactory; import org.apache.hyracks.storage.am.lsm.invertedindex.tokenizers.HashedUTF8NGramTokenFactory; import org.apache.hyracks.storage.am.lsm.invertedindex.tokenizers.HashedUTF8WordTokenFactory; import org.apache.hyracks.storage.am.lsm.invertedindex.tokenizers.IBinaryTokenizer; import org.apache.hyracks.storage.am.lsm.invertedindex.tokenizers.IBinaryTokenizerFactory; import org.apache.hyracks.storage.am.lsm.invertedindex.tokenizers.IToken; import org.apache.hyracks.storage.am.lsm.invertedindex.tokenizers.ITokenFactory; import org.apache.hyracks.storage.am.lsm.invertedindex.tokenizers.NGramUTF8StringBinaryTokenizerFactory; import org.apache.hyracks.storage.am.lsm.invertedindex.tokenizers.UTF8NGramTokenFactory; import org.apache.hyracks.storage.am.lsm.invertedindex.tokenizers.UTF8WordTokenFactory; import org.apache.hyracks.storage.am.lsm.invertedindex.util.LSMInvertedIndexTestContext.InvertedIndexType; import org.apache.hyracks.storage.common.IIndexBulkLoader; import org.apache.hyracks.storage.common.IIndexCursor; import org.apache.hyracks.storage.common.MultiComparator; @SuppressWarnings("rawtypes") public class LSMInvertedIndexTestUtils { public static final int TEST_GRAM_LENGTH = 3; public static TupleGenerator createStringDocumentTupleGen(Random rnd) throws IOException { IFieldValueGenerator[] fieldGens = new IFieldValueGenerator[2]; fieldGens[0] = new DocumentStringFieldValueGenerator(2, 10, 10000, rnd); fieldGens[1] = new SortedIntegerFieldValueGenerator(0); ISerializerDeserializer[] fieldSerdes = new ISerializerDeserializer[] { new UTF8StringSerializerDeserializer(), IntegerSerializerDeserializer.INSTANCE }; TupleGenerator tupleGen = new TupleGenerator(fieldGens, fieldSerdes, 0); return tupleGen; } public static TupleGenerator createPersonNamesTupleGen(Random rnd) throws IOException { IFieldValueGenerator[] fieldGens = new IFieldValueGenerator[2]; fieldGens[0] = new PersonNameFieldValueGenerator(rnd, 0.5f); fieldGens[1] = new SortedIntegerFieldValueGenerator(0); ISerializerDeserializer[] fieldSerdes = new ISerializerDeserializer[] { new UTF8StringSerializerDeserializer(), IntegerSerializerDeserializer.INSTANCE }; TupleGenerator tupleGen = new TupleGenerator(fieldGens, fieldSerdes, 0); return tupleGen; } private static ISerializerDeserializer[] getNonHashedIndexFieldSerdes(InvertedIndexType invIndexType) throws HyracksDataException { ISerializerDeserializer[] fieldSerdes = null; switch (invIndexType) { case INMEMORY: case ONDISK: case LSM: { fieldSerdes = new ISerializerDeserializer[] { new UTF8StringSerializerDeserializer(), IntegerSerializerDeserializer.INSTANCE }; break; } case PARTITIONED_INMEMORY: case PARTITIONED_ONDISK: case PARTITIONED_LSM: { // Such indexes also include the set-size for partitioning. fieldSerdes = new ISerializerDeserializer[] { new UTF8StringSerializerDeserializer(), ShortSerializerDeserializer.INSTANCE, IntegerSerializerDeserializer.INSTANCE }; break; } default: { throw new HyracksDataException("Unhandled inverted index type '" + invIndexType + "'."); } } return fieldSerdes; } private static ISerializerDeserializer[] getHashedIndexFieldSerdes(InvertedIndexType invIndexType) throws HyracksDataException { ISerializerDeserializer[] fieldSerdes = null; switch (invIndexType) { case INMEMORY: case ONDISK: case LSM: { fieldSerdes = new ISerializerDeserializer[] { IntegerSerializerDeserializer.INSTANCE, IntegerSerializerDeserializer.INSTANCE }; break; } case PARTITIONED_INMEMORY: case PARTITIONED_ONDISK: case PARTITIONED_LSM: { // Such indexes also include the set-size for partitioning. fieldSerdes = new ISerializerDeserializer[] { IntegerSerializerDeserializer.INSTANCE, ShortSerializerDeserializer.INSTANCE, IntegerSerializerDeserializer.INSTANCE }; break; } default: { throw new HyracksDataException("Unhandled inverted index type '" + invIndexType + "'."); } } return fieldSerdes; } public static LSMInvertedIndexTestContext createWordInvIndexTestContext(LSMInvertedIndexTestHarness harness, InvertedIndexType invIndexType) throws IOException, HyracksDataException { ISerializerDeserializer[] fieldSerdes = getNonHashedIndexFieldSerdes(invIndexType); ITokenFactory tokenFactory = new UTF8WordTokenFactory(); IBinaryTokenizerFactory tokenizerFactory = new DelimitedUTF8StringBinaryTokenizerFactory(true, false, tokenFactory); LSMInvertedIndexTestContext testCtx = LSMInvertedIndexTestContext.create(harness, fieldSerdes, fieldSerdes.length - 1, tokenizerFactory, invIndexType, null, null, null, null, null, null); return testCtx; } public static LSMInvertedIndexTestContext createHashedWordInvIndexTestContext(LSMInvertedIndexTestHarness harness, InvertedIndexType invIndexType) throws IOException, HyracksDataException { ISerializerDeserializer[] fieldSerdes = getHashedIndexFieldSerdes(invIndexType); ITokenFactory tokenFactory = new HashedUTF8WordTokenFactory(); IBinaryTokenizerFactory tokenizerFactory = new DelimitedUTF8StringBinaryTokenizerFactory(true, false, tokenFactory); LSMInvertedIndexTestContext testCtx = LSMInvertedIndexTestContext.create(harness, fieldSerdes, fieldSerdes.length - 1, tokenizerFactory, invIndexType, null, null, null, null, null, null); return testCtx; } public static LSMInvertedIndexTestContext createNGramInvIndexTestContext(LSMInvertedIndexTestHarness harness, InvertedIndexType invIndexType) throws IOException, HyracksDataException { ISerializerDeserializer[] fieldSerdes = getNonHashedIndexFieldSerdes(invIndexType); ITokenFactory tokenFactory = new UTF8NGramTokenFactory(); IBinaryTokenizerFactory tokenizerFactory = new NGramUTF8StringBinaryTokenizerFactory(TEST_GRAM_LENGTH, true, true, false, tokenFactory); LSMInvertedIndexTestContext testCtx = LSMInvertedIndexTestContext.create(harness, fieldSerdes, fieldSerdes.length - 1, tokenizerFactory, invIndexType, null, null, null, null, null, null); return testCtx; } public static LSMInvertedIndexTestContext createHashedNGramInvIndexTestContext(LSMInvertedIndexTestHarness harness, InvertedIndexType invIndexType) throws IOException, HyracksDataException { ISerializerDeserializer[] fieldSerdes = getHashedIndexFieldSerdes(invIndexType); ITokenFactory tokenFactory = new HashedUTF8NGramTokenFactory(); IBinaryTokenizerFactory tokenizerFactory = new NGramUTF8StringBinaryTokenizerFactory(TEST_GRAM_LENGTH, true, true, false, tokenFactory); LSMInvertedIndexTestContext testCtx = LSMInvertedIndexTestContext.create(harness, fieldSerdes, fieldSerdes.length - 1, tokenizerFactory, invIndexType, null, null, null, null, null, null); return testCtx; } public static void bulkLoadInvIndex(LSMInvertedIndexTestContext testCtx, TupleGenerator tupleGen, int numDocs, boolean appendOnly) throws HyracksDataException, IOException { SortedSet<CheckTuple> tmpMemIndex = new TreeSet<>(); // First generate the expected index by inserting the documents one-by-one. for (int i = 0; i < numDocs; i++) { ITupleReference tuple = tupleGen.next(); testCtx.insertCheckTuples(tuple, tmpMemIndex); } ISerializerDeserializer[] fieldSerdes = testCtx.getFieldSerdes(); // Use the expected index to bulk-load the actual index. IIndexBulkLoader bulkLoader = testCtx.getIndex().createBulkLoader(1.0f, false, numDocs, true); ArrayTupleBuilder tupleBuilder = new ArrayTupleBuilder(testCtx.getFieldSerdes().length); ArrayTupleReference tuple = new ArrayTupleReference(); Iterator<CheckTuple> checkTupleIter = tmpMemIndex.iterator(); while (checkTupleIter.hasNext()) { CheckTuple checkTuple = checkTupleIter.next(); OrderedIndexTestUtils.createTupleFromCheckTuple(checkTuple, tupleBuilder, tuple, fieldSerdes); bulkLoader.add(tuple); } bulkLoader.end(); // Add all check tuples from the temp index to the text context. testCtx.getCheckTuples().addAll(tmpMemIndex); } public static void insertIntoInvIndex(LSMInvertedIndexTestContext testCtx, TupleGenerator tupleGen, int numDocs) throws IOException { // InMemoryInvertedIndex only supports insert. for (int i = 0; i < numDocs; i++) { ITupleReference tuple = tupleGen.next(); testCtx.getIndexAccessor().insert(tuple); testCtx.insertCheckTuples(tuple, testCtx.getCheckTuples()); } } public static void deleteFromInvIndex(LSMInvertedIndexTestContext testCtx, Random rnd, int numDocsToDelete) throws HyracksDataException { List<ITupleReference> documentCorpus = testCtx.getDocumentCorpus(); for (int i = 0; i < numDocsToDelete && !documentCorpus.isEmpty(); i++) { int size = documentCorpus.size(); int tupleIndex = Math.abs(rnd.nextInt()) % size; ITupleReference deleteTuple = documentCorpus.get(tupleIndex); testCtx.getIndexAccessor().delete(deleteTuple); testCtx.deleteCheckTuples(deleteTuple, testCtx.getCheckTuples()); // Swap tupleIndex with last element. documentCorpus.set(tupleIndex, documentCorpus.get(size - 1)); documentCorpus.remove(size - 1); } } /** * Compares actual and expected indexes using the rangeSearch() method of the inverted-index accessor. */ public static void compareActualAndExpectedIndexesRangeSearch(LSMInvertedIndexTestContext testCtx) throws HyracksDataException { IInvertedIndex invIndex = (IInvertedIndex) testCtx.getIndex(); int tokenFieldCount = invIndex.getTokenTypeTraits().length; int invListFieldCount = invIndex.getInvListTypeTraits().length; IInvertedIndexAccessor invIndexAccessor = (IInvertedIndexAccessor) invIndex .createAccessor(NoOpOperationCallback.INSTANCE, NoOpOperationCallback.INSTANCE); IIndexCursor invIndexCursor = invIndexAccessor.createRangeSearchCursor(); MultiComparator tokenCmp = MultiComparator.create(invIndex.getTokenCmpFactories()); IBinaryComparatorFactory[] tupleCmpFactories = new IBinaryComparatorFactory[tokenFieldCount + invListFieldCount]; for (int i = 0; i < tokenFieldCount; i++) { tupleCmpFactories[i] = invIndex.getTokenCmpFactories()[i]; } for (int i = 0; i < invListFieldCount; i++) { tupleCmpFactories[tokenFieldCount + i] = invIndex.getInvListCmpFactories()[i]; } MultiComparator tupleCmp = MultiComparator.create(tupleCmpFactories); RangePredicate nullPred = new RangePredicate(null, null, true, true, tokenCmp, tokenCmp); invIndexAccessor.rangeSearch(invIndexCursor, nullPred); // Helpers for generating a serialized inverted-list element from a CheckTuple from the expected index. ISerializerDeserializer[] fieldSerdes = testCtx.getFieldSerdes(); ArrayTupleBuilder expectedBuilder = new ArrayTupleBuilder(fieldSerdes.length); ArrayTupleReference expectedTuple = new ArrayTupleReference(); Iterator<CheckTuple> expectedIter = testCtx.getCheckTuples().iterator(); // Compare index elements. try { while (invIndexCursor.hasNext() && expectedIter.hasNext()) { invIndexCursor.next(); ITupleReference actualTuple = invIndexCursor.getTuple(); CheckTuple expected = expectedIter.next(); OrderedIndexTestUtils.createTupleFromCheckTuple(expected, expectedBuilder, expectedTuple, fieldSerdes); if (tupleCmp.compare(actualTuple, expectedTuple) != 0) { fail("Index entries differ for token '" + expected.getField(0) + "'."); } } if (expectedIter.hasNext()) { fail("Indexes do not match. Actual index is missing entries."); } if (invIndexCursor.hasNext()) { fail("Indexes do not match. Actual index contains too many entries."); } } finally { invIndexCursor.close(); } } /** * Compares actual and expected indexes by comparing their inverted-lists one by one. Exercises the openInvertedListCursor() method of the inverted-index accessor. */ @SuppressWarnings("unchecked") public static void compareActualAndExpectedIndexes(LSMInvertedIndexTestContext testCtx) throws HyracksDataException { IInvertedIndex invIndex = (IInvertedIndex) testCtx.getIndex(); ISerializerDeserializer[] fieldSerdes = testCtx.getFieldSerdes(); MultiComparator invListCmp = MultiComparator.create(invIndex.getInvListCmpFactories()); IInvertedIndexAccessor invIndexAccessor = (IInvertedIndexAccessor) testCtx.getIndexAccessor(); int tokenFieldCount = invIndex.getTokenTypeTraits().length; int invListFieldCount = invIndex.getInvListTypeTraits().length; // All tokens that were inserted into the indexes. Iterator<Comparable> tokensIter = testCtx.getAllTokens().iterator(); // Search key for finding an inverted-list in the actual index. ArrayTupleBuilder searchKeyBuilder = new ArrayTupleBuilder(tokenFieldCount); ArrayTupleReference searchKey = new ArrayTupleReference(); // Cursor over inverted list from actual index. IInvertedListCursor actualInvListCursor = invIndexAccessor.createInvertedListCursor(); // Helpers for generating a serialized inverted-list element from a CheckTuple from the expected index. ArrayTupleBuilder expectedBuilder = new ArrayTupleBuilder(fieldSerdes.length); // Includes the token fields. ArrayTupleReference completeExpectedTuple = new ArrayTupleReference(); // Field permutation and permuting tuple reference to strip away token fields from completeExpectedTuple. int[] fieldPermutation = new int[invListFieldCount]; for (int i = 0; i < fieldPermutation.length; i++) { fieldPermutation[i] = tokenFieldCount + i; } PermutingTupleReference expectedTuple = new PermutingTupleReference(fieldPermutation); // Iterate over all tokens. Find the inverted-lists in actual and expected indexes. Compare the inverted lists, while (tokensIter.hasNext()) { Comparable token = tokensIter.next(); // Position inverted-list iterator on expected index. CheckTuple checkLowKey = new CheckTuple(tokenFieldCount, tokenFieldCount); checkLowKey.appendField(token); CheckTuple checkHighKey = new CheckTuple(tokenFieldCount, tokenFieldCount); checkHighKey.appendField(token); SortedSet<CheckTuple> expectedInvList = OrderedIndexTestUtils.getPrefixExpectedSubset(testCtx.getCheckTuples(), checkLowKey, checkHighKey); Iterator<CheckTuple> expectedInvListIter = expectedInvList.iterator(); // Position inverted-list cursor in actual index. OrderedIndexTestUtils.createTupleFromCheckTuple(checkLowKey, searchKeyBuilder, searchKey, fieldSerdes); invIndexAccessor.openInvertedListCursor(actualInvListCursor, searchKey); if (actualInvListCursor.size() != expectedInvList.size()) { fail("Actual and expected inverted lists for token '" + token.toString() + "' have different sizes. Actual size: " + actualInvListCursor.size() + ". Expected size: " + expectedInvList.size() + "."); } // Compare inverted-list elements. int count = 0; actualInvListCursor.pinPages(); try { while (actualInvListCursor.hasNext() && expectedInvListIter.hasNext()) { actualInvListCursor.next(); ITupleReference actual = actualInvListCursor.getTuple(); CheckTuple expected = expectedInvListIter.next(); OrderedIndexTestUtils.createTupleFromCheckTuple(expected, expectedBuilder, completeExpectedTuple, fieldSerdes); expectedTuple.reset(completeExpectedTuple); if (invListCmp.compare(actual, expectedTuple) != 0) { fail("Inverted lists of token '" + token + "' differ at position " + count + "."); } count++; } } finally { actualInvListCursor.unpinPages(); } } } /** * Determine the expected results with the simple ScanCount algorithm. */ public static void getExpectedResults(int[] scanCountArray, TreeSet<CheckTuple> checkTuples, ITupleReference searchDocument, IBinaryTokenizer tokenizer, ISerializerDeserializer tokenSerde, IInvertedIndexSearchModifier searchModifier, List<Integer> expectedResults, InvertedIndexType invIndexType) throws IOException { boolean isPartitioned = false; switch (invIndexType) { case INMEMORY: case ONDISK: case LSM: { isPartitioned = false; break; } case PARTITIONED_INMEMORY: case PARTITIONED_ONDISK: case PARTITIONED_LSM: { isPartitioned = true; break; } } getExpectedResults(scanCountArray, checkTuples, searchDocument, tokenizer, tokenSerde, searchModifier, expectedResults, isPartitioned); } @SuppressWarnings("unchecked") public static void getExpectedResults(int[] scanCountArray, TreeSet<CheckTuple> checkTuples, ITupleReference searchDocument, IBinaryTokenizer tokenizer, ISerializerDeserializer tokenSerde, IInvertedIndexSearchModifier searchModifier, List<Integer> expectedResults, boolean isPartitioned) throws IOException { // Reset scan count array. Arrays.fill(scanCountArray, 0); expectedResults.clear(); GrowableArray tokenData = new GrowableArray(); tokenizer.reset(searchDocument.getFieldData(0), searchDocument.getFieldStart(0), searchDocument.getFieldLength(0)); // Run though tokenizer to get number of tokens. int numQueryTokens = 0; while (tokenizer.hasNext()) { tokenizer.next(); numQueryTokens++; } short numTokensLowerBound = -1; short numTokensUpperBound = -1; int invListElementField = 1; if (isPartitioned) { numTokensLowerBound = searchModifier.getNumTokensLowerBound((short) numQueryTokens); numTokensUpperBound = searchModifier.getNumTokensUpperBound((short) numQueryTokens); invListElementField = 2; } int occurrenceThreshold = searchModifier.getOccurrenceThreshold(numQueryTokens); tokenizer.reset(searchDocument.getFieldData(0), searchDocument.getFieldStart(0), searchDocument.getFieldLength(0)); while (tokenizer.hasNext()) { tokenizer.next(); IToken token = tokenizer.getToken(); tokenData.reset(); token.serializeToken(tokenData); ByteArrayInputStream inStream = new ByteArrayInputStream(tokenData.getByteArray(), 0, tokenData.getLength()); DataInput dataIn = new DataInputStream(inStream); Comparable tokenObj = (Comparable) tokenSerde.deserialize(dataIn); CheckTuple lowKey; if (numTokensLowerBound < 0) { // Index is not partitioned, or no length filtering is possible for this search modifier. lowKey = new CheckTuple(1, 1); lowKey.appendField(tokenObj); } else { // Index is length partitioned, and search modifier supports length filtering. lowKey = new CheckTuple(2, 2); lowKey.appendField(tokenObj); lowKey.appendField(Short.valueOf(numTokensLowerBound)); } CheckTuple highKey; if (numTokensUpperBound < 0) { // Index is not partitioned, or no length filtering is possible for this search modifier. highKey = new CheckTuple(1, 1); highKey.appendField(tokenObj); } else { // Index is length partitioned, and search modifier supports length filtering. highKey = new CheckTuple(2, 2); highKey.appendField(tokenObj); highKey.appendField(Short.valueOf(numTokensUpperBound)); } // Get view over check tuples containing inverted-list corresponding to token. SortedSet<CheckTuple> invList = OrderedIndexTestUtils.getPrefixExpectedSubset(checkTuples, lowKey, highKey); Iterator<CheckTuple> invListIter = invList.iterator(); // Iterate over inverted list and update scan count array. while (invListIter.hasNext()) { CheckTuple checkTuple = invListIter.next(); Integer element = (Integer) checkTuple.getField(invListElementField); scanCountArray[element]++; } } // Run through scan count array, and see whether elements satisfy the given occurrence threshold. expectedResults.clear(); for (int i = 0; i < scanCountArray.length; i++) { if (scanCountArray[i] >= occurrenceThreshold) { expectedResults.add(i); } } } public static void testIndexSearch(LSMInvertedIndexTestContext testCtx, TupleGenerator tupleGen, Random rnd, int numDocQueries, int numRandomQueries, IInvertedIndexSearchModifier searchModifier, int[] scanCountArray) throws IOException, HyracksDataException { IInvertedIndex invIndex = testCtx.invIndex; IInvertedIndexAccessor accessor = (IInvertedIndexAccessor) invIndex .createAccessor(NoOpOperationCallback.INSTANCE, NoOpOperationCallback.INSTANCE); IBinaryTokenizer tokenizer = testCtx.getTokenizerFactory().createTokenizer(); InvertedIndexSearchPredicate searchPred = new InvertedIndexSearchPredicate(tokenizer, searchModifier); List<ITupleReference> documentCorpus = testCtx.getDocumentCorpus(); // Project away the primary-key field. int[] fieldPermutation = new int[] { 0 }; PermutingTupleReference searchDocument = new PermutingTupleReference(fieldPermutation); int numQueries = numDocQueries + numRandomQueries; for (int i = 0; i < numQueries; i++) { // If number of documents in the corpus is less than numDocQueries, then replace the remaining ones with random queries. if (i >= numDocQueries || i >= documentCorpus.size()) { // Generate a random query. ITupleReference randomQuery = tupleGen.next(); searchDocument.reset(randomQuery); } else { // Pick a random document from the corpus to use as the search query. int queryIndex = Math.abs(rnd.nextInt() % documentCorpus.size()); searchDocument.reset(documentCorpus.get(queryIndex)); } // Set query tuple in search predicate. searchPred.setQueryTuple(searchDocument); searchPred.setQueryFieldIndex(0); IIndexCursor resultCursor = accessor.createSearchCursor(false); boolean panic = false; try { accessor.search(resultCursor, searchPred); } catch (HyracksDataException e) { // ignore panic queries. if (e.getErrorCode() == ErrorCode.OCCURRENCE_THRESHOLD_PANIC_EXCEPTION) { panic = true; } else { throw e; } } try { if (!panic) { // Consume cursor and deserialize results so we can sort them. Some search cursors may not deliver the result sorted (e.g., LSM search cursor). ArrayList<Integer> actualResults = new ArrayList<>(); try { while (resultCursor.hasNext()) { resultCursor.next(); ITupleReference resultTuple = resultCursor.getTuple(); int actual = IntegerPointable.getInteger(resultTuple.getFieldData(0), resultTuple.getFieldStart(0)); actualResults.add(Integer.valueOf(actual)); } } catch (HyracksDataException e) { if (e.getErrorCode() == ErrorCode.OCCURRENCE_THRESHOLD_PANIC_EXCEPTION) { // Ignore panic queries. continue; } else { throw e; } } Collections.sort(actualResults); // Get expected results. List<Integer> expectedResults = new ArrayList<>(); LSMInvertedIndexTestUtils.getExpectedResults(scanCountArray, testCtx.getCheckTuples(), searchDocument, tokenizer, testCtx.getFieldSerdes()[0], searchModifier, expectedResults, testCtx.getInvertedIndexType()); Iterator<Integer> expectedIter = expectedResults.iterator(); Iterator<Integer> actualIter = actualResults.iterator(); while (expectedIter.hasNext() && actualIter.hasNext()) { int expected = expectedIter.next(); int actual = actualIter.next(); if (actual != expected) { fail("Query results do not match. Encountered: " + actual + ". Expected: " + expected + ""); } } if (expectedIter.hasNext()) { fail("Query results do not match. Actual results missing."); } if (actualIter.hasNext()) { fail("Query results do not match. Actual contains too many results."); } } } finally { resultCursor.close(); } } } }
heriram/incubator-asterixdb
hyracks-fullstack/hyracks/hyracks-tests/hyracks-storage-am-lsm-invertedindex-test/src/test/java/org/apache/hyracks/storage/am/lsm/invertedindex/util/LSMInvertedIndexTestUtils.java
Java
apache-2.0
31,192
/** * Copyright Acropolis Software SPRL (https://www.acrosoft.be) * * 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 be.acrosoft.gaia.shared.dispatch; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * This annotation is used on {@link Listener} implementations to indicate that instances of these * listeners should be stored as {@link java.lang.ref.WeakReference} as much as possible, allowing for * their collection even though they are registered as listeners in listener groups. * @see Listener * @see java.lang.ref.WeakReference */ @Target({ElementType.TYPE}) @Retention(value=RetentionPolicy.RUNTIME) public @interface WeakListener { }
acrosoft-be/shared
Dispatch/src/main/java/be/acrosoft/gaia/shared/dispatch/WeakListener.java
Java
apache-2.0
1,283
/******************************************************************************* * Copyright 2013-2014 Gengyu (Univer) Shi * * 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.shigengyu.hyperion.core; /** * The common interface for all compensators. Compensators need to be designed as stateless. * * @author Gengyu (Univer) Shi * */ public interface TransitionCompensator { boolean canHandle(Exception exception); TransitionCompensationResult compensate(WorkflowInstance workflowInstance); }
shigengyu/Hyperion
src/main/java/com/shigengyu/hyperion/core/TransitionCompensator.java
Java
apache-2.0
1,103
# Copyright (c) 2011 X.commerce, a business unit of eBay Inc. # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # 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. """Defines interface for DB access. Functions in this module are imported into the nova.db namespace. Call these functions from nova.db namespace, not the nova.db.api namespace. All functions in this module return objects that implement a dictionary-like interface. Currently, many of these objects are sqlalchemy objects that implement a dictionary interface. However, a future goal is to have all of these objects be simple dictionaries. """ from eventlet import tpool from oslo.config import cfg from nova.cells import rpcapi as cells_rpcapi from nova.openstack.common.db import api as db_api from nova.openstack.common.gettextutils import _ from nova.openstack.common import log as logging db_opts = [ cfg.BoolOpt('enable_new_services', default=True, help='Services to be added to the available pool on create'), cfg.StrOpt('instance_name_template', default='instance-%08x', help='Template string to be used to generate instance names'), cfg.StrOpt('snapshot_name_template', default='snapshot-%s', help='Template string to be used to generate snapshot names'), ] tpool_opts = [ cfg.BoolOpt('use_tpool', default=False, deprecated_name='dbapi_use_tpool', deprecated_group='DEFAULT', help='Enable the experimental use of thread pooling for ' 'all DB API calls'), ] CONF = cfg.CONF CONF.register_opts(db_opts) CONF.register_opts(tpool_opts, 'database') CONF.import_opt('backend', 'nova.openstack.common.db.options', group='database') _BACKEND_MAPPING = {'sqlalchemy': 'nova.db.sqlalchemy.api'} class NovaDBAPI(object): """Nova's DB API wrapper class. This wraps the oslo DB API with an option to be able to use eventlet's thread pooling. Since the CONF variable may not be loaded at the time this class is instantiated, we must look at it on the first DB API call. """ def __init__(self): self.__db_api = None @property def _db_api(self): if not self.__db_api: nova_db_api = db_api.DBAPI(CONF.database.backend, backend_mapping=_BACKEND_MAPPING) if CONF.database.use_tpool: self.__db_api = tpool.Proxy(nova_db_api) else: self.__db_api = nova_db_api return self.__db_api def __getattr__(self, key): return getattr(self._db_api, key) IMPL = NovaDBAPI() LOG = logging.getLogger(__name__) # The maximum value a signed INT type may have MAX_INT = 0x7FFFFFFF ################### def constraint(**conditions): """Return a constraint object suitable for use with some updates.""" return IMPL.constraint(**conditions) def equal_any(*values): """Return an equality condition object suitable for use in a constraint. Equal_any conditions require that a model object's attribute equal any one of the given values. """ return IMPL.equal_any(*values) def not_equal(*values): """Return an inequality condition object suitable for use in a constraint. Not_equal conditions require that a model object's attribute differs from all of the given values. """ return IMPL.not_equal(*values) ################### def service_destroy(context, service_id): """Destroy the service or raise if it does not exist.""" return IMPL.service_destroy(context, service_id) def service_get(context, service_id, with_compute_node=False): """Get a service or raise if it does not exist.""" return IMPL.service_get(context, service_id, with_compute_node=with_compute_node) def service_get_by_host_and_topic(context, host, topic): """Get a service by host it's on and topic it listens to.""" return IMPL.service_get_by_host_and_topic(context, host, topic) def service_get_all(context, disabled=None): """Get all services.""" return IMPL.service_get_all(context, disabled) def service_get_all_by_topic(context, topic): """Get all services for a given topic.""" return IMPL.service_get_all_by_topic(context, topic) def service_get_all_by_host(context, host): """Get all services for a given host.""" return IMPL.service_get_all_by_host(context, host) def service_get_by_compute_host(context, host): """Get the service entry for a given compute host. Returns the service entry joined with the compute_node entry. """ return IMPL.service_get_by_compute_host(context, host) def service_get_by_args(context, host, binary): """Get the state of a service by node name and binary.""" return IMPL.service_get_by_args(context, host, binary) def service_create(context, values): """Create a service from the values dictionary.""" return IMPL.service_create(context, values) def service_update(context, service_id, values): """Set the given properties on a service and update it. Raises NotFound if service does not exist. """ return IMPL.service_update(context, service_id, values) ################### def compute_node_get(context, compute_id): """Get a compute node by its id. :param context: The security context :param compute_id: ID of the compute node :returns: Dictionary-like object containing properties of the compute node, including its corresponding service Raises ComputeHostNotFound if compute node with the given ID doesn't exist. """ return IMPL.compute_node_get(context, compute_id) def compute_node_get_by_service_id(context, service_id): """Get a compute node by its associated service id. :param context: The security context :param service_id: ID of the associated service :returns: Dictionary-like object containing properties of the compute node, including its corresponding service and statistics Raises ServiceNotFound if service with the given ID doesn't exist. """ return IMPL.compute_node_get_by_service_id(context, service_id) def compute_node_get_all(context, no_date_fields=False): """Get all computeNodes. :param context: The security context :param no_date_fields: If set to True, excludes 'created_at', 'updated_at', 'deleted_at' and 'deleted' fields from the output, thus significantly reducing its size. Set to False by default :returns: List of dictionaries each containing compute node properties, including corresponding service """ return IMPL.compute_node_get_all(context, no_date_fields) def compute_node_search_by_hypervisor(context, hypervisor_match): """Get compute nodes by hypervisor hostname. :param context: The security context :param hypervisor_match: The hypervisor hostname :returns: List of dictionary-like objects each containing compute node properties, including corresponding service """ return IMPL.compute_node_search_by_hypervisor(context, hypervisor_match) def compute_node_create(context, values): """Create a compute node from the values dictionary. :param context: The security context :param values: Dictionary containing compute node properties :returns: Dictionary-like object containing the properties of the created node, including its corresponding service and statistics """ return IMPL.compute_node_create(context, values) def compute_node_update(context, compute_id, values): """Set the given properties on a compute node and update it. :param context: The security context :param compute_id: ID of the compute node :param values: Dictionary containing compute node properties to be updated :returns: Dictionary-like object containing the properties of the updated compute node, including its corresponding service and statistics Raises ComputeHostNotFound if compute node with the given ID doesn't exist. """ return IMPL.compute_node_update(context, compute_id, values) def compute_node_delete(context, compute_id): """Delete a compute node from the database. :param context: The security context :param compute_id: ID of the compute node Raises ComputeHostNotFound if compute node with the given ID doesn't exist. """ return IMPL.compute_node_delete(context, compute_id) def compute_node_statistics(context): """Get aggregate statistics over all compute nodes. :param context: The security context :returns: Dictionary containing compute node characteristics summed up over all the compute nodes, e.g. 'vcpus', 'free_ram_mb' etc. """ return IMPL.compute_node_statistics(context) ################### def certificate_create(context, values): """Create a certificate from the values dictionary.""" return IMPL.certificate_create(context, values) def certificate_get_all_by_project(context, project_id): """Get all certificates for a project.""" return IMPL.certificate_get_all_by_project(context, project_id) def certificate_get_all_by_user(context, user_id): """Get all certificates for a user.""" return IMPL.certificate_get_all_by_user(context, user_id) def certificate_get_all_by_user_and_project(context, user_id, project_id): """Get all certificates for a user and project.""" return IMPL.certificate_get_all_by_user_and_project(context, user_id, project_id) ################### def floating_ip_get(context, id): return IMPL.floating_ip_get(context, id) def floating_ip_get_pools(context): """Returns a list of floating ip pools.""" return IMPL.floating_ip_get_pools(context) def floating_ip_allocate_address(context, project_id, pool, auto_assigned=False): """Allocate free floating ip from specified pool and return the address. Raises if one is not available. """ return IMPL.floating_ip_allocate_address(context, project_id, pool, auto_assigned) def floating_ip_bulk_create(context, ips): """Create a lot of floating ips from the values dictionary.""" return IMPL.floating_ip_bulk_create(context, ips) def floating_ip_bulk_destroy(context, ips): """Destroy a lot of floating ips from the values dictionary.""" return IMPL.floating_ip_bulk_destroy(context, ips) def floating_ip_create(context, values): """Create a floating ip from the values dictionary.""" return IMPL.floating_ip_create(context, values) def floating_ip_deallocate(context, address): """Deallocate a floating ip by address.""" return IMPL.floating_ip_deallocate(context, address) def floating_ip_destroy(context, address): """Destroy the floating_ip or raise if it does not exist.""" return IMPL.floating_ip_destroy(context, address) def floating_ip_disassociate(context, address): """Disassociate a floating ip from a fixed ip by address. :returns: the fixed ip record joined to network record or None if the ip was not associated to an ip. """ return IMPL.floating_ip_disassociate(context, address) def floating_ip_fixed_ip_associate(context, floating_address, fixed_address, host): """Associate a floating ip to a fixed_ip by address. :returns: the fixed ip record joined to network record or None if the ip was already associated to the fixed ip. """ return IMPL.floating_ip_fixed_ip_associate(context, floating_address, fixed_address, host) def floating_ip_get_all(context): """Get all floating ips.""" return IMPL.floating_ip_get_all(context) def floating_ip_get_all_by_host(context, host): """Get all floating ips by host.""" return IMPL.floating_ip_get_all_by_host(context, host) def floating_ip_get_all_by_project(context, project_id): """Get all floating ips by project.""" return IMPL.floating_ip_get_all_by_project(context, project_id) def floating_ip_get_by_address(context, address): """Get a floating ip by address or raise if it doesn't exist.""" return IMPL.floating_ip_get_by_address(context, address) def floating_ip_get_by_fixed_address(context, fixed_address): """Get a floating ips by fixed address.""" return IMPL.floating_ip_get_by_fixed_address(context, fixed_address) def floating_ip_get_by_fixed_ip_id(context, fixed_ip_id): """Get a floating ips by fixed address.""" return IMPL.floating_ip_get_by_fixed_ip_id(context, fixed_ip_id) def floating_ip_update(context, address, values): """Update a floating ip by address or raise if it doesn't exist.""" return IMPL.floating_ip_update(context, address, values) def floating_ip_set_auto_assigned(context, address): """Set auto_assigned flag to floating ip.""" return IMPL.floating_ip_set_auto_assigned(context, address) def dnsdomain_list(context): """Get a list of all zones in our database, public and private.""" return IMPL.dnsdomain_list(context) def dnsdomain_get_all(context): """Get a list of all dnsdomains in our database.""" return IMPL.dnsdomain_get_all(context) def dnsdomain_register_for_zone(context, fqdomain, zone): """Associated a DNS domain with an availability zone.""" return IMPL.dnsdomain_register_for_zone(context, fqdomain, zone) def dnsdomain_register_for_project(context, fqdomain, project): """Associated a DNS domain with a project id.""" return IMPL.dnsdomain_register_for_project(context, fqdomain, project) def dnsdomain_unregister(context, fqdomain): """Purge associations for the specified DNS zone.""" return IMPL.dnsdomain_unregister(context, fqdomain) def dnsdomain_get(context, fqdomain): """Get the db record for the specified domain.""" return IMPL.dnsdomain_get(context, fqdomain) #################### def migration_update(context, id, values): """Update a migration instance.""" return IMPL.migration_update(context, id, values) def migration_create(context, values): """Create a migration record.""" return IMPL.migration_create(context, values) def migration_get(context, migration_id): """Finds a migration by the id.""" return IMPL.migration_get(context, migration_id) def migration_get_by_instance_and_status(context, instance_uuid, status): """Finds a migration by the instance uuid its migrating.""" return IMPL.migration_get_by_instance_and_status(context, instance_uuid, status) def migration_get_unconfirmed_by_dest_compute(context, confirm_window, dest_compute, use_slave=False): """Finds all unconfirmed migrations within the confirmation window for a specific destination compute host. """ return IMPL.migration_get_unconfirmed_by_dest_compute(context, confirm_window, dest_compute, use_slave=use_slave) def migration_get_in_progress_by_host_and_node(context, host, node): """Finds all migrations for the given host + node that are not yet confirmed or reverted. """ return IMPL.migration_get_in_progress_by_host_and_node(context, host, node) def migration_get_all_by_filters(context, filters): """Finds all migrations in progress.""" return IMPL.migration_get_all_by_filters(context, filters) #################### def fixed_ip_associate(context, address, instance_uuid, network_id=None, reserved=False): """Associate fixed ip to instance. Raises if fixed ip is not available. """ return IMPL.fixed_ip_associate(context, address, instance_uuid, network_id, reserved) def fixed_ip_associate_pool(context, network_id, instance_uuid=None, host=None): """Find free ip in network and associate it to instance or host. Raises if one is not available. """ return IMPL.fixed_ip_associate_pool(context, network_id, instance_uuid, host) def fixed_ip_create(context, values): """Create a fixed ip from the values dictionary.""" return IMPL.fixed_ip_create(context, values) def fixed_ip_bulk_create(context, ips): """Create a lot of fixed ips from the values dictionary.""" return IMPL.fixed_ip_bulk_create(context, ips) def fixed_ip_disassociate(context, address): """Disassociate a fixed ip from an instance by address.""" return IMPL.fixed_ip_disassociate(context, address) def fixed_ip_disassociate_all_by_timeout(context, host, time): """Disassociate old fixed ips from host.""" return IMPL.fixed_ip_disassociate_all_by_timeout(context, host, time) def fixed_ip_get(context, id, get_network=False): """Get fixed ip by id or raise if it does not exist. If get_network is true, also return the associated network. """ return IMPL.fixed_ip_get(context, id, get_network) def fixed_ip_get_all(context): """Get all defined fixed ips.""" return IMPL.fixed_ip_get_all(context) def fixed_ip_get_by_address(context, address, columns_to_join=None): """Get a fixed ip by address or raise if it does not exist.""" return IMPL.fixed_ip_get_by_address(context, address, columns_to_join=columns_to_join) def fixed_ip_get_by_address_detailed(context, address): """Get detailed fixed ip info by address or raise if it does not exist.""" return IMPL.fixed_ip_get_by_address_detailed(context, address) def fixed_ip_get_by_floating_address(context, floating_address): """Get a fixed ip by a floating address.""" return IMPL.fixed_ip_get_by_floating_address(context, floating_address) def fixed_ip_get_by_instance(context, instance_uuid): """Get fixed ips by instance or raise if none exist.""" return IMPL.fixed_ip_get_by_instance(context, instance_uuid) def fixed_ip_get_by_host(context, host): """Get fixed ips by compute host.""" return IMPL.fixed_ip_get_by_host(context, host) def fixed_ip_get_by_network_host(context, network_uuid, host): """Get fixed ip for a host in a network.""" return IMPL.fixed_ip_get_by_network_host(context, network_uuid, host) def fixed_ips_by_virtual_interface(context, vif_id): """Get fixed ips by virtual interface or raise if none exist.""" return IMPL.fixed_ips_by_virtual_interface(context, vif_id) def fixed_ip_update(context, address, values): """Create a fixed ip from the values dictionary.""" return IMPL.fixed_ip_update(context, address, values) #################### def virtual_interface_create(context, values): """Create a virtual interface record in the database.""" return IMPL.virtual_interface_create(context, values) def virtual_interface_get(context, vif_id): """Gets a virtual interface from the table.""" return IMPL.virtual_interface_get(context, vif_id) def virtual_interface_get_by_address(context, address): """Gets a virtual interface from the table filtering on address.""" return IMPL.virtual_interface_get_by_address(context, address) def virtual_interface_get_by_uuid(context, vif_uuid): """Gets a virtual interface from the table filtering on vif uuid.""" return IMPL.virtual_interface_get_by_uuid(context, vif_uuid) def virtual_interface_get_by_instance(context, instance_id, use_slave=False): """Gets all virtual_interfaces for instance.""" return IMPL.virtual_interface_get_by_instance(context, instance_id, use_slave=use_slave) def virtual_interface_get_by_instance_and_network(context, instance_id, network_id): """Gets all virtual interfaces for instance.""" return IMPL.virtual_interface_get_by_instance_and_network(context, instance_id, network_id) def virtual_interface_delete_by_instance(context, instance_id): """Delete virtual interface records associated with instance.""" return IMPL.virtual_interface_delete_by_instance(context, instance_id) def virtual_interface_get_all(context): """Gets all virtual interfaces from the table.""" return IMPL.virtual_interface_get_all(context) #################### def instance_create(context, values): """Create an instance from the values dictionary.""" return IMPL.instance_create(context, values) def instance_destroy(context, instance_uuid, constraint=None, update_cells=True): """Destroy the instance or raise if it does not exist.""" rv = IMPL.instance_destroy(context, instance_uuid, constraint) if update_cells: try: cells_rpcapi.CellsAPI().instance_destroy_at_top(context, rv) except Exception: LOG.exception(_("Failed to notify cells of instance destroy")) return rv def instance_get_by_uuid(context, uuid, columns_to_join=None, use_slave=False): """Get an instance or raise if it does not exist.""" return IMPL.instance_get_by_uuid(context, uuid, columns_to_join, use_slave=use_slave) def instance_get(context, instance_id, columns_to_join=None): """Get an instance or raise if it does not exist.""" return IMPL.instance_get(context, instance_id, columns_to_join=columns_to_join) def instance_get_all(context, columns_to_join=None): """Get all instances.""" return IMPL.instance_get_all(context, columns_to_join=columns_to_join) def instance_get_all_by_filters(context, filters, sort_key='created_at', sort_dir='desc', limit=None, marker=None, columns_to_join=None, use_slave=False): """Get all instances that match all filters.""" return IMPL.instance_get_all_by_filters(context, filters, sort_key, sort_dir, limit=limit, marker=marker, columns_to_join=columns_to_join, use_slave=use_slave) def instance_get_active_by_window_joined(context, begin, end=None, project_id=None, host=None): """Get instances and joins active during a certain time window. Specifying a project_id will filter for a certain project. Specifying a host will filter for instances on a given compute host. """ return IMPL.instance_get_active_by_window_joined(context, begin, end, project_id, host) def instance_get_all_by_host(context, host, columns_to_join=None, use_slave=False): """Get all instances belonging to a host.""" return IMPL.instance_get_all_by_host(context, host, columns_to_join, use_slave=use_slave) def instance_get_all_by_host_and_node(context, host, node): """Get all instances belonging to a node.""" return IMPL.instance_get_all_by_host_and_node(context, host, node) def instance_get_all_by_host_and_not_type(context, host, type_id=None): """Get all instances belonging to a host with a different type_id.""" return IMPL.instance_get_all_by_host_and_not_type(context, host, type_id) def instance_get_floating_address(context, instance_id): """Get the first floating ip address of an instance.""" return IMPL.instance_get_floating_address(context, instance_id) def instance_floating_address_get_all(context, instance_uuid): """Get all floating ip addresses of an instance.""" return IMPL.instance_floating_address_get_all(context, instance_uuid) # NOTE(hanlind): This method can be removed as conductor RPC API moves to v2.0. def instance_get_all_hung_in_rebooting(context, reboot_window): """Get all instances stuck in a rebooting state.""" return IMPL.instance_get_all_hung_in_rebooting(context, reboot_window) def instance_update(context, instance_uuid, values, update_cells=True): """Set the given properties on an instance and update it. Raises NotFound if instance does not exist. """ rv = IMPL.instance_update(context, instance_uuid, values) if update_cells: try: cells_rpcapi.CellsAPI().instance_update_at_top(context, rv) except Exception: LOG.exception(_("Failed to notify cells of instance update")) return rv # FIXME(comstud): 'update_cells' is temporary as we transition to using # objects. When everything is using Instance.save(), we can remove the # argument and the RPC to nova-cells. def instance_update_and_get_original(context, instance_uuid, values, update_cells=True, columns_to_join=None): """Set the given properties on an instance and update it. Return a shallow copy of the original instance reference, as well as the updated one. :param context: = request context object :param instance_uuid: = instance id or uuid :param values: = dict containing column values :returns: a tuple of the form (old_instance_ref, new_instance_ref) Raises NotFound if instance does not exist. """ rv = IMPL.instance_update_and_get_original(context, instance_uuid, values, columns_to_join=columns_to_join) if update_cells: try: cells_rpcapi.CellsAPI().instance_update_at_top(context, rv[1]) except Exception: LOG.exception(_("Failed to notify cells of instance update")) return rv def instance_add_security_group(context, instance_id, security_group_id): """Associate the given security group with the given instance.""" return IMPL.instance_add_security_group(context, instance_id, security_group_id) def instance_remove_security_group(context, instance_id, security_group_id): """Disassociate the given security group from the given instance.""" return IMPL.instance_remove_security_group(context, instance_id, security_group_id) #################### def instance_group_create(context, values, policies=None, metadata=None, members=None): """Create a new group with metadata. Each group will receive a unique uuid. This will be used for access to the group. """ return IMPL.instance_group_create(context, values, policies, metadata, members) def instance_group_get(context, group_uuid): """Get a specific group by id.""" return IMPL.instance_group_get(context, group_uuid) def instance_group_update(context, group_uuid, values): """Update the attributes of an group.""" return IMPL.instance_group_update(context, group_uuid, values) def instance_group_delete(context, group_uuid): """Delete an group.""" return IMPL.instance_group_delete(context, group_uuid) def instance_group_get_all(context): """Get all groups.""" return IMPL.instance_group_get_all(context) def instance_group_get_all_by_project_id(context, project_id): """Get all groups for a specific project_id.""" return IMPL.instance_group_get_all_by_project_id(context, project_id) def instance_group_metadata_add(context, group_uuid, metadata, set_delete=False): """Add metadata to the group.""" return IMPL.instance_group_metadata_add(context, group_uuid, metadata, set_delete) def instance_group_metadata_delete(context, group_uuid, key): """Delete metadata from the group.""" return IMPL.instance_group_metadata_delete(context, group_uuid, key) def instance_group_metadata_get(context, group_uuid): """Get the metadata from the group.""" return IMPL.instance_group_metadata_get(context, group_uuid) def instance_group_members_add(context, group_uuid, members, set_delete=False): """Add members to the group.""" return IMPL.instance_group_members_add(context, group_uuid, members, set_delete=set_delete) def instance_group_member_delete(context, group_uuid, instance_id): """Delete a specific member from the group.""" return IMPL.instance_group_member_delete(context, group_uuid, instance_id) def instance_group_members_get(context, group_uuid): """Get the members from the group.""" return IMPL.instance_group_members_get(context, group_uuid) def instance_group_policies_add(context, group_uuid, policies, set_delete=False): """Add policies to the group.""" return IMPL.instance_group_policies_add(context, group_uuid, policies, set_delete=set_delete) def instance_group_policy_delete(context, group_uuid, policy): """Delete a specific policy from the group.""" return IMPL.instance_group_policy_delete(context, group_uuid, policy) def instance_group_policies_get(context, group_uuid): """Get the policies from the group.""" return IMPL.instance_group_policies_get(context, group_uuid) ################### def instance_info_cache_get(context, instance_uuid): """Gets an instance info cache from the table. :param instance_uuid: = uuid of the info cache's instance """ return IMPL.instance_info_cache_get(context, instance_uuid) def instance_info_cache_update(context, instance_uuid, values): """Update an instance info cache record in the table. :param instance_uuid: = uuid of info cache's instance :param values: = dict containing column values to update """ return IMPL.instance_info_cache_update(context, instance_uuid, values) def instance_info_cache_delete(context, instance_uuid): """Deletes an existing instance_info_cache record :param instance_uuid: = uuid of the instance tied to the cache record """ return IMPL.instance_info_cache_delete(context, instance_uuid) ################### def key_pair_create(context, values): """Create a key_pair from the values dictionary.""" return IMPL.key_pair_create(context, values) def key_pair_destroy(context, user_id, name): """Destroy the key_pair or raise if it does not exist.""" return IMPL.key_pair_destroy(context, user_id, name) def key_pair_get(context, user_id, name): """Get a key_pair or raise if it does not exist.""" return IMPL.key_pair_get(context, user_id, name) def key_pair_get_all_by_user(context, user_id): """Get all key_pairs by user.""" return IMPL.key_pair_get_all_by_user(context, user_id) def key_pair_count_by_user(context, user_id): """Count number of key pairs for the given user ID.""" return IMPL.key_pair_count_by_user(context, user_id) #################### def network_associate(context, project_id, network_id=None, force=False): """Associate a free network to a project.""" return IMPL.network_associate(context, project_id, network_id, force) def network_count_reserved_ips(context, network_id): """Return the number of reserved ips in the network.""" return IMPL.network_count_reserved_ips(context, network_id) def network_create_safe(context, values): """Create a network from the values dict. The network is only returned if the create succeeds. If the create violates constraints because the network already exists, no exception is raised. """ return IMPL.network_create_safe(context, values) def network_delete_safe(context, network_id): """Delete network with key network_id. This method assumes that the network is not associated with any project """ return IMPL.network_delete_safe(context, network_id) def network_disassociate(context, network_id, disassociate_host=True, disassociate_project=True): """Disassociate the network from project or host Raises if it does not exist. """ return IMPL.network_disassociate(context, network_id, disassociate_host, disassociate_project) def network_get(context, network_id, project_only="allow_none"): """Get a network or raise if it does not exist.""" return IMPL.network_get(context, network_id, project_only=project_only) def network_get_all(context, project_only="allow_none"): """Return all defined networks.""" return IMPL.network_get_all(context, project_only) def network_get_all_by_uuids(context, network_uuids, project_only="allow_none"): """Return networks by ids.""" return IMPL.network_get_all_by_uuids(context, network_uuids, project_only=project_only) # pylint: disable=C0103 def network_in_use_on_host(context, network_id, host=None): """Indicates if a network is currently in use on host.""" return IMPL.network_in_use_on_host(context, network_id, host) def network_get_associated_fixed_ips(context, network_id, host=None): """Get all network's ips that have been associated.""" return IMPL.network_get_associated_fixed_ips(context, network_id, host) def network_get_by_uuid(context, uuid): """Get a network by uuid or raise if it does not exist.""" return IMPL.network_get_by_uuid(context, uuid) def network_get_by_cidr(context, cidr): """Get a network by cidr or raise if it does not exist.""" return IMPL.network_get_by_cidr(context, cidr) def network_get_all_by_host(context, host): """All networks for which the given host is the network host.""" return IMPL.network_get_all_by_host(context, host) def network_set_host(context, network_id, host_id): """Safely set the host for network.""" return IMPL.network_set_host(context, network_id, host_id) def network_update(context, network_id, values): """Set the given properties on a network and update it. Raises NotFound if network does not exist. """ return IMPL.network_update(context, network_id, values) ############### def quota_create(context, project_id, resource, limit, user_id=None): """Create a quota for the given project and resource.""" return IMPL.quota_create(context, project_id, resource, limit, user_id=user_id) def quota_get(context, project_id, resource, user_id=None): """Retrieve a quota or raise if it does not exist.""" return IMPL.quota_get(context, project_id, resource, user_id=user_id) def quota_get_all_by_project_and_user(context, project_id, user_id): """Retrieve all quotas associated with a given project and user.""" return IMPL.quota_get_all_by_project_and_user(context, project_id, user_id) def quota_get_all_by_project(context, project_id): """Retrieve all quotas associated with a given project.""" return IMPL.quota_get_all_by_project(context, project_id) def quota_get_all(context, project_id): """Retrieve all user quotas associated with a given project.""" return IMPL.quota_get_all(context, project_id) def quota_update(context, project_id, resource, limit, user_id=None): """Update a quota or raise if it does not exist.""" return IMPL.quota_update(context, project_id, resource, limit, user_id=user_id) ################### def quota_usage_get(context, project_id, resource, user_id=None): """Retrieve a quota usage or raise if it does not exist.""" return IMPL.quota_usage_get(context, project_id, resource, user_id=user_id) def quota_usage_get_all_by_project_and_user(context, project_id, user_id): """Retrieve all usage associated with a given resource.""" return IMPL.quota_usage_get_all_by_project_and_user(context, project_id, user_id) def quota_usage_get_all_by_project(context, project_id): """Retrieve all usage associated with a given resource.""" return IMPL.quota_usage_get_all_by_project(context, project_id) def quota_usage_update(context, project_id, user_id, resource, **kwargs): """Update a quota usage or raise if it does not exist.""" return IMPL.quota_usage_update(context, project_id, user_id, resource, **kwargs) ################### def quota_reserve(context, resources, quotas, user_quotas, deltas, expire, until_refresh, max_age, project_id=None, user_id=None): """Check quotas and create appropriate reservations.""" return IMPL.quota_reserve(context, resources, quotas, user_quotas, deltas, expire, until_refresh, max_age, project_id=project_id, user_id=user_id) def reservation_commit(context, reservations, project_id=None, user_id=None): """Commit quota reservations.""" return IMPL.reservation_commit(context, reservations, project_id=project_id, user_id=user_id) def reservation_rollback(context, reservations, project_id=None, user_id=None): """Roll back quota reservations.""" return IMPL.reservation_rollback(context, reservations, project_id=project_id, user_id=user_id) def quota_destroy_all_by_project_and_user(context, project_id, user_id): """Destroy all quotas associated with a given project and user.""" return IMPL.quota_destroy_all_by_project_and_user(context, project_id, user_id) def quota_destroy_all_by_project(context, project_id): """Destroy all quotas associated with a given project.""" return IMPL.quota_destroy_all_by_project(context, project_id) def reservation_expire(context): """Roll back any expired reservations.""" return IMPL.reservation_expire(context) ################### def ec2_volume_create(context, volume_id, forced_id=None): return IMPL.ec2_volume_create(context, volume_id, forced_id) def ec2_volume_get_by_id(context, volume_id): return IMPL.ec2_volume_get_by_id(context, volume_id) def ec2_volume_get_by_uuid(context, volume_uuid): return IMPL.ec2_volume_get_by_uuid(context, volume_uuid) def get_snapshot_uuid_by_ec2_id(context, ec2_id): return IMPL.get_snapshot_uuid_by_ec2_id(context, ec2_id) def get_ec2_snapshot_id_by_uuid(context, snapshot_id): return IMPL.get_ec2_snapshot_id_by_uuid(context, snapshot_id) def ec2_snapshot_create(context, snapshot_id, forced_id=None): return IMPL.ec2_snapshot_create(context, snapshot_id, forced_id) #################### def block_device_mapping_create(context, values, legacy=True): """Create an entry of block device mapping.""" return IMPL.block_device_mapping_create(context, values, legacy) def block_device_mapping_update(context, bdm_id, values, legacy=True): """Update an entry of block device mapping.""" return IMPL.block_device_mapping_update(context, bdm_id, values, legacy) def block_device_mapping_update_or_create(context, values, legacy=True): """Update an entry of block device mapping. If not existed, create a new entry """ return IMPL.block_device_mapping_update_or_create(context, values, legacy) def block_device_mapping_get_all_by_instance(context, instance_uuid, use_slave=False): """Get all block device mapping belonging to an instance.""" return IMPL.block_device_mapping_get_all_by_instance(context, instance_uuid, use_slave) def block_device_mapping_get_by_volume_id(context, volume_id, columns_to_join=None): """Get block device mapping for a given volume.""" return IMPL.block_device_mapping_get_by_volume_id(context, volume_id, columns_to_join) def block_device_mapping_destroy(context, bdm_id): """Destroy the block device mapping.""" return IMPL.block_device_mapping_destroy(context, bdm_id) def block_device_mapping_destroy_by_instance_and_device(context, instance_uuid, device_name): """Destroy the block device mapping.""" return IMPL.block_device_mapping_destroy_by_instance_and_device( context, instance_uuid, device_name) def block_device_mapping_destroy_by_instance_and_volume(context, instance_uuid, volume_id): """Destroy the block device mapping.""" return IMPL.block_device_mapping_destroy_by_instance_and_volume( context, instance_uuid, volume_id) #################### def security_group_get_all(context): """Get all security groups.""" return IMPL.security_group_get_all(context) def security_group_get(context, security_group_id, columns_to_join=None): """Get security group by its id.""" return IMPL.security_group_get(context, security_group_id, columns_to_join) def security_group_get_by_name(context, project_id, group_name, columns_to_join=None): """Returns a security group with the specified name from a project.""" return IMPL.security_group_get_by_name(context, project_id, group_name, columns_to_join=None) def security_group_get_by_project(context, project_id): """Get all security groups belonging to a project.""" return IMPL.security_group_get_by_project(context, project_id) def security_group_get_by_instance(context, instance_uuid): """Get security groups to which the instance is assigned.""" return IMPL.security_group_get_by_instance(context, instance_uuid) def security_group_in_use(context, group_id): """Indicates if a security group is currently in use.""" return IMPL.security_group_in_use(context, group_id) def security_group_create(context, values): """Create a new security group.""" return IMPL.security_group_create(context, values) def security_group_update(context, security_group_id, values, columns_to_join=None): """Update a security group.""" return IMPL.security_group_update(context, security_group_id, values, columns_to_join=columns_to_join) def security_group_ensure_default(context): """Ensure default security group exists for a project_id. Returns a tuple with the first element being a bool indicating if the default security group previously existed. Second element is the dict used to create the default security group. """ return IMPL.security_group_ensure_default(context) def security_group_destroy(context, security_group_id): """Deletes a security group.""" return IMPL.security_group_destroy(context, security_group_id) #################### def security_group_rule_create(context, values): """Create a new security group.""" return IMPL.security_group_rule_create(context, values) def security_group_rule_get_by_security_group(context, security_group_id, columns_to_join=None): """Get all rules for a given security group.""" return IMPL.security_group_rule_get_by_security_group( context, security_group_id, columns_to_join=columns_to_join) def security_group_rule_get_by_security_group_grantee(context, security_group_id): """Get all rules that grant access to the given security group.""" return IMPL.security_group_rule_get_by_security_group_grantee(context, security_group_id) def security_group_rule_destroy(context, security_group_rule_id): """Deletes a security group rule.""" return IMPL.security_group_rule_destroy(context, security_group_rule_id) def security_group_rule_get(context, security_group_rule_id): """Gets a security group rule.""" return IMPL.security_group_rule_get(context, security_group_rule_id) def security_group_rule_count_by_group(context, security_group_id): """Count rules in a given security group.""" return IMPL.security_group_rule_count_by_group(context, security_group_id) ################### def security_group_default_rule_get(context, security_group_rule_default_id): return IMPL.security_group_default_rule_get(context, security_group_rule_default_id) def security_group_default_rule_destroy(context, security_group_rule_default_id): return IMPL.security_group_default_rule_destroy( context, security_group_rule_default_id) def security_group_default_rule_create(context, values): return IMPL.security_group_default_rule_create(context, values) def security_group_default_rule_list(context): return IMPL.security_group_default_rule_list(context) ################### def provider_fw_rule_create(context, rule): """Add a firewall rule at the provider level (all hosts & instances).""" return IMPL.provider_fw_rule_create(context, rule) def provider_fw_rule_get_all(context): """Get all provider-level firewall rules.""" return IMPL.provider_fw_rule_get_all(context) def provider_fw_rule_destroy(context, rule_id): """Delete a provider firewall rule from the database.""" return IMPL.provider_fw_rule_destroy(context, rule_id) ################### def project_get_networks(context, project_id, associate=True): """Return the network associated with the project. If associate is true, it will attempt to associate a new network if one is not found, otherwise it returns None. """ return IMPL.project_get_networks(context, project_id, associate) ################### def console_pool_create(context, values): """Create console pool.""" return IMPL.console_pool_create(context, values) def console_pool_get_by_host_type(context, compute_host, proxy_host, console_type): """Fetch a console pool for a given proxy host, compute host, and type.""" return IMPL.console_pool_get_by_host_type(context, compute_host, proxy_host, console_type) def console_pool_get_all_by_host_type(context, host, console_type): """Fetch all pools for given proxy host and type.""" return IMPL.console_pool_get_all_by_host_type(context, host, console_type) def console_create(context, values): """Create a console.""" return IMPL.console_create(context, values) def console_delete(context, console_id): """Delete a console.""" return IMPL.console_delete(context, console_id) def console_get_by_pool_instance(context, pool_id, instance_uuid): """Get console entry for a given instance and pool.""" return IMPL.console_get_by_pool_instance(context, pool_id, instance_uuid) def console_get_all_by_instance(context, instance_uuid, columns_to_join=None): """Get consoles for a given instance.""" return IMPL.console_get_all_by_instance(context, instance_uuid, columns_to_join) def console_get(context, console_id, instance_uuid=None): """Get a specific console (possibly on a given instance).""" return IMPL.console_get(context, console_id, instance_uuid) ################## def flavor_create(context, values, projects=None): """Create a new instance type.""" return IMPL.flavor_create(context, values, projects=projects) def flavor_get_all(context, inactive=False, filters=None, sort_key='flavorid', sort_dir='asc', limit=None, marker=None): """Get all instance flavors.""" return IMPL.flavor_get_all( context, inactive=inactive, filters=filters, sort_key=sort_key, sort_dir=sort_dir, limit=limit, marker=marker) def flavor_get(context, id): """Get instance type by id.""" return IMPL.flavor_get(context, id) def flavor_get_by_name(context, name): """Get instance type by name.""" return IMPL.flavor_get_by_name(context, name) def flavor_get_by_flavor_id(context, id, read_deleted=None): """Get instance type by flavor id.""" return IMPL.flavor_get_by_flavor_id(context, id, read_deleted) def flavor_destroy(context, name): """Delete an instance type.""" return IMPL.flavor_destroy(context, name) def flavor_access_get_by_flavor_id(context, flavor_id): """Get flavor access by flavor id.""" return IMPL.flavor_access_get_by_flavor_id(context, flavor_id) def flavor_access_add(context, flavor_id, project_id): """Add flavor access for project.""" return IMPL.flavor_access_add(context, flavor_id, project_id) def flavor_access_remove(context, flavor_id, project_id): """Remove flavor access for project.""" return IMPL.flavor_access_remove(context, flavor_id, project_id) def flavor_extra_specs_get(context, flavor_id): """Get all extra specs for an instance type.""" return IMPL.flavor_extra_specs_get(context, flavor_id) def flavor_extra_specs_get_item(context, flavor_id, key): """Get extra specs by key and flavor_id.""" return IMPL.flavor_extra_specs_get_item(context, flavor_id, key) def flavor_extra_specs_delete(context, flavor_id, key): """Delete the given extra specs item.""" IMPL.flavor_extra_specs_delete(context, flavor_id, key) def flavor_extra_specs_update_or_create(context, flavor_id, extra_specs): """Create or update instance type extra specs. This adds or modifies the key/value pairs specified in the extra specs dict argument """ IMPL.flavor_extra_specs_update_or_create(context, flavor_id, extra_specs) #################### def pci_device_get_by_addr(context, node_id, dev_addr): """Get PCI device by address.""" return IMPL.pci_device_get_by_addr(context, node_id, dev_addr) def pci_device_get_by_id(context, id): """Get PCI device by id.""" return IMPL.pci_device_get_by_id(context, id) def pci_device_get_all_by_node(context, node_id): """Get all PCI devices for one host.""" return IMPL.pci_device_get_all_by_node(context, node_id) def pci_device_get_all_by_instance_uuid(context, instance_uuid): """Get PCI devices allocated to instance.""" return IMPL.pci_device_get_all_by_instance_uuid(context, instance_uuid) def pci_device_destroy(context, node_id, address): """Delete a PCI device record.""" return IMPL.pci_device_destroy(context, node_id, address) def pci_device_update(context, node_id, address, value): """Update a pci device.""" return IMPL.pci_device_update(context, node_id, address, value) ################### def cell_create(context, values): """Create a new child Cell entry.""" return IMPL.cell_create(context, values) def cell_update(context, cell_name, values): """Update a child Cell entry.""" return IMPL.cell_update(context, cell_name, values) def cell_delete(context, cell_name): """Delete a child Cell.""" return IMPL.cell_delete(context, cell_name) def cell_get(context, cell_name): """Get a specific child Cell.""" return IMPL.cell_get(context, cell_name) def cell_get_all(context): """Get all child Cells.""" return IMPL.cell_get_all(context) #################### def instance_metadata_get(context, instance_uuid): """Get all metadata for an instance.""" return IMPL.instance_metadata_get(context, instance_uuid) def instance_metadata_delete(context, instance_uuid, key): """Delete the given metadata item.""" IMPL.instance_metadata_delete(context, instance_uuid, key) def instance_metadata_update(context, instance_uuid, metadata, delete): """Update metadata if it exists, otherwise create it.""" return IMPL.instance_metadata_update(context, instance_uuid, metadata, delete) #################### def instance_system_metadata_get(context, instance_uuid): """Get all system metadata for an instance.""" return IMPL.instance_system_metadata_get(context, instance_uuid) def instance_system_metadata_update(context, instance_uuid, metadata, delete): """Update metadata if it exists, otherwise create it.""" IMPL.instance_system_metadata_update( context, instance_uuid, metadata, delete) #################### def agent_build_create(context, values): """Create a new agent build entry.""" return IMPL.agent_build_create(context, values) def agent_build_get_by_triple(context, hypervisor, os, architecture): """Get agent build by hypervisor/OS/architecture triple.""" return IMPL.agent_build_get_by_triple(context, hypervisor, os, architecture) def agent_build_get_all(context, hypervisor=None): """Get all agent builds.""" return IMPL.agent_build_get_all(context, hypervisor) def agent_build_destroy(context, agent_update_id): """Destroy agent build entry.""" IMPL.agent_build_destroy(context, agent_update_id) def agent_build_update(context, agent_build_id, values): """Update agent build entry.""" IMPL.agent_build_update(context, agent_build_id, values) #################### def bw_usage_get(context, uuid, start_period, mac, use_slave=False): """Return bw usage for instance and mac in a given audit period.""" return IMPL.bw_usage_get(context, uuid, start_period, mac) def bw_usage_get_by_uuids(context, uuids, start_period): """Return bw usages for instance(s) in a given audit period.""" return IMPL.bw_usage_get_by_uuids(context, uuids, start_period) def bw_usage_update(context, uuid, mac, start_period, bw_in, bw_out, last_ctr_in, last_ctr_out, last_refreshed=None, update_cells=True): """Update cached bandwidth usage for an instance's network based on mac address. Creates new record if needed. """ rv = IMPL.bw_usage_update(context, uuid, mac, start_period, bw_in, bw_out, last_ctr_in, last_ctr_out, last_refreshed=last_refreshed) if update_cells: try: cells_rpcapi.CellsAPI().bw_usage_update_at_top(context, uuid, mac, start_period, bw_in, bw_out, last_ctr_in, last_ctr_out, last_refreshed) except Exception: LOG.exception(_("Failed to notify cells of bw_usage update")) return rv ################### def vol_get_usage_by_time(context, begin): """Return volumes usage that have been updated after a specified time.""" return IMPL.vol_get_usage_by_time(context, begin) def vol_usage_update(context, id, rd_req, rd_bytes, wr_req, wr_bytes, instance_id, project_id, user_id, availability_zone, update_totals=False): """Update cached volume usage for a volume Creates new record if needed. """ return IMPL.vol_usage_update(context, id, rd_req, rd_bytes, wr_req, wr_bytes, instance_id, project_id, user_id, availability_zone, update_totals=update_totals) ################### def s3_image_get(context, image_id): """Find local s3 image represented by the provided id.""" return IMPL.s3_image_get(context, image_id) def s3_image_get_by_uuid(context, image_uuid): """Find local s3 image represented by the provided uuid.""" return IMPL.s3_image_get_by_uuid(context, image_uuid) def s3_image_create(context, image_uuid): """Create local s3 image represented by provided uuid.""" return IMPL.s3_image_create(context, image_uuid) #################### def aggregate_create(context, values, metadata=None): """Create a new aggregate with metadata.""" return IMPL.aggregate_create(context, values, metadata) def aggregate_get(context, aggregate_id): """Get a specific aggregate by id.""" return IMPL.aggregate_get(context, aggregate_id) def aggregate_get_by_host(context, host, key=None): """Get a list of aggregates that host belongs to.""" return IMPL.aggregate_get_by_host(context, host, key) def aggregate_metadata_get_by_host(context, host, key=None): """Get metadata for all aggregates that host belongs to. Returns a dictionary where each value is a set, this is to cover the case where there two aggregates have different values for the same key. Optional key filter """ return IMPL.aggregate_metadata_get_by_host(context, host, key) def aggregate_metadata_get_by_metadata_key(context, aggregate_id, key): """Get metadata for an aggregate by metadata key.""" return IMPL.aggregate_metadata_get_by_metadata_key(context, aggregate_id, key) def aggregate_host_get_by_metadata_key(context, key): """Get hosts with a specific metadata key metadata for all aggregates. Returns a dictionary where each key is a hostname and each value is a set of the key values return value: {machine: set( az1, az2 )} """ return IMPL.aggregate_host_get_by_metadata_key(context, key) def aggregate_update(context, aggregate_id, values): """Update the attributes of an aggregates. If values contains a metadata key, it updates the aggregate metadata too. """ return IMPL.aggregate_update(context, aggregate_id, values) def aggregate_delete(context, aggregate_id): """Delete an aggregate.""" return IMPL.aggregate_delete(context, aggregate_id) def aggregate_get_all(context): """Get all aggregates.""" return IMPL.aggregate_get_all(context) def aggregate_metadata_add(context, aggregate_id, metadata, set_delete=False): """Add/update metadata. If set_delete=True, it adds only.""" IMPL.aggregate_metadata_add(context, aggregate_id, metadata, set_delete) def aggregate_metadata_get(context, aggregate_id): """Get metadata for the specified aggregate.""" return IMPL.aggregate_metadata_get(context, aggregate_id) def aggregate_metadata_delete(context, aggregate_id, key): """Delete the given metadata key.""" IMPL.aggregate_metadata_delete(context, aggregate_id, key) def aggregate_host_add(context, aggregate_id, host): """Add host to the aggregate.""" IMPL.aggregate_host_add(context, aggregate_id, host) def aggregate_host_get_all(context, aggregate_id): """Get hosts for the specified aggregate.""" return IMPL.aggregate_host_get_all(context, aggregate_id) def aggregate_host_delete(context, aggregate_id, host): """Delete the given host from the aggregate.""" IMPL.aggregate_host_delete(context, aggregate_id, host) #################### def instance_fault_create(context, values): """Create a new Instance Fault.""" return IMPL.instance_fault_create(context, values) def instance_fault_get_by_instance_uuids(context, instance_uuids): """Get all instance faults for the provided instance_uuids.""" return IMPL.instance_fault_get_by_instance_uuids(context, instance_uuids) #################### def action_start(context, values): """Start an action for an instance.""" return IMPL.action_start(context, values) def action_finish(context, values): """Finish an action for an instance.""" return IMPL.action_finish(context, values) def actions_get(context, uuid): """Get all instance actions for the provided instance.""" return IMPL.actions_get(context, uuid) def action_get_by_request_id(context, uuid, request_id): """Get the action by request_id and given instance.""" return IMPL.action_get_by_request_id(context, uuid, request_id) def action_event_start(context, values): """Start an event on an instance action.""" return IMPL.action_event_start(context, values) def action_event_finish(context, values): """Finish an event on an instance action.""" return IMPL.action_event_finish(context, values) def action_events_get(context, action_id): """Get the events by action id.""" return IMPL.action_events_get(context, action_id) def action_event_get_by_id(context, action_id, event_id): return IMPL.action_event_get_by_id(context, action_id, event_id) #################### def get_ec2_instance_id_by_uuid(context, instance_id): """Get ec2 id through uuid from instance_id_mappings table.""" return IMPL.get_ec2_instance_id_by_uuid(context, instance_id) def get_instance_uuid_by_ec2_id(context, ec2_id): """Get uuid through ec2 id from instance_id_mappings table.""" return IMPL.get_instance_uuid_by_ec2_id(context, ec2_id) def ec2_instance_create(context, instance_uuid, id=None): """Create the ec2 id to instance uuid mapping on demand.""" return IMPL.ec2_instance_create(context, instance_uuid, id) def ec2_instance_get_by_uuid(context, instance_uuid): return IMPL.ec2_instance_get_by_uuid(context, instance_uuid) def ec2_instance_get_by_id(context, instance_id): return IMPL.ec2_instance_get_by_id(context, instance_id) #################### def task_log_end_task(context, task_name, period_beginning, period_ending, host, errors, message=None): """Mark a task as complete for a given host/time period.""" return IMPL.task_log_end_task(context, task_name, period_beginning, period_ending, host, errors, message) def task_log_begin_task(context, task_name, period_beginning, period_ending, host, task_items=None, message=None): """Mark a task as started for a given host/time period.""" return IMPL.task_log_begin_task(context, task_name, period_beginning, period_ending, host, task_items, message) def task_log_get_all(context, task_name, period_beginning, period_ending, host=None, state=None): return IMPL.task_log_get_all(context, task_name, period_beginning, period_ending, host, state) def task_log_get(context, task_name, period_beginning, period_ending, host, state=None): return IMPL.task_log_get(context, task_name, period_beginning, period_ending, host, state) #################### def archive_deleted_rows(context, max_rows=None): """Move up to max_rows rows from production tables to corresponding shadow tables. :returns: number of rows archived. """ return IMPL.archive_deleted_rows(context, max_rows=max_rows) def archive_deleted_rows_for_table(context, tablename, max_rows=None): """Move up to max_rows rows from tablename to corresponding shadow table. :returns: number of rows archived. """ return IMPL.archive_deleted_rows_for_table(context, tablename, max_rows=max_rows)
tanglei528/nova
nova/db/api.py
Python
apache-2.0
65,070
#!/usr/bin/python3 import MySQLdb import os import re db = MySQLdb.connect("etos39.cn.ao.ericsson.se","automation","automation","gerrit_data_new") # db = MySQLdb.connect("localhost","root","root","work" ) cursor = db.cursor() cursor.execute('SELECT reviewer_username FROM comments GROUP BY reviewer_username') usersList = cursor.fetchall() UM = {} for users in usersList: for user in users: if user != None: outPut = os.popen('/usr/bin/ldapsearch -x -LLL -D "uid=COVESEOS,ou=Users,ou=Internal,o=ericsson" -w 1qaz\@WSX -b "uid='+user+',ou=Users,ou=Internal,o=ericsson" -h ecd.ericsson.se -p 389|grep eriOperationalManager:|awk \'{print $2}\'','r') if outPut != None: try: param = [] param=(str(user),str(outPut.read())) rule=re.compile(r'[^a-zA-z]') username = rule.sub('',str(user)) managername = rule.sub('',param[1]) print(username) cursor.execute("""INSERT INTO person(username,manager)VALUES(%s,%s)""",(username,managername)) db.commit() except Exception as e: print e db.rollback()
KiviMao/kivi
Script/Show-Comments-story/Get-All-User.py
Python
apache-2.0
1,268
<?php switch (@$_GET['action']) { default: $query = "SELECT * FROM ix_matchs ORDER BY id DESC"; $sql = mysql_query($query); $texte='<br><table class="liste_table" cellpadding=0 cellspacing=2 align="center"> <tr> <td class="liste_titre" width=20%>Date</td> <td class="liste_titre" width=25%>Adversaire</td> <td class="liste_titre" width=15%>Type</td> <td class="liste_titre" width=20%>Score</td> <td class="liste_titre" width=10%>Détail</td> <td class="liste_titre" width=10%>Démos</td> </tr> '; while($data = mysql_fetch_array($sql)) { if ($data['score1']<$data['score2']) { $color="#FFC8C8"; $colortxt="#E71B1B"; @$perdu++; } if ($data['score1']>$data['score2']) { $color="#D0F8C8"; $colortxt="#52C174"; @$gagne++; } if ($data['score1']==$data['score2']) { $color="#C8D8FF"; $colortxt="#3A37CE"; @$egalite++; } if (!empty($data['site_adv'])) { $adversaire="<a href=\"".$data['site_adv']."\" target=\"_blank\">".$data['adversaire']."</a>"; } else { $adversaire=$data['adversaire']; } if (!empty($data['hltv'])) { $demo='<a href="'.$data['hltv'].'" target="_blank"><img src="images/video.png" border=0 style="border:1px solid #FFFFFF;" OnMouseOver="this.style.border=\'1px outset #F7A118\'" OnMouseOut="this.style.border=\'1px solid #FFFFFF\'"></a>'; } else if (!empty($data['screen'])) { $demo='<a href="'.$data['screen'].'" target="_blank"><img src="images/screen.png" border=0 style="border:1px solid #FFFFFF;" OnMouseOver="this.style.border=\'1px outset #F7A118\'" OnMouseOut="this.style.border=\'1px solid #FFFFFF\'"></a>'; } else $demo="-"; $texte.=" <tr> <td class='liste_txt'>".inverser_date($data['date'])."</td> <td class='liste_txt'>$adversaire</td> <td class='liste_txt'>".$data['type']."</td> <td class='liste_txt' bgcolor='$color'><font color='$colortxt'><b>".$data['score1']."/".$data['score2']."</b></font></td> <td class='liste_txt'><a href=\"?page=matchs&action=detail&id=".$data['id']."\"><img src='images/rapport.png' border=0 style=\"border:1px solid #FFFFFF;\" OnMouseOver=\"this.style.border='1px outset #108AFB'\" OnMouseOut=\"this.style.border='1px solid #FFFFFF'\"></a></td> <td class='liste_txt'>$demo</td> </tr>"; } $texte.="</table><p align=\"center\"><img src=\"images/carre_vert.jpg\" alt=\"\" name=\"carre_rouge\" width=\"10\" height=\"10\" id=\"carre_rouge\" /> Gagné - <img src=\"images/carre_rouge.jpg\" alt=\"\" name=\"carre_rouge\" width=\"10\" height=\"10\" id=\"carre_rouge\" /> Perdu - <img src=\"images/carre_bleu.jpg\" alt=\"\" name=\"carre_rouge\" width=\"10\" height=\"10\" id=\"carre_rouge\" /> Egalité"; $texte.="<br><br><br><b>$gagne</b> matchs gagnés, <b>$perdu</b> matchs perdus et <b>$egalite</b> égalités.<br></p>"; $afficher->AddSession($handle, "contenu"); $afficher->setVar($handle, "contenu.module_titre", "Liste des matchs"); $afficher->setVar($handle, "contenu.module_texte", $texte ); $afficher->CloseSession($handle, "contenu"); break; case "detail": $query = "SELECT * FROM ix_matchs WHERE id=".$_GET['id']; $sql = mysql_query($query); $data=mysql_fetch_object($sql); (file_exists("images/maps/" . $data->map1 . ".jpg")) ? $urlimg1="images/maps/" . $data->map1 . ".jpg" : $urlimg1="images/maps/none.jpg"; (file_exists("images/maps/" . $data->map2 . ".jpg")) ? $urlimg2="images/maps/" . $data->map2 . ".jpg" : $urlimg2="images/maps/none.jpg"; if (isset($data->map1)) { $imgmap1='<img src="'.$urlimg1.'" style="border:1px solid #000000">'; } if (isset($data->map2)) { $imgmap2='<img src="'.$urlimg2.'" style="border:1px solid #000000">'; } $maps='<table width="322" align="center" cellpadding="0" cellspacing="0" > <tr bgcolor="#000000"> <td><div align="center"><font color="#FFFFFF">Map 1 : <b>'.$data->map1.'</b></font></div></td> <td><div align="center"><font color="#FFFFFF">Map 2 : <b>'.$data->map2.'</b></font></div></td> </tr> <tr> <td>'.@$imgmap1.'</td> <td>'.@$imgmap2.'</td> </tr> </table>'; $texte='<p align="center"><br /><span class="txt2" style="font-size:13px; font-weight:bold"> D&eacute;tail du Match contre les '.$data->adversaire.'</SPAN></p> <p>'.$maps.'<br><br> <span class="txt2">Date</span> : '.inverser_date($data->date).@$case.'<br /> <span class="txt2">Type</span> : '.$data->type.'<br /> <span class="txt2">Line Up</span> : '.$data->lineup.'<br /> <span class="txt2">Score</span> : <b>'.$data->score1.'</b> / '.$data->score2.'</p> <p><span class="txt2">Rapport : </span><br /> '.$data->rapport.'<br /> <br /> <span class="txt2"> Lien D&eacute;mo </span>: <a href="'.$data->hltv.'" target="_blank">'.$data->hltv.'</a><br /> <span class="txt2">Lien Screen </span>: <a href="'.$data->screen.'" target="_blank">'.$data->screen.'</a> </p> <p align="center"><br>- Post&eacute; un commentaire - ( a venir ! )<br> </p>'; $afficher->AddSession($handle, "contenu"); $afficher->setVar($handle, "contenu.module_titre", "Détail d'un match"); $afficher->setVar($handle, "contenu.module_texte", $texte ); $afficher->CloseSession($handle, "contenu"); } ?>
studiodev/archives
2005 - PortiX-Team (CMS)/pages/matchs.php
PHP
apache-2.0
5,562
/* Copyright 2014 Rustici Software 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. */ using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Text; using System.Web; using Newtonsoft.Json.Linq; using TinCan.Documents; using TinCan.LRSResponses; namespace TinCan { public class RemoteLRS : ILRS { public Uri endpoint { get; set; } public TCAPIVersion version { get; set; } public String auth { get; set; } public Dictionary<String, String> extended { get; set; } public void SetAuth(String username, String password) { auth = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(username + ":" + password)); } public RemoteLRS() { } public RemoteLRS(Uri endpoint, TCAPIVersion version, String username, String password) { this.endpoint = endpoint; this.version = version; this.SetAuth(username, password); } public RemoteLRS(String endpoint, TCAPIVersion version, String username, String password) : this(new Uri(endpoint), version, username, password) { } public RemoteLRS(String endpoint, String username, String password) : this(endpoint, TCAPIVersion.latest(), username, password) { } private class MyHTTPRequest { public String method { get; set; } public String resource { get; set; } public Dictionary<String, String> queryParams { get; set; } public Dictionary<String, String> headers { get; set; } public String contentType { get; set; } public byte[] content { get; set; } } private class MyHTTPResponse { public HttpStatusCode status { get; set; } public String contentType { get; set; } public byte[] content { get; set; } public DateTime lastModified { get; set; } public String etag { get; set; } public Exception ex { get; set; } public MyHTTPResponse() { } public MyHTTPResponse(HttpWebResponse webResp) { status = webResp.StatusCode; contentType = webResp.ContentType; etag = webResp.Headers.Get("Etag"); lastModified = webResp.LastModified; using (var stream = webResp.GetResponseStream()) { content = ReadFully(stream, (int)webResp.ContentLength); } } } private MyHTTPResponse MakeSyncRequest(MyHTTPRequest req) { String url; if (req.resource.StartsWith("http", StringComparison.InvariantCultureIgnoreCase)) { url = req.resource; } else { url = endpoint.ToString(); if (! url.EndsWith("/") && ! req.resource.StartsWith("/")) { url += "/"; } url += req.resource; } if (req.queryParams != null) { String qs = ""; foreach (KeyValuePair<String, String> entry in req.queryParams) { if (qs != "") { qs += "&"; } qs += HttpUtility.UrlEncode(entry.Key) + "=" + HttpUtility.UrlEncode(entry.Value); } if (qs != "") { url += "?" + qs; } } // TODO: handle special properties we recognize, such as content type, modified since, etc. var webReq = (HttpWebRequest)WebRequest.Create(url); webReq.Method = req.method; webReq.Headers.Add("X-Experience-API-Version", version.ToString()); if (auth != null) { webReq.Headers.Add("Authorization", auth); } if (req.headers != null) { foreach (KeyValuePair<String, String> entry in req.headers) { webReq.Headers.Add(entry.Key, entry.Value); } } if (req.contentType != null) { webReq.ContentType = req.contentType; } else { webReq.ContentType = "application/octet-stream"; } if (req.content != null) { webReq.ContentLength = req.content.Length; using (var stream = webReq.GetRequestStream()) { stream.Write(req.content, 0, req.content.Length); } } MyHTTPResponse resp; try { using (var webResp = (HttpWebResponse)webReq.GetResponse()) { resp = new MyHTTPResponse(webResp); } } catch (WebException ex) { if (ex.Response != null) { using (var webResp = (HttpWebResponse)ex.Response) { resp = new MyHTTPResponse(webResp); } } else { resp = new MyHTTPResponse(); resp.content = Encoding.UTF8.GetBytes("Web exception without '.Response'"); } resp.ex = ex; } return resp; } /// <summary> /// See http://www.yoda.arachsys.com/csharp/readbinary.html no license found /// /// Reads data from a stream until the end is reached. The /// data is returned as a byte array. An IOException is /// thrown if any of the underlying IO calls fail. /// </summary> /// <param name="stream">The stream to read data from</param> /// <param name="initialLength">The initial buffer length</param> private static byte[] ReadFully(Stream stream, int initialLength) { // If we've been passed an unhelpful initial length, just // use 32K. if (initialLength < 1) { initialLength = 32768; } byte[] buffer = new byte[initialLength]; int read = 0; int chunk; while ((chunk = stream.Read(buffer, read, buffer.Length - read)) > 0) { read += chunk; // If we've reached the end of our buffer, check to see if there's // any more information if (read == buffer.Length) { int nextByte = stream.ReadByte(); // End of stream? If so, we're done if (nextByte == -1) { return buffer; } // Nope. Resize the buffer, put in the byte we've just // read, and continue byte[] newBuffer = new byte[buffer.Length * 2]; Array.Copy(buffer, newBuffer, buffer.Length); newBuffer[read] = (byte)nextByte; buffer = newBuffer; read++; } } // Buffer is now too big. Shrink it. byte[] ret = new byte[read]; Array.Copy(buffer, ret, read); return ret; } private MyHTTPResponse GetDocument(String resource, Dictionary<String, String> queryParams, Document document) { var req = new MyHTTPRequest(); req.method = "GET"; req.resource = resource; req.queryParams = queryParams; var res = MakeSyncRequest(req); if (res.status == HttpStatusCode.OK) { document.content = res.content; document.contentType = res.contentType; document.timestamp = res.lastModified; document.etag = res.etag; } return res; } private ProfileKeysLRSResponse GetProfileKeys(String resource, Dictionary<String, String> queryParams) { var r = new ProfileKeysLRSResponse(); var req = new MyHTTPRequest(); req.method = "GET"; req.resource = resource; req.queryParams = queryParams; var res = MakeSyncRequest(req); if (res.status != HttpStatusCode.OK) { r.success = false; r.httpException = res.ex; r.SetErrMsgFromBytes(res.content); return r; } r.success = true; var keys = JArray.Parse(Encoding.UTF8.GetString(res.content)); if (keys.Count > 0) { r.content = new List<String>(); foreach (JToken key in keys) { r.content.Add((String)key); } } return r; } private LRSResponse SaveDocument(String resource, Dictionary<String, String> queryParams, Document document) { var r = new LRSResponse(); var req = new MyHTTPRequest(); req.method = "PUT"; req.resource = resource; req.queryParams = queryParams; req.contentType = document.contentType; req.content = document.content; var res = MakeSyncRequest(req); if (res.status != HttpStatusCode.NoContent) { r.success = false; r.httpException = res.ex; r.SetErrMsgFromBytes(res.content); return r; } r.success = true; return r; } private LRSResponse DeleteDocument(String resource, Dictionary<String, String> queryParams) { var r = new LRSResponse(); var req = new MyHTTPRequest(); req.method = "DELETE"; req.resource = resource; req.queryParams = queryParams; var res = MakeSyncRequest(req); if (res.status != HttpStatusCode.NoContent) { r.success = false; r.httpException = res.ex; r.SetErrMsgFromBytes(res.content); return r; } r.success = true; return r; } private StatementLRSResponse GetStatement(Dictionary<String, String> queryParams) { var r = new StatementLRSResponse(); var req = new MyHTTPRequest(); req.method = "GET"; req.resource = "statements"; req.queryParams = queryParams; var res = MakeSyncRequest(req); if (res.status != HttpStatusCode.OK) { r.success = false; r.httpException = res.ex; r.SetErrMsgFromBytes(res.content); return r; } r.success = true; r.content = new Statement(new Json.StringOfJSON(Encoding.UTF8.GetString(res.content))); return r; } public AboutLRSResponse About() { var r = new AboutLRSResponse(); var req = new MyHTTPRequest(); req.method = "GET"; req.resource = "about"; var res = MakeSyncRequest(req); if (res.status != HttpStatusCode.OK) { r.success = false; r.httpException = res.ex; r.SetErrMsgFromBytes(res.content); return r; } r.success = true; r.content = new About(Encoding.UTF8.GetString(res.content)); return r; } public StatementLRSResponse SaveStatement(Statement statement) { var r = new StatementLRSResponse(); var req = new MyHTTPRequest(); req.queryParams = new Dictionary<String, String>(); req.resource = "statements"; if (statement.id == null) { req.method = "POST"; } else { req.method = "PUT"; req.queryParams.Add("statementId", statement.id.ToString()); } req.contentType = "application/json"; req.content = Encoding.UTF8.GetBytes(statement.ToJSON(version)); var res = MakeSyncRequest(req); if (statement.id == null) { if (res.status != HttpStatusCode.OK) { r.success = false; r.httpException = res.ex; r.SetErrMsgFromBytes(res.content); return r; } var ids = JArray.Parse(Encoding.UTF8.GetString(res.content)); statement.id = new Guid((String)ids[0]); } else { if (res.status != HttpStatusCode.NoContent) { r.success = false; r.httpException = res.ex; r.SetErrMsgFromBytes(res.content); return r; } } r.success = true; r.content = statement; return r; } public StatementsResultLRSResponse SaveStatements(List<Statement> statements) { var r = new StatementsResultLRSResponse(); var req = new MyHTTPRequest(); req.resource = "statements"; req.method = "POST"; req.contentType = "application/json"; var jarray = new JArray(); foreach (Statement st in statements) { jarray.Add(st.ToJObject(version)); } req.content = Encoding.UTF8.GetBytes(jarray.ToString()); var res = MakeSyncRequest(req); if (res.status != HttpStatusCode.OK) { r.success = false; r.httpException = res.ex; r.SetErrMsgFromBytes(res.content); return r; } var ids = JArray.Parse(Encoding.UTF8.GetString(res.content)); for (int i = 0; i < ids.Count; i++) { statements[i].id = new Guid((String)ids[i]); } r.success = true; r.content = new StatementsResult(statements); return r; } public StatementLRSResponse RetrieveStatement(Guid id) { var queryParams = new Dictionary<String, String>(); queryParams.Add("statementId", id.ToString()); return GetStatement(queryParams); } public StatementLRSResponse RetrieveVoidedStatement(Guid id) { var queryParams = new Dictionary<String, String>(); queryParams.Add("voidedStatementId", id.ToString()); return GetStatement(queryParams); } public StatementsResultLRSResponse QueryStatements(StatementsQuery query) { var r = new StatementsResultLRSResponse(); var req = new MyHTTPRequest(); req.method = "GET"; req.resource = "statements"; req.queryParams = query.ToParameterMap(version); var res = MakeSyncRequest(req); if (res.status != HttpStatusCode.OK) { r.success = false; r.httpException = res.ex; r.SetErrMsgFromBytes(res.content); return r; } r.success = true; r.content = new StatementsResult(new Json.StringOfJSON(Encoding.UTF8.GetString(res.content))); return r; } public StatementsResultLRSResponse MoreStatements(StatementsResult result) { var r = new StatementsResultLRSResponse(); var req = new MyHTTPRequest(); req.method = "GET"; req.resource = endpoint.GetLeftPart(UriPartial.Authority); if (! req.resource.EndsWith("/")) { req.resource += "/"; } req.resource += result.more; var res = MakeSyncRequest(req); if (res.status != HttpStatusCode.OK) { r.success = false; r.httpException = res.ex; r.SetErrMsgFromBytes(res.content); return r; } r.success = true; r.content = new StatementsResult(new Json.StringOfJSON(Encoding.UTF8.GetString(res.content))); return r; } // TODO: since param public ProfileKeysLRSResponse RetrieveStateIds(Activity activity, Agent agent, Nullable<Guid> registration = null) { var queryParams = new Dictionary<String, String>(); queryParams.Add("activityId", activity.id.ToString()); queryParams.Add("agent", agent.ToJSON(version)); if (registration != null) { queryParams.Add("registration", registration.ToString()); } return GetProfileKeys("activities/state", queryParams); } public StateLRSResponse RetrieveState(String id, Activity activity, Agent agent, Nullable<Guid> registration = null) { var r = new StateLRSResponse(); var queryParams = new Dictionary<String, String>(); queryParams.Add("stateId", id); queryParams.Add("activityId", activity.id.ToString()); queryParams.Add("agent", agent.ToJSON(version)); var state = new StateDocument(); state.id = id; state.activity = activity; state.agent = agent; if (registration != null) { queryParams.Add("registration", registration.ToString()); state.registration = registration; } var resp = GetDocument("activities/state", queryParams, state); if (resp.status != HttpStatusCode.OK && resp.status != HttpStatusCode.NotFound) { r.success = false; r.httpException = resp.ex; r.SetErrMsgFromBytes(resp.content); return r; } r.success = true; return r; } public LRSResponse SaveState(StateDocument state) { var queryParams = new Dictionary<String, String>(); queryParams.Add("stateId", state.id); queryParams.Add("activityId", state.activity.id.ToString()); queryParams.Add("agent", state.agent.ToJSON(version)); if (state.registration != null) { queryParams.Add("registration", state.registration.ToString()); } return SaveDocument("activities/state", queryParams, state); } public LRSResponse DeleteState(StateDocument state) { var queryParams = new Dictionary<String, String>(); queryParams.Add("stateId", state.id); queryParams.Add("activityId", state.activity.id.ToString()); queryParams.Add("agent", state.agent.ToJSON(version)); if (state.registration != null) { queryParams.Add("registration", state.registration.ToString()); } return DeleteDocument("activities/state", queryParams); } public LRSResponse ClearState(Activity activity, Agent agent, Nullable<Guid> registration = null) { var queryParams = new Dictionary<String, String>(); queryParams.Add("activityId", activity.id.ToString()); queryParams.Add("agent", agent.ToJSON(version)); if (registration != null) { queryParams.Add("registration", registration.ToString()); } return DeleteDocument("activities/state", queryParams); } // TODO: since param public ProfileKeysLRSResponse RetrieveActivityProfileIds(Activity activity) { var queryParams = new Dictionary<String, String>(); queryParams.Add("activityId", activity.id.ToString()); return GetProfileKeys("activities/profile", queryParams); } public ActivityProfileLRSResponse RetrieveActivityProfile(String id, Activity activity) { var r = new ActivityProfileLRSResponse(); var queryParams = new Dictionary<String, String>(); queryParams.Add("profileId", id); queryParams.Add("activityId", activity.id.ToString()); var profile = new ActivityProfileDocument(); profile.id = id; profile.activity = activity; var resp = GetDocument("activities/profile", queryParams, profile); if (resp.status != HttpStatusCode.OK && resp.status != HttpStatusCode.NotFound) { r.success = false; r.httpException = resp.ex; r.SetErrMsgFromBytes(resp.content); return r; } r.success = true; return r; } public LRSResponse SaveActivityProfile(ActivityProfileDocument profile) { var queryParams = new Dictionary<String, String>(); queryParams.Add("profileId", profile.id); queryParams.Add("activityId", profile.activity.id.ToString()); return SaveDocument("activities/profile", queryParams, profile); } public LRSResponse DeleteActivityProfile(ActivityProfileDocument profile) { var queryParams = new Dictionary<String, String>(); queryParams.Add("profileId", profile.id); queryParams.Add("activityId", profile.activity.id.ToString()); // TODO: need to pass Etag? return DeleteDocument("activities/profile", queryParams); } // TODO: since param public ProfileKeysLRSResponse RetrieveAgentProfileIds(Agent agent) { var queryParams = new Dictionary<String, String>(); queryParams.Add("agent", agent.ToJSON(version)); return GetProfileKeys("agents/profile", queryParams); } public AgentProfileLRSResponse RetrieveAgentProfile(String id, Agent agent) { var r = new AgentProfileLRSResponse(); var queryParams = new Dictionary<String, String>(); queryParams.Add("profileId", id); queryParams.Add("agent", agent.ToJSON(version)); var profile = new AgentProfileDocument(); profile.id = id; profile.agent = agent; var resp = GetDocument("agents/profile", queryParams, profile); if (resp.status != HttpStatusCode.OK && resp.status != HttpStatusCode.NotFound) { r.success = false; r.httpException = resp.ex; r.SetErrMsgFromBytes(resp.content); return r; } r.success = true; return r; } public LRSResponse SaveAgentProfile(AgentProfileDocument profile) { var queryParams = new Dictionary<String, String>(); queryParams.Add("profileId", profile.id); queryParams.Add("agent", profile.agent.ToJSON(version)); return SaveDocument("agents/profile", queryParams, profile); } public LRSResponse DeleteAgentProfile(AgentProfileDocument profile) { var queryParams = new Dictionary<String, String>(); queryParams.Add("profileId", profile.id); queryParams.Add("agent", profile.agent.ToJSON(version)); // TODO: need to pass Etag? return DeleteDocument("agents/profile", queryParams); } } }
nagyistoce/TinCan.NET
TinCan/RemoteLRS.cs
C#
apache-2.0
24,709
var stage, board, tiles, fleets, scale, sWid, is_dragging; var lastMouse = { x:0, y:0 }; var is_dragging = false; $(document).ready(function() { init_stage(); document.addEventListener('keyup', handleKeyUp, false); document.addEventListener('keydown', handleKeyDown, false); loadLobby(); }); /** * Called from createAll in game.js after all assets are loaded. * Clears old game globals, re-sets defaults. */ var setGlobals = function() { stage.removeChild(board); board = new createjs.Container(); tiles = []; fleetshapes = {}; scale = 0.60; }; var handleKeyUp = function( e ) { switch (e.keyCode) { case 189: // dash zoomBoard(-0.05); break; case 187: // equals (plus sign) zoomBoard(0.05); break; default: break; } }; var handleKeyDown = function( e ) { switch (e.keyCode) { case 37: // left arrow moveBoard(-1, 0); break; case 38: // up arrow moveBoard(0, -1); break; case 39: moveBoard(1, 0); break; case 40: moveBoard(0, 1); break; default: break; } }; /** * Calls init and draw functions for each tile in game board */ var createBoard = function() { if (stage) { initSelection(); updateCanvasSize(); drawAsteroids(); drawTiles(); drawNoFlyZones(); drawBases(); drawAgents(); drawFleets(); drawSprites(); stage.addChild( board ); scale = 0.75; var boardWidth = 7 * sWid * scale; var boardHeight = 7 * sWid * scale; board.x = (window.innerWidth - boardWidth) / 2.0; board.y = (window.innerHeight - boardHeight) / 2.0; board.scaleX = scale; board.scaleY = scale; fadeIn(board, 1000, false, false); } }; var drawAsteroids = function() { var asteroids = clientGame.game.board.asteroids; for ( var a = 0; a < asteroids.length; a++ ) { drawAsteroid( asteroids[a] ); } }; var drawTiles = function() { var planets = clientGame.game.board.planets; for ( var p = 0; p < planets.length; p++ ) { initTile(p); drawTile(p); } }; var drawFleets = function() { initFleets(); var planets = clientGame.game.board.planets; for ( var p = 0; p < planets.length; p++ ) { updateFleets(p); } }; var drawNoFlyZones = function() { var planets = clientGame.game.board.planets; initNoFlyZones(); updateNoFlyZones(); }; var drawBases = function() { var planets = clientGame.game.board.planets; initBases(); for ( var p = 0; p < planets.length; p++ ) { updateBases(p); } }; var drawAgents = function() { initAgents(); var planets = clientGame.game.board.planets; for ( var p = 0; p < planets.length; p++ ) { updateAgents(p); } }; /** * Calls function to turn mouse enablement on/off on different * createJS containers based on what action the user is in. */ var updateBoardInteractivity = function() { var planets = clientGame.game.board.planets; for ( var p = 0; p < planets.length; p++ ) { updateTileInteractivity(p); } updateFleetsInteractivity(); updateBasesInteractivity(); updateAgentsInteractivity(); }; /** * Calls update functions on each tile to update appearance, interactivity * based on current pending action or game event */ var updateBoard = function() { var planets = clientGame.game.board.planets; // this sets all bases to invisible. Update function will reveal // and draw any that are on planets. updateRemovedBases(); for ( var p = 0; p < planets.length; p++ ) { updateTileInteractivity(p); updateTileImage(p); updateFleets(p); updateBases(p); updateAgents(p); } updateNoFlyZones(); updateRemovedFleets(); updateDeadAgents(); stage.update(); };
Zebbeni/alien-empire
client/game_board.js
JavaScript
apache-2.0
3,574
// Code generated by protoc-gen-go. DO NOT EDIT. // source: google/ads/googleads/v1/errors/conversion_action_error.proto package errors // import "google.golang.org/genproto/googleapis/ads/googleads/v1/errors" import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" import _ "google.golang.org/genproto/googleapis/api/annotations" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package // Enum describing possible conversion action errors. type ConversionActionErrorEnum_ConversionActionError int32 const ( // Enum unspecified. ConversionActionErrorEnum_UNSPECIFIED ConversionActionErrorEnum_ConversionActionError = 0 // The received error code is not known in this version. ConversionActionErrorEnum_UNKNOWN ConversionActionErrorEnum_ConversionActionError = 1 // The specified conversion action name already exists. ConversionActionErrorEnum_DUPLICATE_NAME ConversionActionErrorEnum_ConversionActionError = 2 // Another conversion action with the specified app id already exists. ConversionActionErrorEnum_DUPLICATE_APP_ID ConversionActionErrorEnum_ConversionActionError = 3 // Android first open action conflicts with Google play codeless download // action tracking the same app. ConversionActionErrorEnum_TWO_CONVERSION_ACTIONS_BIDDING_ON_SAME_APP_DOWNLOAD ConversionActionErrorEnum_ConversionActionError = 4 // Android first open action conflicts with Google play codeless download // action tracking the same app. ConversionActionErrorEnum_BIDDING_ON_SAME_APP_DOWNLOAD_AS_GLOBAL_ACTION ConversionActionErrorEnum_ConversionActionError = 5 // The attribution model cannot be set to DATA_DRIVEN because a data-driven // model has never been generated. ConversionActionErrorEnum_DATA_DRIVEN_MODEL_WAS_NEVER_GENERATED ConversionActionErrorEnum_ConversionActionError = 6 // The attribution model cannot be set to DATA_DRIVEN because the // data-driven model is expired. ConversionActionErrorEnum_DATA_DRIVEN_MODEL_EXPIRED ConversionActionErrorEnum_ConversionActionError = 7 // The attribution model cannot be set to DATA_DRIVEN because the // data-driven model is stale. ConversionActionErrorEnum_DATA_DRIVEN_MODEL_STALE ConversionActionErrorEnum_ConversionActionError = 8 // The attribution model cannot be set to DATA_DRIVEN because the // data-driven model is unavailable or the conversion action was newly // added. ConversionActionErrorEnum_DATA_DRIVEN_MODEL_UNKNOWN ConversionActionErrorEnum_ConversionActionError = 9 ) var ConversionActionErrorEnum_ConversionActionError_name = map[int32]string{ 0: "UNSPECIFIED", 1: "UNKNOWN", 2: "DUPLICATE_NAME", 3: "DUPLICATE_APP_ID", 4: "TWO_CONVERSION_ACTIONS_BIDDING_ON_SAME_APP_DOWNLOAD", 5: "BIDDING_ON_SAME_APP_DOWNLOAD_AS_GLOBAL_ACTION", 6: "DATA_DRIVEN_MODEL_WAS_NEVER_GENERATED", 7: "DATA_DRIVEN_MODEL_EXPIRED", 8: "DATA_DRIVEN_MODEL_STALE", 9: "DATA_DRIVEN_MODEL_UNKNOWN", } var ConversionActionErrorEnum_ConversionActionError_value = map[string]int32{ "UNSPECIFIED": 0, "UNKNOWN": 1, "DUPLICATE_NAME": 2, "DUPLICATE_APP_ID": 3, "TWO_CONVERSION_ACTIONS_BIDDING_ON_SAME_APP_DOWNLOAD": 4, "BIDDING_ON_SAME_APP_DOWNLOAD_AS_GLOBAL_ACTION": 5, "DATA_DRIVEN_MODEL_WAS_NEVER_GENERATED": 6, "DATA_DRIVEN_MODEL_EXPIRED": 7, "DATA_DRIVEN_MODEL_STALE": 8, "DATA_DRIVEN_MODEL_UNKNOWN": 9, } func (x ConversionActionErrorEnum_ConversionActionError) String() string { return proto.EnumName(ConversionActionErrorEnum_ConversionActionError_name, int32(x)) } func (ConversionActionErrorEnum_ConversionActionError) EnumDescriptor() ([]byte, []int) { return fileDescriptor_conversion_action_error_6bc78838b2a5587b, []int{0, 0} } // Container for enum describing possible conversion action errors. type ConversionActionErrorEnum struct { XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *ConversionActionErrorEnum) Reset() { *m = ConversionActionErrorEnum{} } func (m *ConversionActionErrorEnum) String() string { return proto.CompactTextString(m) } func (*ConversionActionErrorEnum) ProtoMessage() {} func (*ConversionActionErrorEnum) Descriptor() ([]byte, []int) { return fileDescriptor_conversion_action_error_6bc78838b2a5587b, []int{0} } func (m *ConversionActionErrorEnum) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_ConversionActionErrorEnum.Unmarshal(m, b) } func (m *ConversionActionErrorEnum) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_ConversionActionErrorEnum.Marshal(b, m, deterministic) } func (dst *ConversionActionErrorEnum) XXX_Merge(src proto.Message) { xxx_messageInfo_ConversionActionErrorEnum.Merge(dst, src) } func (m *ConversionActionErrorEnum) XXX_Size() int { return xxx_messageInfo_ConversionActionErrorEnum.Size(m) } func (m *ConversionActionErrorEnum) XXX_DiscardUnknown() { xxx_messageInfo_ConversionActionErrorEnum.DiscardUnknown(m) } var xxx_messageInfo_ConversionActionErrorEnum proto.InternalMessageInfo func init() { proto.RegisterType((*ConversionActionErrorEnum)(nil), "google.ads.googleads.v1.errors.ConversionActionErrorEnum") proto.RegisterEnum("google.ads.googleads.v1.errors.ConversionActionErrorEnum_ConversionActionError", ConversionActionErrorEnum_ConversionActionError_name, ConversionActionErrorEnum_ConversionActionError_value) } func init() { proto.RegisterFile("google/ads/googleads/v1/errors/conversion_action_error.proto", fileDescriptor_conversion_action_error_6bc78838b2a5587b) } var fileDescriptor_conversion_action_error_6bc78838b2a5587b = []byte{ // 443 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x92, 0x41, 0x8b, 0xd3, 0x40, 0x14, 0xc7, 0x6d, 0x56, 0x77, 0x75, 0x16, 0x74, 0x18, 0x14, 0xd9, 0x55, 0xf7, 0x50, 0xf0, 0xe0, 0xc1, 0x84, 0xb0, 0x07, 0x21, 0x7a, 0x79, 0xcd, 0x8c, 0x61, 0x30, 0x9d, 0x09, 0x49, 0x9a, 0x8a, 0x14, 0x86, 0xd8, 0x94, 0x50, 0xd8, 0xcd, 0x94, 0x4c, 0xed, 0x07, 0xf2, 0xe8, 0x47, 0xf1, 0xe6, 0xd7, 0xf0, 0xe2, 0xc9, 0xbb, 0x24, 0xb3, 0xad, 0x87, 0xed, 0xf6, 0x34, 0x7f, 0xde, 0xfb, 0xff, 0xfe, 0x09, 0xef, 0x3d, 0xf4, 0xa1, 0xd6, 0xba, 0xbe, 0x5a, 0x78, 0x65, 0x65, 0x3c, 0x2b, 0x3b, 0xb5, 0xf1, 0xbd, 0x45, 0xdb, 0xea, 0xd6, 0x78, 0x73, 0xdd, 0x6c, 0x16, 0xad, 0x59, 0xea, 0x46, 0x95, 0xf3, 0x75, 0xf7, 0xf4, 0x0d, 0x77, 0xd5, 0xea, 0xb5, 0x26, 0x17, 0x16, 0x71, 0xcb, 0xca, 0xb8, 0x3b, 0xda, 0xdd, 0xf8, 0xae, 0xa5, 0xcf, 0x5f, 0x6e, 0xd3, 0x57, 0x4b, 0xaf, 0x6c, 0x1a, 0xbd, 0x2e, 0xbb, 0x08, 0x63, 0xe9, 0xe1, 0x1f, 0x07, 0x9d, 0x85, 0xbb, 0x7c, 0xe8, 0xe3, 0x59, 0x07, 0xb2, 0xe6, 0xdb, 0xf5, 0xf0, 0x97, 0x83, 0x9e, 0xed, 0xed, 0x92, 0x27, 0xe8, 0x74, 0x22, 0xb2, 0x84, 0x85, 0xfc, 0x23, 0x67, 0x14, 0xdf, 0x23, 0xa7, 0xe8, 0x64, 0x22, 0x3e, 0x09, 0x39, 0x15, 0x78, 0x40, 0x08, 0x7a, 0x4c, 0x27, 0x49, 0xcc, 0x43, 0xc8, 0x99, 0x12, 0x30, 0x66, 0xd8, 0x21, 0x4f, 0x11, 0xfe, 0x5f, 0x83, 0x24, 0x51, 0x9c, 0xe2, 0x23, 0xf2, 0x0e, 0x5d, 0xe6, 0x53, 0xa9, 0x42, 0x29, 0x0a, 0x96, 0x66, 0x5c, 0x0a, 0x05, 0x61, 0xce, 0xa5, 0xc8, 0xd4, 0x88, 0x53, 0xca, 0x45, 0xa4, 0xa4, 0x50, 0x19, 0x8c, 0x2d, 0x42, 0xe5, 0x54, 0xc4, 0x12, 0x28, 0xbe, 0x4f, 0x7c, 0xf4, 0xf6, 0x90, 0x43, 0x41, 0xa6, 0xa2, 0x58, 0x8e, 0x20, 0xbe, 0x09, 0xc4, 0x0f, 0xc8, 0x1b, 0xf4, 0x9a, 0x42, 0x0e, 0x8a, 0xa6, 0xbc, 0x60, 0x42, 0x8d, 0x25, 0x65, 0xb1, 0x9a, 0x42, 0xa6, 0x04, 0x2b, 0x58, 0xaa, 0x22, 0x26, 0x58, 0x0a, 0x39, 0xa3, 0xf8, 0x98, 0xbc, 0x42, 0x67, 0xb7, 0xad, 0xec, 0x73, 0xc2, 0x53, 0x46, 0xf1, 0x09, 0x79, 0x81, 0x9e, 0xdf, 0x6e, 0x67, 0x39, 0xc4, 0x0c, 0x3f, 0xdc, 0xcf, 0x6e, 0x67, 0xf3, 0x68, 0xf4, 0x77, 0x80, 0x86, 0x73, 0x7d, 0xed, 0x1e, 0x5e, 0xdb, 0xe8, 0x7c, 0xef, 0xdc, 0x93, 0x6e, 0x69, 0xc9, 0xe0, 0x0b, 0xbd, 0xa1, 0x6b, 0x7d, 0x55, 0x36, 0xb5, 0xab, 0xdb, 0xda, 0xab, 0x17, 0x4d, 0xbf, 0xd2, 0xed, 0x09, 0xad, 0x96, 0xe6, 0xae, 0x8b, 0x7a, 0x6f, 0x9f, 0xef, 0xce, 0x51, 0x04, 0xf0, 0xc3, 0xb9, 0x88, 0x6c, 0x18, 0x54, 0xc6, 0xb5, 0xb2, 0x53, 0x85, 0xef, 0xf6, 0x9f, 0x34, 0x3f, 0xb7, 0x86, 0x19, 0x54, 0x66, 0xb6, 0x33, 0xcc, 0x0a, 0x7f, 0x66, 0x0d, 0xbf, 0x9d, 0xa1, 0xad, 0x06, 0x01, 0x54, 0x26, 0x08, 0x76, 0x96, 0x20, 0x28, 0xfc, 0x20, 0xb0, 0xa6, 0xaf, 0xc7, 0xfd, 0xdf, 0x5d, 0xfe, 0x0b, 0x00, 0x00, 0xff, 0xff, 0x0c, 0xe0, 0x92, 0x88, 0xee, 0x02, 0x00, 0x00, }
ptinsley/fling
vendor/google.golang.org/genproto/googleapis/ads/googleads/v1/errors/conversion_action_error.pb.go
GO
apache-2.0
8,831
/* * Copyright 2017 Mirko Sertic * * 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 de.mirkosertic.bytecoder.integrationtest; import de.mirkosertic.bytecoder.api.Import; import de.mirkosertic.bytecoder.api.web.AnimationFrameCallback; import de.mirkosertic.bytecoder.api.web.CanvasRenderingContext2D; import de.mirkosertic.bytecoder.api.web.MouseEvent; import de.mirkosertic.bytecoder.api.web.Document; import de.mirkosertic.bytecoder.api.web.EventListener; import de.mirkosertic.bytecoder.api.web.HTMLButton; import de.mirkosertic.bytecoder.api.web.HTMLCanvasElement; import de.mirkosertic.bytecoder.api.web.Window; import org.jbox2d.collision.shapes.CircleShape; import org.jbox2d.collision.shapes.PolygonShape; import org.jbox2d.collision.shapes.Shape; import org.jbox2d.collision.shapes.ShapeType; import org.jbox2d.common.Vec2; import org.jbox2d.dynamics.Body; import org.jbox2d.dynamics.BodyDef; import org.jbox2d.dynamics.BodyType; import org.jbox2d.dynamics.Fixture; import org.jbox2d.dynamics.FixtureDef; import org.jbox2d.dynamics.World; import org.jbox2d.dynamics.joints.RevoluteJointDef; public class JBox2DSimulation { public static class Scene { private final World world; private Body axis; private Body reel; private long lastCalculated; private final long startTime; public Scene() { world = new World(new Vec2(0, -9.8f)); initAxis(); initReel(); joinReelToAxis(); initBalls(); lastCalculated = System.currentTimeMillis(); startTime = lastCalculated; } private void initAxis() { final BodyDef axisDef = new BodyDef(); axisDef.type = BodyType.STATIC; axisDef.position = new Vec2(3, 3); axis = world.createBody(axisDef); final CircleShape axisShape = new CircleShape(); axisShape.setRadius(0.02f); axisShape.m_p.set(0, 0); final FixtureDef axisFixture = new FixtureDef(); axisFixture.shape = axisShape; axis.createFixture(axisFixture); } private void initReel() { final BodyDef reelDef = new BodyDef(); reelDef.type = BodyType.DYNAMIC; reelDef.position = new Vec2(3, 3); reel = world.createBody(reelDef); final FixtureDef fixture = new FixtureDef(); fixture.friction = 0.5f; fixture.restitution = 0.4f; fixture.density = 1; final int parts = 30; for (int i = 0; i < parts; ++i) { final PolygonShape shape = new PolygonShape(); final double angle1 = i / (double) parts * 2 * Math.PI; final double x1 = 2.7 * Math.cos(angle1); final double y1 = 2.7 * Math.sin(angle1); final double angle2 = (i + 1) / (double) parts * 2 * Math.PI; final double x2 = 2.7 * Math.cos(angle2); final double y2 = 2.7 * Math.sin(angle2); final double angle = (angle1 + angle2) / 2; final double x = 0.01 * Math.cos(angle); final double y = 0.01 * Math.sin(angle); shape.set(new Vec2[] { new Vec2((float) x1, (float) y1), new Vec2((float) x2, (float) y2), new Vec2((float) (x2 - x), (float) (y2 - y)), new Vec2((float) (x1 - x), (float) (y1 - y)) }, 4); fixture.shape = shape; reel.createFixture(fixture); } } private void initBalls() { final float ballRadius = 0.15f; final BodyDef ballDef = new BodyDef(); ballDef.type = BodyType.DYNAMIC; final FixtureDef fixtureDef = new FixtureDef(); fixtureDef.friction = 0.3f; fixtureDef.restitution = 0.3f; fixtureDef.density = 0.2f; final CircleShape shape = new CircleShape(); shape.m_radius = ballRadius; fixtureDef.shape = shape; for (int i = 0; i < 6; ++i) { for (int j = 0; j < 6; ++j) { final float x = (j + 0.5f) * (ballRadius * 2 + 0.01f); final float y = (i + 0.5f) * (ballRadius * 2 + 0.01f); ballDef.position.x = 3 + x; ballDef.position.y = 3 + y; Body body = world.createBody(ballDef); body.createFixture(fixtureDef); ballDef.position.x = 3 - x; ballDef.position.y = 3 + y; body = world.createBody(ballDef); body.createFixture(fixtureDef); ballDef.position.x = 3 + x; ballDef.position.y = 3 - y; body = world.createBody(ballDef); body.createFixture(fixtureDef); ballDef.position.x = 3 - x; ballDef.position.y = 3 - y; body = world.createBody(ballDef); body.createFixture(fixtureDef); } } } private void joinReelToAxis() { final RevoluteJointDef jointDef = new RevoluteJointDef(); jointDef.bodyA = axis; jointDef.bodyB = reel; world.createJoint(jointDef); } public void calculate() { final long currentTime = System.currentTimeMillis(); int timeToCalculate = (int) (currentTime - lastCalculated); final long relativeTime = currentTime - startTime; while (timeToCalculate > 10) { final int period = (int) ((relativeTime + 5000) / 10000); reel.applyTorque(period % 2 == 0 ? 8f : -8f); world.step(0.01f, 20, 40); lastCalculated += 10; timeToCalculate -= 10; } lastCalculated = System.currentTimeMillis(); } public World getWorld() { return world; } } private static Scene scene; private static CanvasRenderingContext2D renderingContext2D; private static AnimationFrameCallback animationCallback; private static Window window; public static void main(final String[] args) { scene = new Scene(); window = Window.window(); final Document document = window.document(); final HTMLCanvasElement theCanvas = document.getElementById("benchmark-canvas"); renderingContext2D = theCanvas.getContext("2d"); animationCallback = new AnimationFrameCallback() { @Override public void run(final int aElapsedTime) { final long theStart = System.currentTimeMillis(); statsBegin(); scene.calculate(); render(); statsEnd(); final int theDuration = (int) (System.currentTimeMillis() - theStart); logRuntime(theDuration); window.requestAnimationFrame(animationCallback); } }; final HTMLButton button = document.getElementById("button"); button.addEventListener("click", new EventListener<MouseEvent>() { @Override public void run(final MouseEvent aValue) { button.disabled(true); window.requestAnimationFrame(animationCallback); } }); window.fetch("versioninfo.txt").then(response -> { response.text().then(text -> { document.getElementById("versioninfo").innerHTML(text); }); }); } @Import(module = "debug", name = "logRuntime") public static native void logRuntime(int aValue); @Import(module = "stats", name = "begin") public static native void statsBegin(); @Import(module = "stats", name = "end") public static native void statsEnd(); private static void render() { renderingContext2D.setFillStyle("white"); renderingContext2D.setStrokeStyle("black"); renderingContext2D.fillRect(0, 0, 600, 600); renderingContext2D.save(); renderingContext2D.translate(0, 600); renderingContext2D.scale(1, -1); renderingContext2D.scale(100, 100); renderingContext2D.setLineWidth(0.01f); for (Body body = scene.getWorld().getBodyList(); body != null; body = body.getNext()) { final Vec2 center = body.getPosition(); renderingContext2D.save(); renderingContext2D.translate(center.x, center.y); renderingContext2D.rotate(body.getAngle()); for (Fixture fixture = body.getFixtureList(); fixture != null; fixture = fixture.getNext()) { final Shape shape = fixture.getShape(); if (shape.getType() == ShapeType.CIRCLE) { final CircleShape circle = (CircleShape) shape; renderingContext2D.beginPath(); renderingContext2D.arc(circle.m_p.x, circle.m_p.y, circle.getRadius(), 0, Math.PI * 2, true); renderingContext2D.closePath(); renderingContext2D.stroke(); } else if (shape.getType() == ShapeType.POLYGON) { final PolygonShape poly = (PolygonShape) shape; final Vec2[] vertices = poly.getVertices(); renderingContext2D.beginPath(); renderingContext2D.moveTo(vertices[0].x, vertices[0].y); for (int i = 1; i < poly.getVertexCount(); ++i) { renderingContext2D.lineTo(vertices[i].x, vertices[i].y); } renderingContext2D.closePath(); renderingContext2D.stroke(); } } renderingContext2D.restore(); } renderingContext2D.restore(); } }
mirkosertic/Bytecoder
integrationtest/src/main/java/de/mirkosertic/bytecoder/integrationtest/JBox2DSimulation.java
Java
apache-2.0
10,500
// +build linux package node import ( "fmt" "net" "sync" "syscall" "github.com/golang/glog" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "github.com/openshift/origin/pkg/network/common" networkinformers "github.com/openshift/origin/pkg/network/generated/informers/internalversion" "github.com/vishvananda/netlink" ) type egressIPWatcher struct { sync.Mutex tracker *common.EgressIPTracker oc *ovsController localIP string masqueradeBit uint32 iptables *NodeIPTables iptablesMark map[string]string vxlanMonitor *egressVXLANMonitor localEgressLink netlink.Link localEgressNet *net.IPNet testModeChan chan string } func newEgressIPWatcher(oc *ovsController, localIP string, masqueradeBit *int32) *egressIPWatcher { eip := &egressIPWatcher{ oc: oc, localIP: localIP, iptablesMark: make(map[string]string), } if masqueradeBit != nil { eip.masqueradeBit = 1 << uint32(*masqueradeBit) } eip.tracker = common.NewEgressIPTracker(eip) return eip } func (eip *egressIPWatcher) Start(networkInformers networkinformers.SharedInformerFactory, iptables *NodeIPTables) error { var err error if eip.localEgressLink, eip.localEgressNet, err = GetLinkDetails(eip.localIP); err != nil { // Not expected, should already be caught by node.New() return nil } eip.iptables = iptables updates := make(chan *egressVXLANNode) eip.vxlanMonitor = newEgressVXLANMonitor(eip.oc.ovs, eip.tracker, updates) go eip.watchVXLAN(updates) eip.tracker.Start(networkInformers.Network().InternalVersion().HostSubnets(), networkInformers.Network().InternalVersion().NetNamespaces()) return nil } // Convert vnid to a hex value that is not 0, does not have masqueradeBit set, and isn't // the same value as would be returned for any other valid vnid. func getMarkForVNID(vnid, masqueradeBit uint32) string { if vnid == 0 { vnid = 0xff000000 } if (vnid & masqueradeBit) != 0 { vnid = (vnid | 0x01000000) ^ masqueradeBit } return fmt.Sprintf("0x%08x", vnid) } func (eip *egressIPWatcher) ClaimEgressIP(vnid uint32, egressIP, nodeIP string) { if nodeIP == eip.localIP { mark := getMarkForVNID(vnid, eip.masqueradeBit) eip.iptablesMark[egressIP] = mark if err := eip.assignEgressIP(egressIP, mark); err != nil { utilruntime.HandleError(fmt.Errorf("Error assigning Egress IP %q: %v", egressIP, err)) } } else if eip.vxlanMonitor != nil { eip.vxlanMonitor.AddNode(nodeIP) } } func (eip *egressIPWatcher) ReleaseEgressIP(egressIP, nodeIP string) { if nodeIP == eip.localIP { mark := eip.iptablesMark[egressIP] delete(eip.iptablesMark, egressIP) if err := eip.releaseEgressIP(egressIP, mark); err != nil { utilruntime.HandleError(fmt.Errorf("Error releasing Egress IP %q: %v", egressIP, err)) } } else if eip.vxlanMonitor != nil { eip.vxlanMonitor.RemoveNode(nodeIP) } } func (eip *egressIPWatcher) SetNamespaceEgressNormal(vnid uint32) { if err := eip.oc.SetNamespaceEgressNormal(vnid); err != nil { utilruntime.HandleError(fmt.Errorf("Error updating Namespace egress rules for VNID %d: %v", vnid, err)) } } func (eip *egressIPWatcher) SetNamespaceEgressDropped(vnid uint32) { if err := eip.oc.SetNamespaceEgressDropped(vnid); err != nil { utilruntime.HandleError(fmt.Errorf("Error updating Namespace egress rules for VNID %d: %v", vnid, err)) } } func (eip *egressIPWatcher) SetNamespaceEgressViaEgressIP(vnid uint32, egressIP, nodeIP string) { mark := eip.iptablesMark[egressIP] if err := eip.oc.SetNamespaceEgressViaEgressIP(vnid, nodeIP, mark); err != nil { utilruntime.HandleError(fmt.Errorf("Error updating Namespace egress rules for VNID %d: %v", vnid, err)) } } func (eip *egressIPWatcher) assignEgressIP(egressIP, mark string) error { if egressIP == eip.localIP { return fmt.Errorf("desired egress IP %q is the node IP", egressIP) } if eip.testModeChan != nil { eip.testModeChan <- fmt.Sprintf("claim %s", egressIP) return nil } localEgressIPMaskLen, _ := eip.localEgressNet.Mask.Size() egressIPNet := fmt.Sprintf("%s/%d", egressIP, localEgressIPMaskLen) addr, err := netlink.ParseAddr(egressIPNet) if err != nil { return fmt.Errorf("could not parse egress IP %q: %v", egressIPNet, err) } if !eip.localEgressNet.Contains(addr.IP) { return fmt.Errorf("egress IP %q is not in local network %s of interface %s", egressIP, eip.localEgressNet.String(), eip.localEgressLink.Attrs().Name) } err = netlink.AddrAdd(eip.localEgressLink, addr) if err != nil { if err == syscall.EEXIST { glog.V(2).Infof("Egress IP %q already exists on %s", egressIPNet, eip.localEgressLink.Attrs().Name) } else { return fmt.Errorf("could not add egress IP %q to %s: %v", egressIPNet, eip.localEgressLink.Attrs().Name, err) } } if err := eip.iptables.AddEgressIPRules(egressIP, mark); err != nil { return fmt.Errorf("could not add egress IP iptables rule: %v", err) } return nil } func (eip *egressIPWatcher) releaseEgressIP(egressIP, mark string) error { if egressIP == eip.localIP { return nil } if eip.testModeChan != nil { eip.testModeChan <- fmt.Sprintf("release %s", egressIP) return nil } localEgressIPMaskLen, _ := eip.localEgressNet.Mask.Size() egressIPNet := fmt.Sprintf("%s/%d", egressIP, localEgressIPMaskLen) addr, err := netlink.ParseAddr(egressIPNet) if err != nil { return fmt.Errorf("could not parse egress IP %q: %v", egressIPNet, err) } err = netlink.AddrDel(eip.localEgressLink, addr) if err != nil { if err == syscall.EADDRNOTAVAIL { glog.V(2).Infof("Could not delete egress IP %q from %s: no such address", egressIPNet, eip.localEgressLink.Attrs().Name) } else { return fmt.Errorf("could not delete egress IP %q from %s: %v", egressIPNet, eip.localEgressLink.Attrs().Name, err) } } if err := eip.iptables.DeleteEgressIPRules(egressIP, mark); err != nil { return fmt.Errorf("could not delete egress IP iptables rule: %v", err) } return nil } func (eip *egressIPWatcher) watchVXLAN(updates chan *egressVXLANNode) { for node := range updates { eip.tracker.SetNodeOffline(node.nodeIP, node.offline) } }
legionus/origin
pkg/network/node/egressip.go
GO
apache-2.0
6,103
/* * 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.calcite.sql; import org.apache.calcite.sql.fun.SqlStdOperatorTable; import org.apache.calcite.sql.parser.SqlParserPos; import org.apache.calcite.sql.type.ReturnTypes; import org.apache.calcite.sql.util.SqlBasicVisitor; import org.apache.calcite.sql.util.SqlVisitor; import java.util.ArrayList; import java.util.List; /** * An operator describing a query. (Not a query itself.) * * <p>Operands are:</p> * * <ul> * <li>0: distinct ({@link SqlLiteral})</li> * <li>1: selectClause ({@link SqlNodeList})</li> * <li>2: fromClause ({@link SqlCall} to "join" operator)</li> * <li>3: whereClause ({@link SqlNode})</li> * <li>4: havingClause ({@link SqlNode})</li> * <li>5: qualifyClause ({@link SqlNode})</li> * <li>6: groupClause ({@link SqlNode})</li> * <li>7: windowClause ({@link SqlNodeList})</li> * <li>8: orderClause ({@link SqlNode})</li> * </ul> */ public class SqlSelectOperator extends SqlOperator { public static final SqlSelectOperator INSTANCE = new SqlSelectOperator(); //~ Constructors ----------------------------------------------------------- private SqlSelectOperator() { super("SELECT", SqlKind.SELECT, 2, true, ReturnTypes.SCOPE, null, null); } //~ Methods ---------------------------------------------------------------- public SqlSyntax getSyntax() { return SqlSyntax.SPECIAL; } public SqlCall createCall( SqlLiteral functionQualifier, SqlParserPos pos, SqlNode... operands) { assert functionQualifier == null; return new SqlSelect(pos, /*keywordList=*/ (SqlNodeList) operands[0], /*selectList=*/ (SqlNodeList) operands[1], /* from= */ operands[2], /* where= */ operands[3], /*groupBy=*/ (SqlNodeList) operands[4], /*having=*/ operands[5], /*qualify=*/ operands[6], /*windowDecls=*/ (SqlNodeList) operands[7], /*orderBy=*/ (SqlNodeList) operands[8], /*offset=*/ operands[9], /*fetch=*/ operands[10], /*hints=*/ (SqlNodeList) operands[11]); } /** * Creates a call to the <code>SELECT</code> operator. * * @param keywordList List of keywords such DISTINCT and ALL, or null * @param selectList The SELECT clause, or null if empty * @param fromClause The FROM clause * @param whereClause The WHERE clause, or null if not present * @param groupBy The GROUP BY clause, or null if not present * @param having The HAVING clause, or null if not present * @param qualify The QUALIFY clause, or null if not present * @param windowDecls The WINDOW clause, or null if not present * @param orderBy The ORDER BY clause, or null if not present * @param offset Expression for number of rows to discard before * returning first row * @param fetch Expression for number of rows to fetch * @param pos The parser position, or * {@link org.apache.calcite.sql.parser.SqlParserPos#ZERO} * if not specified; must not be null. * @return A {@link SqlSelect}, never null */ public SqlSelect createCall( SqlNodeList keywordList, SqlNodeList selectList, SqlNode fromClause, SqlNode whereClause, SqlNodeList groupBy, SqlNode having, SqlNode qualify, SqlNodeList windowDecls, SqlNodeList orderBy, SqlNode offset, SqlNode fetch, SqlNodeList hints, SqlParserPos pos) { return new SqlSelect( pos, keywordList, selectList, fromClause, whereClause, groupBy, having, qualify, windowDecls, orderBy, offset, fetch, hints); } public <R> void acceptCall( SqlVisitor<R> visitor, SqlCall call, boolean onlyExpressions, SqlBasicVisitor.ArgHandler<R> argHandler) { if (!onlyExpressions) { // None of the arguments to the SELECT operator are expressions. super.acceptCall(visitor, call, onlyExpressions, argHandler); } } @SuppressWarnings("deprecation") public void unparse( SqlWriter writer, SqlCall call, int leftPrec, int rightPrec) { SqlSelect select = (SqlSelect) call; final SqlWriter.Frame selectFrame = writer.startList(SqlWriter.FrameTypeEnum.SELECT); writer.sep("SELECT"); if (select.hasHints()) { writer.sep("/*+"); select.hints.unparse(writer, 0, 0); writer.print("*/"); writer.newlineAndIndent(); } for (int i = 0; i < select.keywordList.size(); i++) { final SqlNode keyword = select.keywordList.get(i); keyword.unparse(writer, 0, 0); } if (select.topN != null) { writer.topN(select.topN); } else { writer.fetchAsTopN(select.fetch, select.offset); } final SqlNodeList selectClause = select.selectList != null ? select.selectList : SqlNodeList.of(SqlIdentifier.star(SqlParserPos.ZERO)); writer.list(SqlWriter.FrameTypeEnum.SELECT_LIST, SqlWriter.COMMA, selectClause); if (select.from != null) { // Calcite SQL requires FROM but MySQL does not. writer.sep("FROM"); // for FROM clause, use precedence just below join operator to make // sure that an un-joined nested select will be properly // parenthesized final SqlWriter.Frame fromFrame = writer.startList(SqlWriter.FrameTypeEnum.FROM_LIST); select.from.unparse( writer, SqlJoin.OPERATOR.getLeftPrec() - 1, SqlJoin.OPERATOR.getRightPrec() - 1); writer.endList(fromFrame); } if (select.where != null) { writer.sep("WHERE"); if (!writer.isAlwaysUseParentheses()) { SqlNode node = select.where; // decide whether to split on ORs or ANDs SqlBinaryOperator whereSep = SqlStdOperatorTable.AND; if ((node instanceof SqlCall) && node.getKind() == SqlKind.OR) { whereSep = SqlStdOperatorTable.OR; } // unroll whereClause final List<SqlNode> list = new ArrayList<>(0); while (node.getKind() == whereSep.kind) { assert node instanceof SqlCall; final SqlCall call1 = (SqlCall) node; list.add(0, call1.operand(1)); node = call1.operand(0); } list.add(0, node); // unparse in a WHERE_LIST frame writer.list(SqlWriter.FrameTypeEnum.WHERE_LIST, whereSep, new SqlNodeList(list, select.where.getParserPosition())); } else { select.where.unparse(writer, 0, 0); } } if (select.groupBy != null) { writer.sep("GROUP BY"); final SqlNodeList groupBy = select.groupBy.size() == 0 ? SqlNodeList.SINGLETON_EMPTY : select.groupBy; writer.list(SqlWriter.FrameTypeEnum.GROUP_BY_LIST, SqlWriter.COMMA, groupBy); } if (select.having != null) { writer.sep("HAVING"); select.having.unparse(writer, 0, 0); } if (select.getQualify() != null) { writer.sep("QUALIFY"); select.getQualify().unparse(writer, 0, 0); } if (select.windowDecls.size() > 0) { writer.sep("WINDOW"); writer.list(SqlWriter.FrameTypeEnum.WINDOW_DECL_LIST, SqlWriter.COMMA, select.windowDecls); } if (select.orderBy != null && select.orderBy.size() > 0) { writer.sep("ORDER BY"); writer.list(SqlWriter.FrameTypeEnum.ORDER_BY_LIST, SqlWriter.COMMA, select.orderBy); } writer.fetchOffset(select.fetch, select.offset); writer.endList(selectFrame); } public boolean argumentMustBeScalar(int ordinal) { return ordinal == SqlSelect.WHERE_OPERAND; } }
googleinterns/calcite
core/src/main/java/org/apache/calcite/sql/SqlSelectOperator.java
Java
apache-2.0
8,563
package org.docksidestage.hangar.dbflute.dtomapper; import java.util.Map; import org.dbflute.Entity; import org.docksidestage.hangar.dbflute.dtomapper.bs.BsMemberServiceDtoMapper; /** * The DTO mapper of MEMBER_SERVICE. * <p> * You can implement your original methods here. * This class remains when re-generating. * </p> * @author DBFlute(AutoGenerator) */ public class MemberServiceDtoMapper extends BsMemberServiceDtoMapper { /** Serial version UID. (Default) */ private static final long serialVersionUID = 1L; public MemberServiceDtoMapper() { } public MemberServiceDtoMapper(Map<Entity, Object> relationDtoMap, Map<Object, Entity> relationEntityMap) { super(relationDtoMap, relationEntityMap); } }
dbflute-test/dbflute-test-active-hangar
src/main/java/org/docksidestage/hangar/dbflute/dtomapper/MemberServiceDtoMapper.java
Java
apache-2.0
776
/* * @Author: aaronpmishkin * @Date: 2016-06-17 09:05:15 * @Last Modified by: aaronpmishkin * @Last Modified time: 2017-06-02 17:48:12 */ // Import Angular Classes: import { Injectable } from '@angular/core'; import { NgZone } from '@angular/core'; // Import Libraries: import * as d3 from 'd3'; import { Subject } from 'rxjs/Subject'; import '../../utilities/rxjs-operators'; // Import Application Classes import { RendererService } from '../services/Renderer.service'; import { ChartUndoRedoService } from '../services/ChartUndoRedo.service'; import { LabelDefinitions } from '../definitions/Label.definitions'; // Import Model Classes: import { Objective } from '../../../model/Objective'; import { PrimitiveObjective } from '../../../model/PrimitiveObjective'; import { AbstractObjective } from '../../../model/AbstractObjective'; import { RowData, CellData, LabelData, RendererConfig } from '../../../types/RendererData.types'; import { RendererUpdate } from '../../../types/RendererData.types'; import { ObjectivesRecord } from '../../../types/Record.types'; /* This class contains all the logic for dragging objective labels change the order of objectives in the objective and summary charts. Any objective label can be dragged within the confines of its parent label's Dimension Two so that it may be reordered with respect to its siblings (ie. the other children of the parent). The rows of the objective and summary charts are reordered to reflect the change in the label ordering when a label is released. */ @Injectable() export class ReorderObjectivesInteraction { // ======================================================================================== // Fields // ======================================================================================== public lastRendererUpdate: RendererUpdate; private labelRootContainer: d3.Selection<any,any,any,any>; private reorderSubject: Subject<boolean>; private ignoreReorder: boolean; // Whether the drag events should be ignored. If true, all dragging of the current label is ignored. // Fields used to store information about the active dragging event chain. private reorderObjectiveMouseOffset: number; // Offset of the mouse from the Coordinate Two position of the label that is to be dragged. This is set when dragging first begins. private totalCoordTwoChange: number = 0; // The Coordinate Two distance that the label has been moved so far. private containerToReorder: d3.Selection<any, any, any, any>; // The the d3 selection of the 'g' element that holds the label being reordered. private parentObjectiveName: string; // The name of the parent objective for the label being reordered. private parentContainer: d3.Selection<any, any, any, any>; // The selection of the container that holds the container for the label being reordered. private siblingContainers: d3.Selection<any, any, any, any>; // The selection of label containers s.t. every label container is at the same level in the label hierarchy as containerToReorder and also has the same parent label. private objectiveDimensionTwo: number; // The Dimension Two (height if vertical, width of horizontal) of the label being dragged. private objectiveCoordTwoOffset: number; // The initial Coordinate Two position (y if vertical, x if horizontal) of the label being reordered. private maxCoordinateTwo: number; // The maximum Coordinate Two that label being reordered can have before it exits the label area. private currentObjectiveIndex: number; // The index of the label being reordered in the list of siblings. private newObjectiveIndex: number; // The new index of the label as a result of the dragging. private jumpPoints: number[]; // The list of points that define what position the label being reordered has been moved to. // ======================================================================================== // Constructor // ======================================================================================== /* @returns {void} @description Used for Angular's dependency injection ONLY. It should not be used to do any initialization of the class. This constructor will be called automatically when Angular constructs an instance of this class prior to dependency injection. */ constructor( private rendererService: RendererService, private chartUndoRedoService: ChartUndoRedoService) { this.chartUndoRedoService.undoRedoDispatcher.on(this.chartUndoRedoService.OBJECTIVES_CHANGE, this.changeRowOrder); } // ======================================================================================== // Methods // ======================================================================================== /* @param enableReordering - Whether or not to enable dragging to reorder objectives. @returns {void} @description Toggles clicking and dragging labels in the label area to reorder objectives. Both abstract and primitive objectives can be reordered via label dragging when the user interaction is enabled. Dragging is implemented using d3's dragging system and makes use of all three drag events. 'start' is used to perform setup that is required to for dragging to work properly and is called before the 'drag' events fire. 'drag' is used to implement the visual dragging mechanism. Note that the handler for these events, reorderObjectives, only updates the visual display of the objective area. 'end' is used to actually reorder the objectives within the objective hierarchy, and then re-render the ValueChart via the ValueChartDirective. */ public toggleObjectiveReordering(enableReordering: boolean, labelRootContainer: d3.Selection<any, any, any, any>, rendererUpdate: RendererUpdate): Subject<boolean> { this.lastRendererUpdate = rendererUpdate; this.labelRootContainer = labelRootContainer; var labelOutlines: d3.Selection<any, any, any, any> = labelRootContainer.selectAll('.' + LabelDefinitions.SUBCONTAINER_OUTLINE); var labelTexts: d3.Selection<any, any, any, any> = labelRootContainer.selectAll('.' + LabelDefinitions.SUBCONTAINER_TEXT); var dragToReorder: d3.DragBehavior<any, any, any> = d3.drag(); if (enableReordering) { dragToReorder .on('start', this.startReorderObjectives) .on('drag', this.reorderObjectives) .on('end', this.endReorderObjectives); } labelOutlines.call(dragToReorder); labelTexts.call(dragToReorder); this.reorderSubject = new Subject(); return this.reorderSubject; } // This function is called when a user first begins to drag a label to rearrange the ordering of objectives. It contains all the logic required to initialize the drag, // including determining the bounds that the label can be dragged in, the points where the label is considered to have switched positions, etc. private startReorderObjectives = (d: LabelData, i: number) => { // Reset variables. this.ignoreReorder = false; // Whether the drag events should be ignored. If true, all further dragging of the current label will be ignored. this.reorderObjectiveMouseOffset = undefined; // Offset of the mouse from the Coordinate Two position of the label that is to be dragged. this.totalCoordTwoChange = 0; // The Coordinate Two distance that the label has been moved so far. this.containerToReorder = d3.select('#label-' + d.objective.getId() + '-container'); // The container that holds the label being reordered. this.parentObjectiveName = (<Element>this.containerToReorder.node()).getAttribute('parent'); // The name of the parent objective for the label being reordered. // If the selected label is the root label, then it is not possible to reorder, and all further drag events for this selection should be ignored. if (this.parentObjectiveName === LabelDefinitions.ROOT_CONTAINER_NAME) { this.ignoreReorder = true; return; } this.chartUndoRedoService.saveObjectivesRecord(this.lastRendererUpdate.valueChart.getRootObjectives()); this.parentContainer = d3.select('#label-' + this.parentObjectiveName + '-container'); // The container that holds the container for the label being reordered. this.siblingContainers = this.parentContainer.selectAll('g[parent="' + this.parentObjectiveName + '"]'); // The selection of label containers s.t. every label container is at the same level as containerToReorder, with the same parent. // Note: siblingsConatiners includes containerToReorder. // Set all the siblings that are NOT being moved to be partially transparent. this.siblingContainers.style('opacity', 0.5); this.containerToReorder.style('opacity', 1); var parentOutline: d3.Selection<any, any, any, any> = this.parentContainer.select('rect'); // Select the rect that outlines the parent label of the label being reordered. var currentOutline: d3.Selection<any, any, any, any> = this.containerToReorder.select('rect'); // Select the rect that outlines the label being reordered. this.objectiveDimensionTwo = +currentOutline.attr(this.lastRendererUpdate.rendererConfig.dimensionTwo); // Determine the Dimension Two (height if vertical, width of horizontal) of the label being dragged. this.maxCoordinateTwo = +parentOutline.attr(this.lastRendererUpdate.rendererConfig.dimensionTwo) - this.objectiveDimensionTwo; // Determine the maximum Coordinate Two of the label being reordered. this.objectiveCoordTwoOffset = +currentOutline.attr(this.lastRendererUpdate.rendererConfig.coordinateTwo); // Determine the initial Coordinate Two position (y if vertical, x if horizontal) of the label being reordered. this.currentObjectiveIndex = this.siblingContainers.nodes().indexOf(this.containerToReorder.node()); // Determine the index of the label being reordered in the list of siblings. this.newObjectiveIndex = this.currentObjectiveIndex; this.jumpPoints = [0]; // Initialize the list of points which define what position the label being reordered has been moved to. this.siblingContainers.select('rect').nodes().forEach((el: Element) => { if (el !== undefined) { // For each of the labels that the label being reordered can be switched with, determine its Coordinate Two midpoint. This is used to determine what position the label being reordered has been moved to. let selection: d3.Selection<any, any, any, any> = d3.select(el); let jumpPoint: number = (+selection.attr(this.lastRendererUpdate.rendererConfig.dimensionTwo) / 2) + +selection.attr(this.lastRendererUpdate.rendererConfig.coordinateTwo); this.jumpPoints.push(jumpPoint); } }); this.jumpPoints.push(this.lastRendererUpdate.rendererConfig.dimensionTwoSize); } // This function is called whenever a label that is being reordered is dragged by the user. It contains the logic which updates the // position of the label so the user knows where they have dragged it to as well as the code that determines what position the label will be in when dragging ends. private reorderObjectives = (d: LabelData, i: number) => { // Do nothing if we are ignoring the current dragging of the label. if (this.ignoreReorder) { return; } // Get the change in Coordinate Two from the d3 event. Note that although we are getting coordinateTwo, not dCoordinateTwo, this is the still the change. // The reason for this is because when a label is dragged, the transform of label container is changed, which can changes cooordinateTwo of the outline rectangle inside the container. // THis change is equal to deltaCoordinateTwo, meaning d3.event.cooordinateTwo is reset to 0 at the end of cooordinateTwo drag event, making cooordinateTwo really dCoordinateTwo var deltaCoordinateTwo: number = (<any>d3.event)[this.lastRendererUpdate.rendererConfig.coordinateTwo]; // If we have not yet determined the mouse offset, then this is the first drag event that has been fired, and the mouse offset from 0 should the current mouse position. if (this.reorderObjectiveMouseOffset === undefined) { this.reorderObjectiveMouseOffset = deltaCoordinateTwo; } deltaCoordinateTwo = deltaCoordinateTwo - this.reorderObjectiveMouseOffset; // Subtract the mouse offset to get the change in Coordinate Two from the 0 point. // Calculate the current Coordinate Two position of the label that is being reordered. // This is the recent change (deltaCoordinateTwo) + the totalChange so far (this.totalCoordTwoChange) + the offset of the label before dragging began (this.objectiveCoordTwoOffset) var currentCoordTwoPosition: number = deltaCoordinateTwo + this.totalCoordTwoChange + this.objectiveCoordTwoOffset; // Make sure that the label does not exit the bounds of the label area. if (currentCoordTwoPosition < 0) { deltaCoordinateTwo = 0 - this.totalCoordTwoChange - this.objectiveCoordTwoOffset; } else if (currentCoordTwoPosition > this.maxCoordinateTwo) { deltaCoordinateTwo = this.maxCoordinateTwo - this.totalCoordTwoChange - this.objectiveCoordTwoOffset; } // Add the most recent change in Coordinate Two to the total change so far. this.totalCoordTwoChange += deltaCoordinateTwo; // If we are dragging the label up, then we want to check the current position of the label from its top. // If we are dragging the label down, then we want to check the current position of the label form its bottom. var labelDimensionTwoOffset: number = (this.totalCoordTwoChange > 0) ? this.objectiveDimensionTwo : 0; // Determine which of the two jump points the label is current between, and assigned its new position accordingly. for (var i = 0; i < this.jumpPoints.length; i++) { if (this.totalCoordTwoChange + labelDimensionTwoOffset > (this.jumpPoints[i] - this.objectiveCoordTwoOffset) && this.totalCoordTwoChange + labelDimensionTwoOffset < (this.jumpPoints[i + 1] - this.objectiveCoordTwoOffset)) { this.newObjectiveIndex = i; break; } } // If we were dragging down, then the index is one off and must be decremented. if (this.totalCoordTwoChange > 0) this.newObjectiveIndex--; // Retrieved the previous transform of the label we are dragging so that it can be incremented properly. var previousTransform: string = this.containerToReorder.attr('transform'); // Generate the new transform. var labelTransform: string = this.rendererService.incrementTransform(this.lastRendererUpdate.viewConfig, previousTransform, 0, deltaCoordinateTwo); // Apply the new transformation to the label. this.containerToReorder.attr('transform', labelTransform); } // This function is called when the label that is being reordered is released by the user, and dragging ends. It contains the logic for re-rendering the ValueChart according // to the labels new position. private endReorderObjectives = (d: LabelData, i: number) => { // Do nothing if we are ignoring the current dragging of the label. if (this.ignoreReorder) { return; } // Get the label data for the siblings of the label we arranged. Note that this contains the label data for the label we rearranged. var parentData: LabelData = this.parentContainer.datum(); // Move the label data for the label we rearranged to its new position in the array of labels. if (this.newObjectiveIndex !== this.currentObjectiveIndex) { // Reorder the label data. let temp: LabelData = parentData.subLabelData.splice(this.currentObjectiveIndex, 1)[0]; parentData.subLabelData.splice(this.newObjectiveIndex, 0, temp); // Reorder the Objectives let siblingObjectives: Objective[] = (<AbstractObjective>parentData.objective).getDirectSubObjectives() let tempObjective: Objective = siblingObjectives.splice(this.currentObjectiveIndex, 1)[0]; siblingObjectives.splice(this.newObjectiveIndex, 0, tempObjective); } else { // No changes were made, so delete the change record that was created in startReorderObjectives. this.chartUndoRedoService.deleteNewestRecord(); this.lastRendererUpdate.renderRequired.value = true; } // Select all the label data, not just the siblings of the label we moved. var labelData: LabelData[] = <any> d3.select('g[parent=' + LabelDefinitions.ROOT_CONTAINER_NAME + ']').data(); // Re-arrange the rows of the objective and summary charts according to the new objective ordering. Note this triggers change detection in ValueChartDirective that // updates the object and summary charts. This is to avoid making the labelRenderer dependent on the other renderers. this.lastRendererUpdate.valueChart.setRootObjectives(this.getOrderedRootObjectives(labelData)); this.siblingContainers.style('opacity', 1); this.containerToReorder.style('opacity', 1); this.reorderSubject.next(true); } // This function extracts the ordering of objectives from the ordering of labels. private getOrderedRootObjectives(labelData: LabelData[]): Objective[] { var rootObjectives: Objective[] = []; labelData.forEach((labelDatum: LabelData) => { var objective: Objective = labelDatum.objective; if (labelDatum.depthOfChildren !== 0) { (<AbstractObjective>objective).setDirectSubObjectives(this.getOrderedRootObjectives(labelDatum.subLabelData)); } rootObjectives.push(objective); }); return rootObjectives; } changeRowOrder = (objectivesRecord: ObjectivesRecord) => { this.lastRendererUpdate.valueChart.setRootObjectives(objectivesRecord.rootObjectives); this.lastRendererUpdate.labelData[0] = undefined; this.reorderSubject.next(true); } }
aaronpmishkin/CUCSC-ValueCharts
client/modules/ValueChart/interactions/ReorderObjectives.interaction.ts
TypeScript
apache-2.0
17,688
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * (C) Copyright 2009-2020, Arnaud Roques * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of PlantUML. * * 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. * * * Original Author: Arnaud Roques */ package net.sourceforge.plantuml.creole.command; import net.sourceforge.plantuml.ISkinSimple; import net.sourceforge.plantuml.command.regex.Matcher2; import net.sourceforge.plantuml.command.regex.MyPattern; import net.sourceforge.plantuml.command.regex.Pattern2; import net.sourceforge.plantuml.creole.Parser; import net.sourceforge.plantuml.creole.legacy.StripeSimple; import net.sourceforge.plantuml.graphic.Splitter; import net.sourceforge.plantuml.ugraphic.color.HColor; public class CommandCreoleSprite implements Command { @Override public String startingChars() { return "<"; } private static final Pattern2 pattern = MyPattern.cmpile("^(" + Splitter.spritePattern2 + ")"); private CommandCreoleSprite() { } public static Command create() { return new CommandCreoleSprite(); } public int matchingSize(String line) { final Matcher2 m = pattern.matcher(line); if (m.find() == false) return 0; return m.group(1).length(); } public String executeAndGetRemaining(String line, StripeSimple stripe) { final Matcher2 m = pattern.matcher(line); if (m.find() == false) throw new IllegalStateException(); final String src = m.group(2); final double scale = Parser.getScale(m.group(3), 1); final String colorName = Parser.getColor(m.group(3)); HColor color = null; if (colorName != null) { final ISkinSimple skinParam = stripe.getSkinParam(); color = skinParam.getIHtmlColorSet().getColorOrWhite(skinParam.getThemeStyle(), colorName); } stripe.addSprite(src, scale, color); return line.substring(m.group(1).length()); } }
talsma-ict/umldoclet
src/plantuml-asl/src/net/sourceforge/plantuml/creole/command/CommandCreoleSprite.java
Java
apache-2.0
2,672
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; using System.Diagnostics; using TrashyWindowControl; namespace SetCoordinatesExample { class Program { static void Main(string[] args) { //make sure a process called "notepad" is already running befor starting this programm! WindowControl twc = new WindowControl(); twc.process = Process.GetProcessesByName("notepad").FirstOrDefault(); char input; Console.WriteLine("Move the window with WASD!"); Console.WriteLine("You can change the height with R/F and the width with T/G"); do { input = Console.ReadKey().KeyChar; input = Char.ToLower(input); switch (input) { case 'w': { twc.y = twc.y - 5; break; } case 's': { twc.y = twc.y + 5; break; } case 'd': { twc.x = twc.x + 5; break; } case 'a': { twc.x = twc.x - 5; break; } case 'r': { twc.height = twc.height + 5; break; } case 'f': { twc.height = twc.height - 5; break; } case 't': { twc.width = twc.width + 5; break; } case 'g': { twc.width = twc.width - 5; break; } } } while (true); } } }
sh1n1xs/TrashyWindowControl
TrashyWindowControlExamples/SetCoordinatesExample/Program.cs
C#
apache-2.0
2,416
/** */ package CIM15.IEC61968.Metering; import CIM15.IEC61968.Customers.CustomerAgreement; import CIM15.IEC61968.Customers.CustomersPackage; import CIM15.IEC61970.Core.IdentifiedObject; import CIM15.IEC61970.Domain.DateTimeInterval; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>End Device Control</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link CIM15.IEC61968.Metering.EndDeviceControl#getDemandResponseProgram <em>Demand Response Program</em>}</li> * <li>{@link CIM15.IEC61968.Metering.EndDeviceControl#getDrProgramLevel <em>Dr Program Level</em>}</li> * <li>{@link CIM15.IEC61968.Metering.EndDeviceControl#isDrProgramMandatory <em>Dr Program Mandatory</em>}</li> * <li>{@link CIM15.IEC61968.Metering.EndDeviceControl#getCustomerAgreement <em>Customer Agreement</em>}</li> * <li>{@link CIM15.IEC61968.Metering.EndDeviceControl#getType <em>Type</em>}</li> * <li>{@link CIM15.IEC61968.Metering.EndDeviceControl#getScheduledInterval <em>Scheduled Interval</em>}</li> * <li>{@link CIM15.IEC61968.Metering.EndDeviceControl#getEndDeviceGroup <em>End Device Group</em>}</li> * <li>{@link CIM15.IEC61968.Metering.EndDeviceControl#getEndDevice <em>End Device</em>}</li> * <li>{@link CIM15.IEC61968.Metering.EndDeviceControl#getPriceSignal <em>Price Signal</em>}</li> * </ul> * </p> * * @generated */ public class EndDeviceControl extends IdentifiedObject { /** * The cached value of the '{@link #getDemandResponseProgram() <em>Demand Response Program</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDemandResponseProgram() * @generated * @ordered */ protected DemandResponseProgram demandResponseProgram; /** * The default value of the '{@link #getDrProgramLevel() <em>Dr Program Level</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDrProgramLevel() * @generated * @ordered */ protected static final int DR_PROGRAM_LEVEL_EDEFAULT = 0; /** * The cached value of the '{@link #getDrProgramLevel() <em>Dr Program Level</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDrProgramLevel() * @generated * @ordered */ protected int drProgramLevel = DR_PROGRAM_LEVEL_EDEFAULT; /** * This is true if the Dr Program Level attribute has been set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ protected boolean drProgramLevelESet; /** * The default value of the '{@link #isDrProgramMandatory() <em>Dr Program Mandatory</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isDrProgramMandatory() * @generated * @ordered */ protected static final boolean DR_PROGRAM_MANDATORY_EDEFAULT = false; /** * The cached value of the '{@link #isDrProgramMandatory() <em>Dr Program Mandatory</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isDrProgramMandatory() * @generated * @ordered */ protected boolean drProgramMandatory = DR_PROGRAM_MANDATORY_EDEFAULT; /** * This is true if the Dr Program Mandatory attribute has been set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ protected boolean drProgramMandatoryESet; /** * The cached value of the '{@link #getCustomerAgreement() <em>Customer Agreement</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getCustomerAgreement() * @generated * @ordered */ protected CustomerAgreement customerAgreement; /** * The default value of the '{@link #getType() <em>Type</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getType() * @generated * @ordered */ protected static final String TYPE_EDEFAULT = null; /** * The cached value of the '{@link #getType() <em>Type</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getType() * @generated * @ordered */ protected String type = TYPE_EDEFAULT; /** * This is true if the Type attribute has been set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ protected boolean typeESet; /** * The cached value of the '{@link #getScheduledInterval() <em>Scheduled Interval</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getScheduledInterval() * @generated * @ordered */ protected DateTimeInterval scheduledInterval; /** * The cached value of the '{@link #getEndDeviceGroup() <em>End Device Group</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getEndDeviceGroup() * @generated * @ordered */ protected EndDeviceGroup endDeviceGroup; /** * The cached value of the '{@link #getEndDevice() <em>End Device</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getEndDevice() * @generated * @ordered */ protected EndDevice endDevice; /** * The default value of the '{@link #getPriceSignal() <em>Price Signal</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getPriceSignal() * @generated * @ordered */ protected static final float PRICE_SIGNAL_EDEFAULT = 0.0F; /** * The cached value of the '{@link #getPriceSignal() <em>Price Signal</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getPriceSignal() * @generated * @ordered */ protected float priceSignal = PRICE_SIGNAL_EDEFAULT; /** * This is true if the Price Signal attribute has been set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ protected boolean priceSignalESet; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected EndDeviceControl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return MeteringPackage.Literals.END_DEVICE_CONTROL; } /** * Returns the value of the '<em><b>Demand Response Program</b></em>' reference. * It is bidirectional and its opposite is '{@link CIM15.IEC61968.Metering.DemandResponseProgram#getEndDeviceControls <em>End Device Controls</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Demand Response Program</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Demand Response Program</em>' reference. * @see #setDemandResponseProgram(DemandResponseProgram) * @see CIM15.IEC61968.Metering.DemandResponseProgram#getEndDeviceControls * @generated */ public DemandResponseProgram getDemandResponseProgram() { if (demandResponseProgram != null && demandResponseProgram.eIsProxy()) { InternalEObject oldDemandResponseProgram = (InternalEObject)demandResponseProgram; demandResponseProgram = (DemandResponseProgram)eResolveProxy(oldDemandResponseProgram); if (demandResponseProgram != oldDemandResponseProgram) { } } return demandResponseProgram; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public DemandResponseProgram basicGetDemandResponseProgram() { return demandResponseProgram; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetDemandResponseProgram(DemandResponseProgram newDemandResponseProgram, NotificationChain msgs) { DemandResponseProgram oldDemandResponseProgram = demandResponseProgram; demandResponseProgram = newDemandResponseProgram; return msgs; } /** * Sets the value of the '{@link CIM15.IEC61968.Metering.EndDeviceControl#getDemandResponseProgram <em>Demand Response Program</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Demand Response Program</em>' reference. * @see #getDemandResponseProgram() * @generated */ public void setDemandResponseProgram(DemandResponseProgram newDemandResponseProgram) { if (newDemandResponseProgram != demandResponseProgram) { NotificationChain msgs = null; if (demandResponseProgram != null) msgs = ((InternalEObject)demandResponseProgram).eInverseRemove(this, MeteringPackage.DEMAND_RESPONSE_PROGRAM__END_DEVICE_CONTROLS, DemandResponseProgram.class, msgs); if (newDemandResponseProgram != null) msgs = ((InternalEObject)newDemandResponseProgram).eInverseAdd(this, MeteringPackage.DEMAND_RESPONSE_PROGRAM__END_DEVICE_CONTROLS, DemandResponseProgram.class, msgs); msgs = basicSetDemandResponseProgram(newDemandResponseProgram, msgs); if (msgs != null) msgs.dispatch(); } } /** * Returns the value of the '<em><b>Dr Program Level</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Dr Program Level</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Dr Program Level</em>' attribute. * @see #isSetDrProgramLevel() * @see #unsetDrProgramLevel() * @see #setDrProgramLevel(int) * @generated */ public int getDrProgramLevel() { return drProgramLevel; } /** * Sets the value of the '{@link CIM15.IEC61968.Metering.EndDeviceControl#getDrProgramLevel <em>Dr Program Level</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Dr Program Level</em>' attribute. * @see #isSetDrProgramLevel() * @see #unsetDrProgramLevel() * @see #getDrProgramLevel() * @generated */ public void setDrProgramLevel(int newDrProgramLevel) { drProgramLevel = newDrProgramLevel; drProgramLevelESet = true; } /** * Unsets the value of the '{@link CIM15.IEC61968.Metering.EndDeviceControl#getDrProgramLevel <em>Dr Program Level</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isSetDrProgramLevel() * @see #getDrProgramLevel() * @see #setDrProgramLevel(int) * @generated */ public void unsetDrProgramLevel() { drProgramLevel = DR_PROGRAM_LEVEL_EDEFAULT; drProgramLevelESet = false; } /** * Returns whether the value of the '{@link CIM15.IEC61968.Metering.EndDeviceControl#getDrProgramLevel <em>Dr Program Level</em>}' attribute is set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return whether the value of the '<em>Dr Program Level</em>' attribute is set. * @see #unsetDrProgramLevel() * @see #getDrProgramLevel() * @see #setDrProgramLevel(int) * @generated */ public boolean isSetDrProgramLevel() { return drProgramLevelESet; } /** * Returns the value of the '<em><b>Dr Program Mandatory</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Dr Program Mandatory</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Dr Program Mandatory</em>' attribute. * @see #isSetDrProgramMandatory() * @see #unsetDrProgramMandatory() * @see #setDrProgramMandatory(boolean) * @generated */ public boolean isDrProgramMandatory() { return drProgramMandatory; } /** * Sets the value of the '{@link CIM15.IEC61968.Metering.EndDeviceControl#isDrProgramMandatory <em>Dr Program Mandatory</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Dr Program Mandatory</em>' attribute. * @see #isSetDrProgramMandatory() * @see #unsetDrProgramMandatory() * @see #isDrProgramMandatory() * @generated */ public void setDrProgramMandatory(boolean newDrProgramMandatory) { drProgramMandatory = newDrProgramMandatory; drProgramMandatoryESet = true; } /** * Unsets the value of the '{@link CIM15.IEC61968.Metering.EndDeviceControl#isDrProgramMandatory <em>Dr Program Mandatory</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isSetDrProgramMandatory() * @see #isDrProgramMandatory() * @see #setDrProgramMandatory(boolean) * @generated */ public void unsetDrProgramMandatory() { drProgramMandatory = DR_PROGRAM_MANDATORY_EDEFAULT; drProgramMandatoryESet = false; } /** * Returns whether the value of the '{@link CIM15.IEC61968.Metering.EndDeviceControl#isDrProgramMandatory <em>Dr Program Mandatory</em>}' attribute is set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return whether the value of the '<em>Dr Program Mandatory</em>' attribute is set. * @see #unsetDrProgramMandatory() * @see #isDrProgramMandatory() * @see #setDrProgramMandatory(boolean) * @generated */ public boolean isSetDrProgramMandatory() { return drProgramMandatoryESet; } /** * Returns the value of the '<em><b>Customer Agreement</b></em>' reference. * It is bidirectional and its opposite is '{@link CIM15.IEC61968.Customers.CustomerAgreement#getEndDeviceControls <em>End Device Controls</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Customer Agreement</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Customer Agreement</em>' reference. * @see #setCustomerAgreement(CustomerAgreement) * @see CIM15.IEC61968.Customers.CustomerAgreement#getEndDeviceControls * @generated */ public CustomerAgreement getCustomerAgreement() { if (customerAgreement != null && customerAgreement.eIsProxy()) { InternalEObject oldCustomerAgreement = (InternalEObject)customerAgreement; customerAgreement = (CustomerAgreement)eResolveProxy(oldCustomerAgreement); if (customerAgreement != oldCustomerAgreement) { } } return customerAgreement; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public CustomerAgreement basicGetCustomerAgreement() { return customerAgreement; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetCustomerAgreement(CustomerAgreement newCustomerAgreement, NotificationChain msgs) { CustomerAgreement oldCustomerAgreement = customerAgreement; customerAgreement = newCustomerAgreement; return msgs; } /** * Sets the value of the '{@link CIM15.IEC61968.Metering.EndDeviceControl#getCustomerAgreement <em>Customer Agreement</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Customer Agreement</em>' reference. * @see #getCustomerAgreement() * @generated */ public void setCustomerAgreement(CustomerAgreement newCustomerAgreement) { if (newCustomerAgreement != customerAgreement) { NotificationChain msgs = null; if (customerAgreement != null) msgs = ((InternalEObject)customerAgreement).eInverseRemove(this, CustomersPackage.CUSTOMER_AGREEMENT__END_DEVICE_CONTROLS, CustomerAgreement.class, msgs); if (newCustomerAgreement != null) msgs = ((InternalEObject)newCustomerAgreement).eInverseAdd(this, CustomersPackage.CUSTOMER_AGREEMENT__END_DEVICE_CONTROLS, CustomerAgreement.class, msgs); msgs = basicSetCustomerAgreement(newCustomerAgreement, msgs); if (msgs != null) msgs.dispatch(); } } /** * Returns the value of the '<em><b>Type</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Type</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Type</em>' attribute. * @see #isSetType() * @see #unsetType() * @see #setType(String) * @generated */ public String getType() { return type; } /** * Sets the value of the '{@link CIM15.IEC61968.Metering.EndDeviceControl#getType <em>Type</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Type</em>' attribute. * @see #isSetType() * @see #unsetType() * @see #getType() * @generated */ public void setType(String newType) { type = newType; typeESet = true; } /** * Unsets the value of the '{@link CIM15.IEC61968.Metering.EndDeviceControl#getType <em>Type</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isSetType() * @see #getType() * @see #setType(String) * @generated */ public void unsetType() { type = TYPE_EDEFAULT; typeESet = false; } /** * Returns whether the value of the '{@link CIM15.IEC61968.Metering.EndDeviceControl#getType <em>Type</em>}' attribute is set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return whether the value of the '<em>Type</em>' attribute is set. * @see #unsetType() * @see #getType() * @see #setType(String) * @generated */ public boolean isSetType() { return typeESet; } /** * Returns the value of the '<em><b>Scheduled Interval</b></em>' containment reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Scheduled Interval</em>' containment reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Scheduled Interval</em>' containment reference. * @see #setScheduledInterval(DateTimeInterval) * @generated */ public DateTimeInterval getScheduledInterval() { return scheduledInterval; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetScheduledInterval(DateTimeInterval newScheduledInterval, NotificationChain msgs) { DateTimeInterval oldScheduledInterval = scheduledInterval; scheduledInterval = newScheduledInterval; return msgs; } /** * Sets the value of the '{@link CIM15.IEC61968.Metering.EndDeviceControl#getScheduledInterval <em>Scheduled Interval</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Scheduled Interval</em>' containment reference. * @see #getScheduledInterval() * @generated */ public void setScheduledInterval(DateTimeInterval newScheduledInterval) { if (newScheduledInterval != scheduledInterval) { NotificationChain msgs = null; if (scheduledInterval != null) msgs = ((InternalEObject)scheduledInterval).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - MeteringPackage.END_DEVICE_CONTROL__SCHEDULED_INTERVAL, null, msgs); if (newScheduledInterval != null) msgs = ((InternalEObject)newScheduledInterval).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - MeteringPackage.END_DEVICE_CONTROL__SCHEDULED_INTERVAL, null, msgs); msgs = basicSetScheduledInterval(newScheduledInterval, msgs); if (msgs != null) msgs.dispatch(); } } /** * Returns the value of the '<em><b>End Device Group</b></em>' reference. * It is bidirectional and its opposite is '{@link CIM15.IEC61968.Metering.EndDeviceGroup#getEndDeviceControls <em>End Device Controls</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>End Device Group</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>End Device Group</em>' reference. * @see #setEndDeviceGroup(EndDeviceGroup) * @see CIM15.IEC61968.Metering.EndDeviceGroup#getEndDeviceControls * @generated */ public EndDeviceGroup getEndDeviceGroup() { if (endDeviceGroup != null && endDeviceGroup.eIsProxy()) { InternalEObject oldEndDeviceGroup = (InternalEObject)endDeviceGroup; endDeviceGroup = (EndDeviceGroup)eResolveProxy(oldEndDeviceGroup); if (endDeviceGroup != oldEndDeviceGroup) { } } return endDeviceGroup; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EndDeviceGroup basicGetEndDeviceGroup() { return endDeviceGroup; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetEndDeviceGroup(EndDeviceGroup newEndDeviceGroup, NotificationChain msgs) { EndDeviceGroup oldEndDeviceGroup = endDeviceGroup; endDeviceGroup = newEndDeviceGroup; return msgs; } /** * Sets the value of the '{@link CIM15.IEC61968.Metering.EndDeviceControl#getEndDeviceGroup <em>End Device Group</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>End Device Group</em>' reference. * @see #getEndDeviceGroup() * @generated */ public void setEndDeviceGroup(EndDeviceGroup newEndDeviceGroup) { if (newEndDeviceGroup != endDeviceGroup) { NotificationChain msgs = null; if (endDeviceGroup != null) msgs = ((InternalEObject)endDeviceGroup).eInverseRemove(this, MeteringPackage.END_DEVICE_GROUP__END_DEVICE_CONTROLS, EndDeviceGroup.class, msgs); if (newEndDeviceGroup != null) msgs = ((InternalEObject)newEndDeviceGroup).eInverseAdd(this, MeteringPackage.END_DEVICE_GROUP__END_DEVICE_CONTROLS, EndDeviceGroup.class, msgs); msgs = basicSetEndDeviceGroup(newEndDeviceGroup, msgs); if (msgs != null) msgs.dispatch(); } } /** * Returns the value of the '<em><b>End Device</b></em>' reference. * It is bidirectional and its opposite is '{@link CIM15.IEC61968.Metering.EndDevice#getEndDeviceControls <em>End Device Controls</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>End Device</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>End Device</em>' reference. * @see #setEndDevice(EndDevice) * @see CIM15.IEC61968.Metering.EndDevice#getEndDeviceControls * @generated */ public EndDevice getEndDevice() { if (endDevice != null && endDevice.eIsProxy()) { InternalEObject oldEndDevice = (InternalEObject)endDevice; endDevice = (EndDevice)eResolveProxy(oldEndDevice); if (endDevice != oldEndDevice) { } } return endDevice; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EndDevice basicGetEndDevice() { return endDevice; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetEndDevice(EndDevice newEndDevice, NotificationChain msgs) { EndDevice oldEndDevice = endDevice; endDevice = newEndDevice; return msgs; } /** * Sets the value of the '{@link CIM15.IEC61968.Metering.EndDeviceControl#getEndDevice <em>End Device</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>End Device</em>' reference. * @see #getEndDevice() * @generated */ public void setEndDevice(EndDevice newEndDevice) { if (newEndDevice != endDevice) { NotificationChain msgs = null; if (endDevice != null) msgs = ((InternalEObject)endDevice).eInverseRemove(this, MeteringPackage.END_DEVICE__END_DEVICE_CONTROLS, EndDevice.class, msgs); if (newEndDevice != null) msgs = ((InternalEObject)newEndDevice).eInverseAdd(this, MeteringPackage.END_DEVICE__END_DEVICE_CONTROLS, EndDevice.class, msgs); msgs = basicSetEndDevice(newEndDevice, msgs); if (msgs != null) msgs.dispatch(); } } /** * Returns the value of the '<em><b>Price Signal</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Price Signal</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Price Signal</em>' attribute. * @see #isSetPriceSignal() * @see #unsetPriceSignal() * @see #setPriceSignal(float) * @generated */ public float getPriceSignal() { return priceSignal; } /** * Sets the value of the '{@link CIM15.IEC61968.Metering.EndDeviceControl#getPriceSignal <em>Price Signal</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Price Signal</em>' attribute. * @see #isSetPriceSignal() * @see #unsetPriceSignal() * @see #getPriceSignal() * @generated */ public void setPriceSignal(float newPriceSignal) { priceSignal = newPriceSignal; priceSignalESet = true; } /** * Unsets the value of the '{@link CIM15.IEC61968.Metering.EndDeviceControl#getPriceSignal <em>Price Signal</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isSetPriceSignal() * @see #getPriceSignal() * @see #setPriceSignal(float) * @generated */ public void unsetPriceSignal() { priceSignal = PRICE_SIGNAL_EDEFAULT; priceSignalESet = false; } /** * Returns whether the value of the '{@link CIM15.IEC61968.Metering.EndDeviceControl#getPriceSignal <em>Price Signal</em>}' attribute is set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return whether the value of the '<em>Price Signal</em>' attribute is set. * @see #unsetPriceSignal() * @see #getPriceSignal() * @see #setPriceSignal(float) * @generated */ public boolean isSetPriceSignal() { return priceSignalESet; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case MeteringPackage.END_DEVICE_CONTROL__DEMAND_RESPONSE_PROGRAM: if (demandResponseProgram != null) msgs = ((InternalEObject)demandResponseProgram).eInverseRemove(this, MeteringPackage.DEMAND_RESPONSE_PROGRAM__END_DEVICE_CONTROLS, DemandResponseProgram.class, msgs); return basicSetDemandResponseProgram((DemandResponseProgram)otherEnd, msgs); case MeteringPackage.END_DEVICE_CONTROL__CUSTOMER_AGREEMENT: if (customerAgreement != null) msgs = ((InternalEObject)customerAgreement).eInverseRemove(this, CustomersPackage.CUSTOMER_AGREEMENT__END_DEVICE_CONTROLS, CustomerAgreement.class, msgs); return basicSetCustomerAgreement((CustomerAgreement)otherEnd, msgs); case MeteringPackage.END_DEVICE_CONTROL__END_DEVICE_GROUP: if (endDeviceGroup != null) msgs = ((InternalEObject)endDeviceGroup).eInverseRemove(this, MeteringPackage.END_DEVICE_GROUP__END_DEVICE_CONTROLS, EndDeviceGroup.class, msgs); return basicSetEndDeviceGroup((EndDeviceGroup)otherEnd, msgs); case MeteringPackage.END_DEVICE_CONTROL__END_DEVICE: if (endDevice != null) msgs = ((InternalEObject)endDevice).eInverseRemove(this, MeteringPackage.END_DEVICE__END_DEVICE_CONTROLS, EndDevice.class, msgs); return basicSetEndDevice((EndDevice)otherEnd, msgs); } return super.eInverseAdd(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case MeteringPackage.END_DEVICE_CONTROL__DEMAND_RESPONSE_PROGRAM: return basicSetDemandResponseProgram(null, msgs); case MeteringPackage.END_DEVICE_CONTROL__CUSTOMER_AGREEMENT: return basicSetCustomerAgreement(null, msgs); case MeteringPackage.END_DEVICE_CONTROL__SCHEDULED_INTERVAL: return basicSetScheduledInterval(null, msgs); case MeteringPackage.END_DEVICE_CONTROL__END_DEVICE_GROUP: return basicSetEndDeviceGroup(null, msgs); case MeteringPackage.END_DEVICE_CONTROL__END_DEVICE: return basicSetEndDevice(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case MeteringPackage.END_DEVICE_CONTROL__DEMAND_RESPONSE_PROGRAM: if (resolve) return getDemandResponseProgram(); return basicGetDemandResponseProgram(); case MeteringPackage.END_DEVICE_CONTROL__DR_PROGRAM_LEVEL: return getDrProgramLevel(); case MeteringPackage.END_DEVICE_CONTROL__DR_PROGRAM_MANDATORY: return isDrProgramMandatory(); case MeteringPackage.END_DEVICE_CONTROL__CUSTOMER_AGREEMENT: if (resolve) return getCustomerAgreement(); return basicGetCustomerAgreement(); case MeteringPackage.END_DEVICE_CONTROL__TYPE: return getType(); case MeteringPackage.END_DEVICE_CONTROL__SCHEDULED_INTERVAL: return getScheduledInterval(); case MeteringPackage.END_DEVICE_CONTROL__END_DEVICE_GROUP: if (resolve) return getEndDeviceGroup(); return basicGetEndDeviceGroup(); case MeteringPackage.END_DEVICE_CONTROL__END_DEVICE: if (resolve) return getEndDevice(); return basicGetEndDevice(); case MeteringPackage.END_DEVICE_CONTROL__PRICE_SIGNAL: return getPriceSignal(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case MeteringPackage.END_DEVICE_CONTROL__DEMAND_RESPONSE_PROGRAM: setDemandResponseProgram((DemandResponseProgram)newValue); return; case MeteringPackage.END_DEVICE_CONTROL__DR_PROGRAM_LEVEL: setDrProgramLevel((Integer)newValue); return; case MeteringPackage.END_DEVICE_CONTROL__DR_PROGRAM_MANDATORY: setDrProgramMandatory((Boolean)newValue); return; case MeteringPackage.END_DEVICE_CONTROL__CUSTOMER_AGREEMENT: setCustomerAgreement((CustomerAgreement)newValue); return; case MeteringPackage.END_DEVICE_CONTROL__TYPE: setType((String)newValue); return; case MeteringPackage.END_DEVICE_CONTROL__SCHEDULED_INTERVAL: setScheduledInterval((DateTimeInterval)newValue); return; case MeteringPackage.END_DEVICE_CONTROL__END_DEVICE_GROUP: setEndDeviceGroup((EndDeviceGroup)newValue); return; case MeteringPackage.END_DEVICE_CONTROL__END_DEVICE: setEndDevice((EndDevice)newValue); return; case MeteringPackage.END_DEVICE_CONTROL__PRICE_SIGNAL: setPriceSignal((Float)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case MeteringPackage.END_DEVICE_CONTROL__DEMAND_RESPONSE_PROGRAM: setDemandResponseProgram((DemandResponseProgram)null); return; case MeteringPackage.END_DEVICE_CONTROL__DR_PROGRAM_LEVEL: unsetDrProgramLevel(); return; case MeteringPackage.END_DEVICE_CONTROL__DR_PROGRAM_MANDATORY: unsetDrProgramMandatory(); return; case MeteringPackage.END_DEVICE_CONTROL__CUSTOMER_AGREEMENT: setCustomerAgreement((CustomerAgreement)null); return; case MeteringPackage.END_DEVICE_CONTROL__TYPE: unsetType(); return; case MeteringPackage.END_DEVICE_CONTROL__SCHEDULED_INTERVAL: setScheduledInterval((DateTimeInterval)null); return; case MeteringPackage.END_DEVICE_CONTROL__END_DEVICE_GROUP: setEndDeviceGroup((EndDeviceGroup)null); return; case MeteringPackage.END_DEVICE_CONTROL__END_DEVICE: setEndDevice((EndDevice)null); return; case MeteringPackage.END_DEVICE_CONTROL__PRICE_SIGNAL: unsetPriceSignal(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case MeteringPackage.END_DEVICE_CONTROL__DEMAND_RESPONSE_PROGRAM: return demandResponseProgram != null; case MeteringPackage.END_DEVICE_CONTROL__DR_PROGRAM_LEVEL: return isSetDrProgramLevel(); case MeteringPackage.END_DEVICE_CONTROL__DR_PROGRAM_MANDATORY: return isSetDrProgramMandatory(); case MeteringPackage.END_DEVICE_CONTROL__CUSTOMER_AGREEMENT: return customerAgreement != null; case MeteringPackage.END_DEVICE_CONTROL__TYPE: return isSetType(); case MeteringPackage.END_DEVICE_CONTROL__SCHEDULED_INTERVAL: return scheduledInterval != null; case MeteringPackage.END_DEVICE_CONTROL__END_DEVICE_GROUP: return endDeviceGroup != null; case MeteringPackage.END_DEVICE_CONTROL__END_DEVICE: return endDevice != null; case MeteringPackage.END_DEVICE_CONTROL__PRICE_SIGNAL: return isSetPriceSignal(); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (drProgramLevel: "); if (drProgramLevelESet) result.append(drProgramLevel); else result.append("<unset>"); result.append(", drProgramMandatory: "); if (drProgramMandatoryESet) result.append(drProgramMandatory); else result.append("<unset>"); result.append(", type: "); if (typeESet) result.append(type); else result.append("<unset>"); result.append(", priceSignal: "); if (priceSignalESet) result.append(priceSignal); else result.append("<unset>"); result.append(')'); return result.toString(); } } // EndDeviceControl
SES-fortiss/SmartGridCoSimulation
core/cim15/src/CIM15/IEC61968/Metering/EndDeviceControl.java
Java
apache-2.0
33,206
#region License and Terms // MoreLINQ - Extensions to LINQ to Objects // Copysecond (c) 2017 Atif Aziz. All seconds 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. #endregion namespace MoreLinq { using System; using System.Collections.Generic; using System.Linq; static partial class MoreEnumerable { /// <summary> /// Performs a full outer join on two homogeneous sequences. /// Additional arguments specify key selection functions and result /// projection functions. /// </summary> /// <typeparam name="TSource"> /// The type of elements in the source sequence.</typeparam> /// <typeparam name="TKey"> /// The type of the key returned by the key selector function.</typeparam> /// <typeparam name="TResult"> /// The type of the result elements.</typeparam> /// <param name="first"> /// The first sequence to join fully.</param> /// <param name="second"> /// The second sequence to join fully.</param> /// <param name="keySelector"> /// Function that projects the key given an element of one of the /// sequences to join.</param> /// <param name="firstSelector"> /// Function that projects the result given just an element from /// <paramref name="first"/> where there is no corresponding element /// in <paramref name="second"/>.</param> /// <param name="secondSelector"> /// Function that projects the result given just an element from /// <paramref name="second"/> where there is no corresponding element /// in <paramref name="first"/>.</param> /// <param name="bothSelector"> /// Function that projects the result given an element from /// <paramref name="first"/> and an element from <paramref name="second"/> /// that match on a common key.</param> /// <returns>A sequence containing results projected from a full /// outer join of the two input sequences.</returns> public static IEnumerable<TResult> FullJoin<TSource, TKey, TResult>( this IEnumerable<TSource> first, IEnumerable<TSource> second, Func<TSource, TKey> keySelector, Func<TSource, TResult> firstSelector, Func<TSource, TResult> secondSelector, Func<TSource, TSource, TResult> bothSelector) { if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); return first.FullJoin(second, keySelector, firstSelector, secondSelector, bothSelector, null); } /// <summary> /// Performs a full outer join on two homogeneous sequences. /// Additional arguments specify key selection functions, result /// projection functions and a key comparer. /// </summary> /// <typeparam name="TSource"> /// The type of elements in the source sequence.</typeparam> /// <typeparam name="TKey"> /// The type of the key returned by the key selector function.</typeparam> /// <typeparam name="TResult"> /// The type of the result elements.</typeparam> /// <param name="first"> /// The first sequence to join fully.</param> /// <param name="second"> /// The second sequence to join fully.</param> /// <param name="keySelector"> /// Function that projects the key given an element of one of the /// sequences to join.</param> /// <param name="firstSelector"> /// Function that projects the result given just an element from /// <paramref name="first"/> where there is no corresponding element /// in <paramref name="second"/>.</param> /// <param name="secondSelector"> /// Function that projects the result given just an element from /// <paramref name="second"/> where there is no corresponding element /// in <paramref name="first"/>.</param> /// <param name="bothSelector"> /// Function that projects the result given an element from /// <paramref name="first"/> and an element from <paramref name="second"/> /// that match on a common key.</param> /// <param name="comparer"> /// The <see cref="IEqualityComparer{T}"/> instance used to compare /// keys for equality.</param> /// <returns>A sequence containing results projected from a full /// outer join of the two input sequences.</returns> public static IEnumerable<TResult> FullJoin<TSource, TKey, TResult>( this IEnumerable<TSource> first, IEnumerable<TSource> second, Func<TSource, TKey> keySelector, Func<TSource, TResult> firstSelector, Func<TSource, TResult> secondSelector, Func<TSource, TSource, TResult> bothSelector, IEqualityComparer<TKey>? comparer) { if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); return first.FullJoin(second, keySelector, keySelector, firstSelector, secondSelector, bothSelector, comparer); } /// <summary> /// Performs a full outer join on two heterogeneous sequences. /// Additional arguments specify key selection functions and result /// projection functions. /// </summary> /// <typeparam name="TFirst"> /// The type of elements in the first sequence.</typeparam> /// <typeparam name="TSecond"> /// The type of elements in the second sequence.</typeparam> /// <typeparam name="TKey"> /// The type of the key returned by the key selector functions.</typeparam> /// <typeparam name="TResult"> /// The type of the result elements.</typeparam> /// <param name="first"> /// The first sequence to join fully.</param> /// <param name="second"> /// The second sequence to join fully.</param> /// <param name="firstKeySelector"> /// Function that projects the key given an element from <paramref name="first"/>.</param> /// <param name="secondKeySelector"> /// Function that projects the key given an element from <paramref name="second"/>.</param> /// <param name="firstSelector"> /// Function that projects the result given just an element from /// <paramref name="first"/> where there is no corresponding element /// in <paramref name="second"/>.</param> /// <param name="secondSelector"> /// Function that projects the result given just an element from /// <paramref name="second"/> where there is no corresponding element /// in <paramref name="first"/>.</param> /// <param name="bothSelector"> /// Function that projects the result given an element from /// <paramref name="first"/> and an element from <paramref name="second"/> /// that match on a common key.</param> /// <returns>A sequence containing results projected from a full /// outer join of the two input sequences.</returns> public static IEnumerable<TResult> FullJoin<TFirst, TSecond, TKey, TResult>( this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TKey> firstKeySelector, Func<TSecond, TKey> secondKeySelector, Func<TFirst, TResult> firstSelector, Func<TSecond, TResult> secondSelector, Func<TFirst, TSecond, TResult> bothSelector) => first.FullJoin(second, firstKeySelector, secondKeySelector, firstSelector, secondSelector, bothSelector, null); /// <summary> /// Performs a full outer join on two heterogeneous sequences. /// Additional arguments specify key selection functions, result /// projection functions and a key comparer. /// </summary> /// <typeparam name="TFirst"> /// The type of elements in the first sequence.</typeparam> /// <typeparam name="TSecond"> /// The type of elements in the second sequence.</typeparam> /// <typeparam name="TKey"> /// The type of the key returned by the key selector functions.</typeparam> /// <typeparam name="TResult"> /// The type of the result elements.</typeparam> /// <param name="first"> /// The first sequence to join fully.</param> /// <param name="second"> /// The second sequence to join fully.</param> /// <param name="firstKeySelector"> /// Function that projects the key given an element from <paramref name="first"/>.</param> /// <param name="secondKeySelector"> /// Function that projects the key given an element from <paramref name="second"/>.</param> /// <param name="firstSelector"> /// Function that projects the result given just an element from /// <paramref name="first"/> where there is no corresponding element /// in <paramref name="second"/>.</param> /// <param name="secondSelector"> /// Function that projects the result given just an element from /// <paramref name="second"/> where there is no corresponding element /// in <paramref name="first"/>.</param> /// <param name="bothSelector"> /// Function that projects the result given an element from /// <paramref name="first"/> and an element from <paramref name="second"/> /// that match on a common key.</param> /// <param name="comparer"> /// The <see cref="IEqualityComparer{T}"/> instance used to compare /// keys for equality.</param> /// <returns>A sequence containing results projected from a full /// outer join of the two input sequences.</returns> public static IEnumerable<TResult> FullJoin<TFirst, TSecond, TKey, TResult>( this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TKey> firstKeySelector, Func<TSecond, TKey> secondKeySelector, Func<TFirst, TResult> firstSelector, Func<TSecond, TResult> secondSelector, Func<TFirst, TSecond, TResult> bothSelector, IEqualityComparer<TKey>? comparer) { if (first == null) throw new ArgumentNullException(nameof(first)); if (second == null) throw new ArgumentNullException(nameof(second)); if (firstKeySelector == null) throw new ArgumentNullException(nameof(firstKeySelector)); if (secondKeySelector == null) throw new ArgumentNullException(nameof(secondKeySelector)); if (firstSelector == null) throw new ArgumentNullException(nameof(firstSelector)); if (secondSelector == null) throw new ArgumentNullException(nameof(secondSelector)); if (bothSelector == null) throw new ArgumentNullException(nameof(bothSelector)); return _(); IEnumerable<TResult> _() { var seconds = second.Select(e => new KeyValuePair<TKey, TSecond>(secondKeySelector(e), e)).ToArray(); var secondLookup = seconds.ToLookup(e => e.Key, e => e.Value, comparer); var firstKeys = new HashSet<TKey>(comparer); foreach (var fe in first) { var key = firstKeySelector(fe); firstKeys.Add(key); using var se = secondLookup[key].GetEnumerator(); if (se.MoveNext()) { do { yield return bothSelector(fe, se.Current); } while (se.MoveNext()); } else { se.Dispose(); yield return firstSelector(fe); } } foreach (var se in seconds) { if (!firstKeys.Contains(se.Key)) yield return secondSelector(se.Value); } } } } }
morelinq/MoreLINQ
MoreLinq/FullJoin.cs
C#
apache-2.0
12,941
package pet // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "net/http" "github.com/go-swagger/go-swagger/httpkit" ) /*DeletePetBadRequest Invalid pet value swagger:response deletePetBadRequest */ type DeletePetBadRequest struct { } // NewDeletePetBadRequest creates DeletePetBadRequest with default headers values func NewDeletePetBadRequest() *DeletePetBadRequest { return &DeletePetBadRequest{} } // WriteResponse to the client func (o *DeletePetBadRequest) WriteResponse(rw http.ResponseWriter, producer httpkit.Producer) { rw.WriteHeader(400) }
Dataman-Cloud/drone
vendor/github.com/go-swagger/go-swagger/examples/generated/restapi/operations/pet/delete_pet_responses.go
GO
apache-2.0
655
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class SynthesizedEmbeddedNativeIntegerAttributeSymbol : SynthesizedEmbeddedAttributeSymbolBase { private readonly ImmutableArray<FieldSymbol> _fields; private readonly ImmutableArray<MethodSymbol> _constructors; private readonly TypeSymbol _boolType; private const string FieldName = "TransformFlags"; public SynthesizedEmbeddedNativeIntegerAttributeSymbol( string name, NamespaceSymbol containingNamespace, ModuleSymbol containingModule, NamedTypeSymbol systemAttributeType, TypeSymbol boolType) : base(name, containingNamespace, containingModule, baseType: systemAttributeType) { _boolType = boolType; var boolArrayType = TypeWithAnnotations.Create( ArrayTypeSymbol.CreateSZArray( boolType.ContainingAssembly, TypeWithAnnotations.Create(boolType))); _fields = ImmutableArray.Create<FieldSymbol>( new SynthesizedFieldSymbol( this, boolArrayType.Type, FieldName, isPublic: true, isReadOnly: true, isStatic: false)); _constructors = ImmutableArray.Create<MethodSymbol>( new SynthesizedEmbeddedAttributeConstructorWithBodySymbol( this, m => ImmutableArray<ParameterSymbol>.Empty, (f, s, p) => GenerateParameterlessConstructorBody(f, s)), new SynthesizedEmbeddedAttributeConstructorWithBodySymbol( this, m => ImmutableArray.Create(SynthesizedParameterSymbol.Create(m, boolArrayType, 0, RefKind.None)), (f, s, p) => GenerateBoolArrayConstructorBody(f, s, p))); // Ensure we never get out of sync with the description Debug.Assert(_constructors.Length == AttributeDescription.NativeIntegerAttribute.Signatures.Length); } internal override IEnumerable<FieldSymbol> GetFieldsToEmit() => _fields; public override ImmutableArray<MethodSymbol> Constructors => _constructors; internal override AttributeUsageInfo GetAttributeUsageInfo() { return new AttributeUsageInfo( AttributeTargets.Class | AttributeTargets.Event | AttributeTargets.Field | AttributeTargets.GenericParameter | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, allowMultiple: false, inherited: false); } private void GenerateParameterlessConstructorBody(SyntheticBoundNodeFactory factory, ArrayBuilder<BoundStatement> statements) { statements.Add( factory.ExpressionStatement( factory.AssignmentExpression( factory.Field( factory.This(), _fields.Single()), factory.Array( _boolType, ImmutableArray.Create<BoundExpression>(factory.Literal(true)) ) ) ) ); } private void GenerateBoolArrayConstructorBody(SyntheticBoundNodeFactory factory, ArrayBuilder<BoundStatement> statements, ImmutableArray<ParameterSymbol> parameters) { statements.Add( factory.ExpressionStatement( factory.AssignmentExpression( factory.Field( factory.This(), _fields.Single()), factory.Parameter(parameters.Single()) ) ) ); } } }
brettfo/roslyn
src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedEmbeddedNativeIntegerAttributeSymbol.cs
C#
apache-2.0
4,340
import React, { FC, useState } from 'react'; import styled from 'styled-components'; import { Modal } from 'antd'; import { Z_INDEX_GREATER_THAN_HEADER } from 'components/Header'; import { useHistory } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; import { useToggle } from 'react-use'; import { Steps, Row } from 'antd'; import StepOneBasic from './StepOneBasic'; import StepTwoAddBatch from './StepTwoAddBatch'; import { useResetCreateForm } from 'hooks/dataset'; import { forceToRefreshQuery } from 'shared/queryClient'; import { DATASET_LIST_QUERY_KEY } from '../DatasetList'; const ContainerModal = styled(Modal)` .ant-modal-body { padding-bottom: 14px; } .ant-modal-footer { display: none; } `; const StepRow = styled(Row)` width: 340px; margin: 10px auto 35px; `; const CreateDataset: FC = () => { const history = useHistory(); const { t } = useTranslation(); const [step, setStep] = useState(0); const [visible, toggleVisible] = useToggle(true); const resetForm = useResetCreateForm(); return ( <ContainerModal title={t('dataset.title_create')} visible={visible} style={{ top: '20%' }} width="fit-content" closable={false} maskClosable={false} maskStyle={{ backdropFilter: 'blur(4px)' }} keyboard={false} afterClose={afterClose} getContainer="body" zIndex={Z_INDEX_GREATER_THAN_HEADER} onCancel={() => toggleVisible(false)} > <StepRow justify="center"> <Steps current={step} size="small"> <Steps.Step title={t('dataset.step_basic')} /> <Steps.Step title={t('dataset.step_add_batch')} /> </Steps> </StepRow> {step === 0 && <StepOneBasic onSuccess={goAddBatch} onCancel={closeModal} />} {step === 1 && ( <StepTwoAddBatch onSuccess={onCreateNStartImportSuccess} onPrevious={backToStepBasic} onCancel={closeModal} /> )} </ContainerModal> ); function afterClose() { history.push('/datasets'); } function goAddBatch() { setStep(1); } function backToStepBasic() { setStep(0); } function closeModal() { resetForm(); toggleVisible(false); } function onCreateNStartImportSuccess() { forceToRefreshQuery([DATASET_LIST_QUERY_KEY]); closeModal(); } }; export default CreateDataset;
bytedance/fedlearner
web_console_v2/client/src/views/Datasets/CreateDataset/index.tsx
TypeScript
apache-2.0
2,390
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.hierarchy; import com.intellij.history.LocalHistory; import com.intellij.history.LocalHistoryAction; import com.intellij.ide.DeleteProvider; import com.intellij.ide.IdeBundle; import com.intellij.ide.util.DeleteHandler; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.ui.PopupHandler; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.util.HashMap; import java.util.Map; import java.util.function.Supplier; public abstract class TypeHierarchyBrowserBase extends HierarchyBrowserBaseEx { public static final String TYPE_HIERARCHY_TYPE = "Class {0}"; public static final String SUBTYPES_HIERARCHY_TYPE = "Subtypes of {0}"; public static final String SUPERTYPES_HIERARCHY_TYPE = "Supertypes of {0}"; private boolean myIsInterface; private final MyDeleteProvider myDeleteElementProvider = new MyDeleteProvider(); public TypeHierarchyBrowserBase(Project project, PsiElement element) { super(project, element); } protected abstract boolean isInterface(@NotNull PsiElement psiElement); protected void createTreeAndSetupCommonActions(@NotNull Map<? super @Nls String, ? super JTree> trees, @NotNull String groupId) { BaseOnThisTypeAction baseOnThisTypeAction = createBaseOnThisAction(); JTree tree1 = createTree(true); PopupHandler.installPopupMenu(tree1, groupId, ActionPlaces.TYPE_HIERARCHY_VIEW_POPUP); baseOnThisTypeAction .registerCustomShortcutSet(ActionManager.getInstance().getAction(IdeActions.ACTION_TYPE_HIERARCHY).getShortcutSet(), tree1); trees.put(getTypeHierarchyType(), tree1); JTree tree2 = createTree(true); PopupHandler.installPopupMenu(tree2, groupId, ActionPlaces.TYPE_HIERARCHY_VIEW_POPUP); baseOnThisTypeAction .registerCustomShortcutSet(ActionManager.getInstance().getAction(IdeActions.ACTION_TYPE_HIERARCHY).getShortcutSet(), tree2); trees.put(getSupertypesHierarchyType(), tree2); JTree tree3 = createTree(true); PopupHandler.installPopupMenu(tree3, groupId, ActionPlaces.TYPE_HIERARCHY_VIEW_POPUP); baseOnThisTypeAction .registerCustomShortcutSet(ActionManager.getInstance().getAction(IdeActions.ACTION_TYPE_HIERARCHY).getShortcutSet(), tree3); trees.put(getSubtypesHierarchyType(), tree3); } @NotNull protected BaseOnThisTypeAction createBaseOnThisAction() { return new BaseOnThisTypeAction(); } protected abstract boolean canBeDeleted(PsiElement psiElement); protected abstract String getQualifiedName(PsiElement psiElement); @Override protected @NotNull Map<String, Supplier<String>> getPresentableNameMap() { HashMap<String, Supplier<String>> map = new HashMap<>(); map.put(TYPE_HIERARCHY_TYPE, TypeHierarchyBrowserBase::getTypeHierarchyType); map.put(SUBTYPES_HIERARCHY_TYPE, TypeHierarchyBrowserBase::getSubtypesHierarchyType); map.put(SUPERTYPES_HIERARCHY_TYPE, TypeHierarchyBrowserBase::getSupertypesHierarchyType); return map; } public boolean isInterface() { return myIsInterface; } @Override protected void setHierarchyBase(@NotNull PsiElement element) { super.setHierarchyBase(element); myIsInterface = isInterface(element); } @Override protected void prependActions(@NotNull DefaultActionGroup actionGroup) { actionGroup.add(new ViewClassHierarchyAction()); actionGroup.add(new ViewSupertypesHierarchyAction()); actionGroup.add(new ViewSubtypesHierarchyAction()); actionGroup.add(new AlphaSortAction()); } @Override @NotNull protected String getActionPlace() { return ActionPlaces.TYPE_HIERARCHY_VIEW_TOOLBAR; } @Override public final Object getData(@NotNull String dataId) { if (PlatformDataKeys.DELETE_ELEMENT_PROVIDER.is(dataId)) { return myDeleteElementProvider; } return super.getData(dataId); } @Override @NotNull protected String getPrevOccurenceActionNameImpl() { return IdeBundle.message("hierarchy.type.prev.occurence.name"); } @Override @NotNull protected String getNextOccurenceActionNameImpl() { return IdeBundle.message("hierarchy.type.next.occurence.name"); } private final class MyDeleteProvider implements DeleteProvider { @Override public void deleteElement(@NotNull DataContext dataContext) { PsiElement aClass = getSelectedElement(); if (!canBeDeleted(aClass)) return; LocalHistoryAction a = LocalHistory.getInstance().startAction(IdeBundle.message("progress.deleting.class", getQualifiedName(aClass))); try { PsiElement[] elements = {aClass}; DeleteHandler.deletePsiElement(elements, myProject); } finally { a.finish(); } } @Override public boolean canDeleteElement(@NotNull DataContext dataContext) { PsiElement aClass = getSelectedElement(); if (!canBeDeleted(aClass)) { return false; } PsiElement[] elements = {aClass}; return DeleteHandler.shouldEnableDeleteAction(elements); } } protected static class BaseOnThisTypeAction extends BaseOnThisElementAction { public BaseOnThisTypeAction() { super(IdeBundle.messagePointer("action.base.on.this.class"), LanguageTypeHierarchy.INSTANCE); } @Override @Nls protected String correctViewType(@NotNull HierarchyBrowserBaseEx browser, @Nls String viewType) { if (((TypeHierarchyBrowserBase)browser).myIsInterface && getTypeHierarchyType().equals(viewType)) { return getSubtypesHierarchyType(); } return viewType; } } public static @Nls String getTypeHierarchyType() { //noinspection UnresolvedPropertyKey return IdeBundle.message("title.hierarchy.class"); } @Nls public static String getSubtypesHierarchyType() { //noinspection UnresolvedPropertyKey return IdeBundle.message("title.hierarchy.subtypes"); } public static @Nls String getSupertypesHierarchyType() { //noinspection UnresolvedPropertyKey return IdeBundle.message("title.hierarchy.supertypes"); } }
GunoH/intellij-community
platform/lang-impl/src/com/intellij/ide/hierarchy/TypeHierarchyBrowserBase.java
Java
apache-2.0
6,301
package exceptions; public class IDaoSaveException extends Exception{ private static final long serialVersionUID = 8041577551538125989L; public IDaoSaveException() { super(); } public IDaoSaveException(String msg) { super(msg); } public IDaoSaveException(String msg,Throwable cause) { super(msg,cause); } }
patrickfav/tuwien
master/SB_task2/src/exceptions/IDaoSaveException.java
Java
apache-2.0
325
// // // Copyright 2012 Kii Corporation // http://kii.com // // 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.kii.cloud.engine; public class TaskType { public static class FileTask { public static final int UPLOAD = 0; public static final int DOWNLOAD = 1; public static final int UPDATE = 2; public static final int UPDATE_METADATA = 3; public static final int REFRESH = 4; public static final int DELETE = 5; public static final int MOVE_TRASH = 6; public static final int RESTORE_TRASH = 7; public static final int LIST_CLOUD = 8; public static final int LIST_TRASH = 9; } public static class UserTask { public static final int LOGIN = 0; public static final int REGISTER = 1; public static final int CHANGE_PASSWORD = 2; public static final int UPDATE = 3; public static final int DELETE = 4; public static final int REFRESH = 5; } }
kii-dev-jenkins/KiiFileStorageSampleApp
src/com/kii/cloud/engine/TaskType.java
Java
apache-2.0
1,522
package com.xlg.forkids.chat.holder; import android.app.Activity; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.xlg.forkids.R; import com.xlg.forkids.baseitems.BaseHolder; import com.xlg.forkids.baseitems.BaseVAccount; import com.xlg.forkids.baseitems.BaseUser; /** Óû§Í·ÏñÇøÓò»ù±¾ÐÅÏ¢ */ public class BaseUserInfoHolder extends BaseHolder { /** Í·Ïñ */ public ImageView Image; /** ÐÕÃû/êÇ³Æ */ public TextView Name; /** Õ˺Š*/ public TextView Account; /** ÐÔ±ð */ public ImageView Sex; /** ¸öÐÔÇ©ÃûºÍ˵Ã÷ */ public TextView Memo; public ImageView EditMemo; private int imageSize; public BaseUserInfoHolder(Activity activity, View v) { super(activity, v); initView(); } private void initView() { Image = (ImageView) mRoot .findViewById(R.id.base_corner_masked_image_image); Name = (TextView) mRoot.findViewById(R.id.user_base_info_name); Account = (TextView) mRoot.findViewById(R.id.user_base_info_userid); Memo = (TextView) mRoot.findViewById(R.id.user_base_info_memo); EditMemo = (ImageView) mRoot .findViewById(R.id.user_base_info_memo_edit); EditMemo.setVisibility(View.GONE); Sex = (ImageView) mRoot.findViewById(R.id.user_base_info_sex); } public void setImageSize(int size) { imageSize = size; } /** ÏÔʾÓû§µÄÐÅÏ¢ */ public void showContent(BaseUser user) { Name.setText(user.getName()); Sex.setImageResource(user.getSex() == 0 ? R.drawable.personal_sex_f : R.drawable.personal_sex_m); Account.setText(mContext.getString(R.string.app_name) + ": " + user.getCode()); mFetcher.loadImage(user.getImage(), Image, imageSize, true); } /** ÏÔʾVÕ˺ŵÄÐÅÏ¢ */ public void showContent(BaseVAccount v) { mFetcher.loadImage(v.getImage(), Image, imageSize, true); Name.setText(v.getName()); Account.setText(mContext.getString(R.string.unions_title_text) + ": " + v.getVcode()); Memo.setText(v.getDescription()); Memo.setVisibility(View.GONE); Sex.setVisibility(View.GONE); } }
RyanTech/Forkids
ForKids/src/com/xlg/forkids/chat/holder/BaseUserInfoHolder.java
Java
apache-2.0
2,094