repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
lorenzopistolesi/sws
Breeder/BR_ReaScript.h
/****************************************************************************** / BR_ReaScript.h / / Copyright (c) 2014-2015 <NAME> / http://forum.cockos.com/member.php?u=27094 / http://github.com/reaper-oss/sws / / Permission is hereby granted, free of charge, to any person obtaining a copy / of this software and associated documentation files (the "Software"), to deal / in the Software without restriction, including without limitation the rights to / use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies / of the Software, and to permit persons to whom the Software is furnished to / do so, subject to the following conditions: / / The above copyright notice and this permission notice shall be included in all / copies or substantial portions of the Software. / / THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, / EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES / OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND / NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT / HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, / WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING / FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR / OTHER DEALINGS IN THE SOFTWARE. / ******************************************************************************/ #pragma once class BR_Envelope; /****************************************************************************** * ReaScript export * ******************************************************************************/ BR_Envelope* BR_EnvAlloc (TrackEnvelope* envelope, bool takeEnvelopesUseProjectTime); int BR_EnvCountPoints (BR_Envelope* envelope); bool BR_EnvDeletePoint (BR_Envelope* envelope, int id); int BR_EnvFind (BR_Envelope* envelope, double position, double delta); int BR_EnvFindNext (BR_Envelope* envelope, double position); int BR_EnvFindPrevious (BR_Envelope* envelope, double position); bool BR_EnvFree (BR_Envelope* envelope, bool commit); MediaItem_Take* BR_EnvGetParentTake (BR_Envelope* envelope); MediaTrack* BR_EnvGetParentTrack (BR_Envelope* envelope); bool BR_EnvGetPoint (BR_Envelope* envelope, int id, double* positionOut, double* valueOut, int* shapeOut, bool* selectedOut, double* bezierOut); void BR_EnvGetProperties (BR_Envelope* envelope, bool* activeOut, bool* visibleOut, bool* armedOut, bool* inLaneOut, int* laneHeightOut, int* defaultShapeOut, double* minValueOut, double* maxValueOut, double* centerValueOut, int* typeOut, bool* faderScalingOut); bool BR_EnvSetPoint (BR_Envelope* envelope, int id, double position, double value, int shape, bool selected, double bezier); void BR_EnvSetProperties (BR_Envelope* envelope, bool active, bool visible, bool armed, bool inLane, int laneHeight, int defaultShape, bool faderScaling); void BR_EnvSortPoints (BR_Envelope* envelope); double BR_EnvValueAtPos (BR_Envelope* envelope, double position); void BR_GetArrangeView (ReaProject* proj, double* startPositionOut, double* endPositionOut); double BR_GetClosestGridDivision (double position); void BR_GetCurrentTheme (char* themePathOut, int themePathOut_sz, char* themeNameOut, int themeNameOut_sz); MediaItem* BR_GetMediaItemByGUID (ReaProject* proj, const char* guidStringIn); void BR_GetMediaItemGUID (MediaItem* item, char* guidStringOut, int guidStringOut_sz); bool BR_GetMediaItemImageResource (MediaItem* item, char* imageOut, int imageOut_sz, int* imageFlagsOut); void BR_GetMediaItemTakeGUID (MediaItem_Take* take, char* guidStringOut, int guidStringOut_sz); bool BR_GetMediaSourceProperties (MediaItem_Take* take, bool* sectionOut, double* startOut, double* lengthOut, double* fadeOut, bool* reverseOut); MediaTrack* BR_GetMediaTrackByGUID (ReaProject* proj, const char* guidStringIn); int BR_GetMediaTrackFreezeCount (MediaTrack* track); void BR_GetMediaTrackGUID (MediaTrack* track, char* guidStringOut, int guidStringOut_sz); void BR_GetMediaTrackLayouts (MediaTrack* track, char* mcpLayoutNameOut, int mcpLayoutNameOut_sz, char* tcpLayoutNameOut, int tcpLayoutNameOut_sz); TrackEnvelope* BR_GetMediaTrackSendInfo_Envelope (MediaTrack* track, int category, int sendidx, int envelopeType); MediaTrack* BR_GetMediaTrackSendInfo_Track (MediaTrack* track, int category, int sendidx, int trackType); double BR_GetMidiSourceLenPPQ (MediaItem_Take* take); bool BR_GetMidiTakePoolGUID (MediaItem_Take* take, char* guidStringOut, int guidStringOut_sz); bool BR_GetMidiTakeTempoInfo (MediaItem_Take* take, bool* ignoreProjTempoOut, double* bpmOut, int* numOut, int* denOut); void BR_GetMouseCursorContext (char* windowOut, int windowOut_sz, char* segmentOut, int segmentOut_sz, char* detailsOut, int detailsOut_sz); TrackEnvelope* BR_GetMouseCursorContext_Envelope (bool* takeEnvelopeOut); MediaItem* BR_GetMouseCursorContext_Item (); void* BR_GetMouseCursorContext_MIDI (bool* inlineEditorOut, int* noteRowOut, int* ccLaneOut, int* ccLaneValOut, int* ccLaneIdOut); double BR_GetMouseCursorContext_Position (); int BR_GetMouseCursorContext_StretchMarker (); MediaItem_Take* BR_GetMouseCursorContext_Take (); MediaTrack* BR_GetMouseCursorContext_Track (); double BR_GetNextGridDivision (double position); double BR_GetPrevGridDivision (double position); double BR_GetSetTrackSendInfo (MediaTrack* track, int category, int sendidx, const char* parmname, bool setNewValue, double newValue); int BR_GetTakeFXCount (MediaItem_Take* take); bool BR_IsTakeMidi (MediaItem_Take* take, bool* inProjectMidiOut); bool BR_IsMidiOpenInInlineEditor(MediaItem_Take* take); MediaItem* BR_ItemAtMouseCursor (double* positionOut); bool BR_MIDI_CCLaneRemove (void* midiEditor, int laneId); bool BR_MIDI_CCLaneReplace (void* midiEditor, int laneId, int newCC); double BR_PositionAtMouseCursor (bool checkRuler); void BR_SetArrangeView (ReaProject* proj, double startPosition, double endPosition); bool BR_SetItemEdges (MediaItem* item, double startTime, double endTime); void BR_SetMediaItemImageResource (MediaItem* item, const char* imageIn, int imageFlags); bool BR_SetMediaSourceProperties (MediaItem_Take* take, bool section, double start, double length, double fade, bool reverse); bool BR_SetMediaTrackLayouts (MediaTrack* track, const char* mcpLayoutNameIn, const char* tcpLayoutNameIn); bool BR_SetMidiTakeTempoInfo (MediaItem_Take* take, bool ignoreProjTempo, double bpm, int num, int den); bool BR_SetTakeSourceFromFile (MediaItem_Take* take, const char* filenameIn, bool inProjectData); bool BR_SetTakeSourceFromFile2 (MediaItem_Take* take, const char* filenameIn, bool inProjectData, bool keepSourceProperties); MediaItem_Take* BR_TakeAtMouseCursor (double* positionOut); MediaTrack* BR_TrackAtMouseCursor (int* contextOut, double* positionOut); bool BR_TrackFX_GetFXModuleName (MediaTrack* track, int fx, char* nameOut, int nameOutSz); int BR_Win32_CB_FindString (void* comboBoxHwnd, int startId, const char* string); int BR_Win32_CB_FindStringExact (void* comboBoxHwnd, int startId, const char* string); void BR_Win32_ClientToScreen (void* hwnd, int xIn, int yIn, int* xOut, int* yOut); void* BR_Win32_FindWindowEx (const char* hwndParent, const char* hwndChildAfter, const char* className, const char* windowName, bool searchClass, bool searchName); int BR_Win32_GET_X_LPARAM (int lParam); int BR_Win32_GET_Y_LPARAM (int lParam); int BR_Win32_GetConstant (const char* constantName); bool BR_Win32_GetCursorPos (int* xOut, int* yOut); void* BR_Win32_GetFocus (); void* BR_Win32_GetForegroundWindow (); void* BR_Win32_GetMainHwnd(); void* BR_Win32_GetMixerHwnd (bool* isDockedOut); void BR_Win32_GetMonitorRectFromRect (bool workingAreaOnly, int leftIn, int topIn, int rightIn, int bottomIn, int* leftOut, int* topOut, int* rightOut, int* bottomOut); void* BR_Win32_GetParent (void* hwnd); int BR_Win32_GetPrivateProfileString (const char* sectionName, const char* keyName, const char* defaultString, const char* filePath, char* stringOut, int stringOut_sz); void* BR_Win32_GetWindow (void* hwnd, int cmd); int BR_Win32_GetWindowLong (void* hwnd, int index); bool BR_Win32_GetWindowRect(void* hwnd, int* leftOut, int* topOut, int* rightOut, int* bottomOut); int BR_Win32_GetWindowText (void* hwnd, char* textOut, int textOut_sz); int BR_Win32_HIBYTE (int value); int BR_Win32_HIWORD (int value); void BR_Win32_HwndToString (void* hwnd, char* stringOut, int stringOut_sz); bool BR_Win32_IsWindow (void* hwnd); bool BR_Win32_IsWindowVisible (void* hwnd); int BR_Win32_LOBYTE (int value); int BR_Win32_LOWORD (int value); int BR_Win32_MAKELONG (int low, int high); int BR_Win32_MAKELPARAM (int low, int high); int BR_Win32_MAKELRESULT (int low, int high); int BR_Win32_MAKEWORD (int low, int high); int BR_Win32_MAKEWPARAM (int low, int high); void* BR_Win32_MIDIEditor_GetActive (); void BR_Win32_ScreenToClient (void* hwnd, int xIn, int yIn, int* xOut, int* yOut); int BR_Win32_SendMessage (void* hwnd, int msg, int lParam, int wParam); void* BR_Win32_SetFocus (void* hwnd); int BR_Win32_SetForegroundWindow (void* hwnd); int BR_Win32_SetWindowLong (void* hwnd, int index, int newLong); bool BR_Win32_SetWindowPos (void* hwnd, const char* hwndInsertAfter, int x, int y, int width, int height, int flags); int BR_Win32_ShellExecute (const char* operation, const char* file, const char* parameters, const char* directoy, int showFlags); bool BR_Win32_ShowWindow (void* hwnd, int cmdShow); void* BR_Win32_StringToHwnd (const char* string); void* BR_Win32_WindowFromPoint (int x, int y); bool BR_Win32_WritePrivateProfileString (const char* sectionName, const char* keyName, const char* value, const char* filePath); /****************************************************************************** * Big description! * ******************************************************************************/ #define BR_MOUSE_REASCRIPT_DESC "[BR] \ Get mouse cursor context. Each parameter returns information in a form of string as specified in the table below.\n\n\ To get more info on stuff that was found under mouse cursor see BR_GetMouseCursorContext_Envelope, BR_GetMouseCursorContext_Item, \ BR_GetMouseCursorContext_MIDI, BR_GetMouseCursorContext_Position, BR_GetMouseCursorContext_Take, BR_GetMouseCursorContext_Track \n\n\ <table border=\"2\">\ <tr><th style=\"width:100px\">Window</th> <th style=\"width:100px\">Segment</th> <th style=\"width:300px\">Details</th> </tr>\ <tr><th rowspan=\"1\" align = \"center\"> unknown </th> <td> \"\" </td> <td> \"\" </td> </tr>\ <tr><th rowspan=\"4\" align = \"center\"> ruler </th> <td> region_lane </td> <td> \"\" </td> </tr>\ <tr> <td> marker_lane </td> <td> \"\" </td> </tr>\ <tr> <td> tempo_lane </td> <td> \"\" </td> </tr>\ <tr> <td> timeline </td> <td> \"\" </td> </tr>\ <tr><th rowspan=\"1\" align = \"center\"> transport </th> <td> \"\" </td> <td> \"\" </td> </tr>\ <tr><th rowspan=\"3\" align = \"center\"> tcp </th> <td> track </td> <td> \"\" </td> </tr>\ <tr> <td> envelope </td> <td> \"\" </td> </tr>\ <tr> <td> empty </td> <td> \"\" </td> </tr>\ <tr><th rowspan=\"2\" align = \"center\"> mcp </th> <td> track </td> <td> \"\" </td> </tr>\ <tr> <td> empty </td> <td> \"\" </td> </tr>\ <tr><th rowspan=\"3\" align = \"center\"> arrange </th> <td> track </td> <td> empty,<br>item, item_stretch_marker,<br>env_point, env_segment </td> </tr>\ <tr> <td> envelope </td> <td> empty, env_point, env_segment </td> </tr>\ <tr> <td> empty </td> <td> \"\" </td> </tr>\ <tr><th rowspan=\"5\" align = \"center\"> midi_editor </th> <td> unknown </td> <td> \"\" </td> </tr>\ <tr> <td> ruler </td> <td> \"\" </td> </tr>\ <tr> <td> piano </td> <td> \"\" </td> </tr>\ <tr> <td> notes </td> <td> \"\" </td> </tr>\ <tr> <td> cc_lane </td> <td> cc_selector, cc_lane </td> </tr>\ </table>"
aristanetworks/DirectFlowAssist
persist_chkp/config.py
''' settings for DirectFlow Assist for Check Point Firewalls ''' # # pylint: disable = line-too-long from config_common import * OPERATING_MODE = SHUNT_MODE # SHUNT_MODE, INLINE_MODE, MIRROR_MODE SYSLOG_TRANSPORT = UDP # options: UDP, TCP (SSL/TLS support coming soon from Check Point) ACCEPT_SYSLOG_MSGS_FROM_IP = [] # only process msgs from these source IP addresses # Define switch and firewall interfaces based on the designations show in diagram below: # Zone_A Zone_B # | | # A B <-- switch interfaces to network # [=========== ARISTA SWITCH ==========::] # AF BF TO_TAP HA_AF HA_BF <-- switch interfaces to firewall # | | | | | # AF BF TAP HA_AF HA_BF <-- firewall interfaces to switch # [PAN FIREWALL 1]--HA--[PAN FIREWALL 2] # # Zone_A interfaces SWITCH_INTERFACE_A = '' SWITCH_INTERFACE_AF = '' SWITCH_INTERFACE_HA_AF = '' # optional: High-Availability to second firewall FIREWALL_INTERFACE_AF = '' # use same firewall intf name on AF and HA_AF, don't include sub-intf # Zone_B interfaces SWITCH_INTERFACE_B = '' SWITCH_INTERFACE_BF = '' SWITCH_INTERFACE_HA_BF = '' # optional: High-Availability to second firewall FIREWALL_INTERFACE_BF = '' # use same firewall intf name on AF and HA_AF, don't include sub-intf SWITCH_INTERFACES_TO_FW_TAP = [] # switch interface(s) attached to firewall tap interface(s) SWITCH_INTERFACES_TO_BE_MIRRORED = [] # only rx/ingress traffic is mirrored, MIRROR_MODE only # Define Syslog Message Triggers. A trigger is defined in a python dictionary, where # each key is a case sensitive syslog message field name and the associated value is a # case insensitive string or list of strings. If the string or any string in the list # is "contained within" the named syslog message field then that key is satisfied. The # value string(s) can be a regular expression if more complex matches are required. # The trigger fires if all keys are satisfied. DROP_DEFAULT = {'product': 'FireWall', 'Action': ['drop', 'deny']} BYPASS_DEFAULT = {'product': 'FireWall', 'Action': 'accept'} DFA_IGNORE_FILTER = {} # filter here if can't config firewall not to send a particular msg # Flow match criteria used by DirectFlow in switch TCAM. The value for each field # is extracted from the triggering syslog message. Define sensible combinations of # these 5-tuple fields: SRC_IP, SRC_PORT, DST_IP, DST_PORT, PROTOCOL. FIVE_TUPLE = [SRC_IP, SRC_PORT, DST_IP, DST_PORT, PROTOCOL] SRC_IP_DST_IP_PORT = [SRC_IP, DST_IP, DST_PORT, PROTOCOL] SRC_IP_DST_IP = [SRC_IP, DST_IP] SRC_IP_ONLY = [SRC_IP] # Combine syslog message triggers, assist actions and DirectFlow flow match criteria # into a specification for DFA controller. When a firewall syslog message is # received triggers are processed in the order defined here. Define defaults last. # Available actions: DROP_FLOW, BYPASS_FIREWALL, REDIRECT_TO_FIREWALL, DFA_IGNORE DFA_CONTROLLER_SPEC = [ # {'action': DFA_IGNORE, 'trigger': DFA_IGNORE_FILTER}, # process ignores first {'action': DROP_FLOW, 'flow_match': SRC_IP_DST_IP_PORT, 'trigger': DROP_DEFAULT}, {'action': BYPASS_FIREWALL, 'flow_match': FIVE_TUPLE, 'trigger': BYPASS_DEFAULT}] # set/mark Ethernet CoS and/or IP ToS fields in bypassed flows; higher value = higher priority # COS range <0-7>; TOS range <0-255> uses the 6 most significant bits of this byte # key= application name string from FW syslog, value is a dict with key='COS' and/or 'TOS' value=integer COS_TOS_MARKING = { 'echo_request_DFA': {'COS': 3, 'TOS': 8}, 'ssh_DFA': {'TOS': 16}} # Check Point package specific settings APP_NAME = 'DirectFlow Assist for Check Point Firewalls' SSL_CA_CERTS_FILE = DFA_PERSIST_ROOT + 'rootCA2.crt' SSL_DFA_CERT_FILE = DFA_PERSIST_ROOT + 'dfa.crt' SSL_DFA_KEY_FILE = DFA_PERSIST_ROOT + 'dfa.key' FW_INTF_IN_SYSLOG_MSG = False # as of R77_30 firewall ingress/egress intf not in syslog msg BYPASS_FLOW_IDLE_TIMEOUT = 2 # in minutes, also used for flow direction sensing idle timeout ASSIST_WHEN_SERVICE_ID_SUFFIX = '_DFA' # suffix on service_id field to indicate DFA should assist def get_msg_class(): ''' runtime import ''' from directflow_assist import CheckPointSyslogMsg return CheckPointSyslogMsg.CheckPointSyslogMsg
TheYargonaut/lucre
EditGroupWindow.py
<reponame>TheYargonaut/lucre import tkinter as tk from tkinter.colorchooser import askcolor from tkinter import ttk from Scrollable import Scrollable from ViewLedgerWidget import ViewLedgerWidget from List import ListView from Group import Group # window for editing a group prevLens = [ 10, 25, 100 ] class EditGroupWindow( tk.Toplevel ): def __init__( self, master, group, ledger, psize, *args, **kwargs ): tk.Toplevel.__init__( self, master, *args, **kwargs ) self.title( "edit group" ) self.groupBack = group self.group = Group( **dict( group ) ) self.ledger = ledger self.psize = psize self.highlight = self.group.color # "white" self.ignored = "#E00E00E00" # gray self.view = None self.build() self.matchListCb( self.view ) def matchListCb( self, view ): 'set the highlights when group lists change' mask = self.group.filter( self.ledger.df.head( len( view ) ) ) for r, m in enumerate( mask ): view.highlightRow( r, self.highlight if m else self.ignored ) def finalize( self ): self.groupBack.whitelist = [ r for r in self.group.whitelist if r ] self.groupBack.blacklist = [ r for r in self.group.blacklist if r ] self.groupBack.negate = self.group.negate self.groupBack.title = self.group.title self.groupBack.color = self.group.color self.ledger.updateCb( self.ledger.df ) self.destroy() def whiteListCb( self, idx, txt ): self.group.whitelist[ idx ] = txt self.matchListCb( self.view ) def blackListCb( self, idx, txt ): self.group.blacklist[ idx ] = txt self.matchListCb( self.view ) def nameCb( self, *args ): self.group.title = self.nameVar.get() def expenseCb( self, value ): self.group.negate = value == 'expense' def colorCb( self ): self.group.color = askcolor( self.group.color, parent=self )[ 1 ] self.highlight = self.group.color self.color.config( fg=self.group.color ) self.matchListCb( self.view ) def build( self ): self.grid_rowconfigure( 0, weight=1 ) self.grid_columnconfigure( 0, weight=1 ) mainFrame = ttk.Frame( self ) mainFrame.grid( row=0, column=0, sticky=tk.NSEW ) mainFrame.grid_rowconfigure( 1, weight=1 ) mainFrame.grid_columnconfigure( 0, weight=1 ) listFrame = ttk.Frame( self ) listFrame.grid( row=0, column=1, sticky=tk.NSEW ) listFrame.grid_rowconfigure( 0, weight=1 ) listFrame.grid_rowconfigure( 1, weight=1 ) listFrame.grid_columnconfigure( 0, weight=1 ) whiteFrame = ttk.Frame( listFrame ) whiteFrame.grid( row=0, column=0, sticky=tk.NSEW ) whiteLabel = tk.Label( whiteFrame, text='whitelist' ) whiteLabel.pack( side=tk.TOP, fill=tk.X ) whiteScroll = Scrollable( whiteFrame, vertical=True ) whiteScroll.pack( side=tk.TOP, fill=tk.BOTH ) whiteList = ListView( whiteScroll, self.group.whitelist, '+', self.whiteListCb ) whiteList.pack() blackFrame = ttk.Frame( listFrame ) blackFrame.grid( row=1, column=0, sticky=tk.NSEW ) blackLabel = tk.Label( blackFrame, text='blacklist' ) blackLabel.pack( side=tk.TOP, fill=tk.X ) blackScroll = Scrollable( blackFrame, vertical=True ) blackScroll.pack( side=tk.TOP, fill=tk.BOTH ) blackList = ListView( blackScroll, self.group.blacklist, '+', self.blackListCb ) blackList.pack() button = ttk.Frame( self ) button.grid( row=1, column=0, columnspan=2, sticky=tk.W + tk.E ) cancel = ttk.Button( button, text="Cancel", command=self.destroy ) cancel.pack( side=tk.RIGHT ) confirm = ttk.Button( button, text="Confirm", command=self.finalize ) confirm.pack( side=tk.RIGHT ) nameFrame = ttk.Frame( mainFrame ) nameFrame.grid( row=0, column=0, sticky=tk.NSEW ) self.color = tk.Button( nameFrame, text="\u2B1B", command=self.colorCb, width=3 ) self.color.config( fg=self.group.color ) self.color.pack( side=tk.LEFT, fill=tk.NONE, expand=False ) self.nameVar = tk.StringVar( nameFrame ) self.nameVar.set( self.group.title ) self.nameVar.trace( 'w', self.nameCb ) name = ttk.Entry( nameFrame, textvariable=self.nameVar, exportselection=0 ) name.pack( side=tk.LEFT, fill=tk.X, expand=True ) style = ttk.OptionMenu( nameFrame, tk.StringVar( nameFrame ), ( "expense" if self.group.negate else "income" ), "income", "expense", command=self.expenseCb ) style.pack( side=tk.RIGHT, fill=tk.NONE, expand=False ) self.view = ViewLedgerWidget( mainFrame, self.ledger.df, lenCb=self.matchListCb ) self.view.grid( row=1, column=0, sticky=tk.NE + tk.S ) def editGroupCb( master, group, ledger, psize ): def cb( master=master, group=group, ledger=ledger, psize=psize ): window = EditGroupWindow( master, group, ledger, psize ) master.wait_window( window ) return cb
jonestimd/finances
src/main/java/io/github/jonestimd/finance/swing/transaction/TransactionGroupColumnAdapter.java
<filename>src/main/java/io/github/jonestimd/finance/swing/transaction/TransactionGroupColumnAdapter.java<gh_stars>1-10 // The MIT License (MIT) // // Copyright (c) 2016 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. package io.github.jonestimd.finance.swing.transaction; import java.util.List; import java.util.function.BiConsumer; import java.util.function.Function; import io.github.jonestimd.finance.domain.transaction.TransactionGroup; import io.github.jonestimd.finance.domain.transaction.TransactionGroupSummary; import io.github.jonestimd.finance.domain.transaction.TransactionSummary; import io.github.jonestimd.finance.swing.BundleType; import io.github.jonestimd.swing.table.model.FunctionColumnAdapter; import io.github.jonestimd.swing.table.model.ValidatedColumnAdapter; public class TransactionGroupColumnAdapter<V> extends FunctionColumnAdapter<TransactionGroupSummary, V> { private TransactionGroupColumnAdapter(String resourcePrefix, Class<V> valueType, Function<TransactionGroup, V> getter, BiConsumer<TransactionGroup, V> setter) { super(BundleType.LABELS.get(), "table.transactionGroup.", resourcePrefix, valueType, TransactionSummary.compose(getter), TransactionSummary.compose(setter)); } private static abstract class ValidatedGroupColumnAdapter<V> extends TransactionGroupColumnAdapter<V> implements ValidatedColumnAdapter<TransactionGroupSummary, V> { private ValidatedGroupColumnAdapter(String resourcePrefix, Class<V> valueType, Function<TransactionGroup, V> getter, BiConsumer<TransactionGroup, V> setter) { super(resourcePrefix, valueType, getter, setter); } } public static final ValidatedColumnAdapter<TransactionGroupSummary, String> NAME_ADAPTER = new ValidatedGroupColumnAdapter<String>(TransactionGroup.NAME, String.class, TransactionGroup::getName, TransactionGroup::setName) { private final TransactionGroupNameValidator<TransactionGroupSummary> validator = new TransactionGroupNameValidator<>(TransactionGroupSummary::getName); public String validate(int selectedIndex, String name, List<? extends TransactionGroupSummary> existingValues) { return validator.validate(selectedIndex, name, existingValues); } }; public static final TransactionGroupColumnAdapter<String> DESCRIPTION_ADAPTER = new TransactionGroupColumnAdapter<>(TransactionGroup.DESCRIPTION, String.class, TransactionGroup::getDescription, TransactionGroup::setDescription); }
vicanso/tiny-site
web/src/components/login_register/index.js
<reponame>vicanso/tiny-site import React from "react"; import { Form, Input, Icon, Card, Button, message, Spin, Row, Col } from "antd"; import { sha256 } from "../../helpers/crypto"; import { generatePassword } from "../../helpers/util"; import "./login_register.sass"; import * as userService from "../../services/user"; import * as commonService from "../../services/common"; class LoginRegister extends React.Component { loginMode = "login"; registerMode = "register"; state = { submitting: false, account: "", password: "", token: "", captcha: "", mode: "", captchaID: "", captchaData: "" }; componentDidMount() { this.getCaptcha(); } async getCaptcha() { this.setState({ captchaData: "" }); try { const data = await commonService.getCaptcha(); this.setState({ captchaID: data.id, captchaData: `data:image/${data.type};base64,${data.data}` }); } catch (err) { message.error(err.message); } } async handleSubmit(e) { const { history } = this.props; const { setUserInfo } = this.props; e.preventDefault(); const { account, password, mode, token, captchaID, captcha } = this.state; if (!account || !password) { message.error("用户名与密码不能为空"); return; } if (!captcha || !captchaID) { message.error("图形验证码不能为空"); return; } const postData = { captcha: `${captchaID}:${captcha}`, account }; let fn = userService.login; if (mode === this.loginMode) { if (!token) { message.error("Token为不能空"); return; } postData.password = <PASSWORD>(<PASSWORD>(password) + token); } else { fn = userService.register; postData.password = <PASSWORD>(password); } this.setState({ submitting: true }); try { const data = await fn(postData); if (setUserInfo) { setUserInfo({ account: data.account || "", roles: data.roles }); } if (history) { history.goBack(); } } catch (err) { message.error(err.message); // 因为图形验证码只可以使用一次,因此失败自动刷新 this.getCaptcha(); } finally { this.setState({ submitting: false }); } } render() { const { mode, submitting, captchaData } = this.state; const title = mode === this.loginMode ? "登录" : "注册"; return ( <div className="LoginRegister"> <Spin spinning={submitting}> <Card title={title}> <Form onSubmit={this.handleSubmit.bind(this)}> <Form.Item> <Input autoFocus prefix={ <Icon type="user" style={{ color: "rgba(0,0,0,.25)" }} /> } onChange={e => { this.setState({ account: e.target.value.trim() }); }} placeholder="用户名" /> </Form.Item> <Form.Item> <Input prefix={ <Icon type="lock" style={{ color: "rgba(0,0,0,.25)" }} /> } type="password" onChange={e => { this.setState({ password: e.target.value.trim() }); }} autoComplete="off" placeholder="密码" /> </Form.Item> <Form.Item> <Row gutter={8}> <Col span={20}> <Input placeholder="请输入图形验证码" onChange={e => { const v = e.target.value.trim(); if (v.length > 4) { message.warn("请输入4位长度验证码"); } this.setState({ captcha: v }); }} /> </Col> <Col span={4}> <a className="captcha" href="/" onClick={e => { e.preventDefault(); this.getCaptcha(); }} > {captchaData && ( <img height="38" src={captchaData} alt="captcha" /> )} </a> </Col> </Row> </Form.Item> <Button type="primary" htmlType="submit" className="submit"> {title} </Button> </Form> </Card> </Spin> </div> ); } } export default LoginRegister;
lyze237/FireAndIce
core/src/main/java/dev/lyze/parallelworlds/screens/game/entities/impl/GroundTile.java
package dev.lyze.parallelworlds.screens.game.entities.impl; import dev.lyze.parallelworlds.screens.game.Level; import dev.lyze.parallelworlds.screens.game.entities.TileEntity; public class GroundTile extends TileEntity { public GroundTile(float x, float y, float width, float height, Level level) { super(x, y, width, height, level); setHitbox(true); } }
rusucosmin/Cplusplus
_codeforces/460C/460c.cpp
<reponame>rusucosmin/Cplusplus #include <iostream> #include <string.h> #include <algorithm> using namespace std; const int maxn = 100005; long long a[maxn], dp[maxn]; long long ans; int n, w; long long m; inline bool check(long long minvalue) { memset(dp, 0, sizeof(dp)); /// dp[i] = number of segments starting at i'th index long long actint = 0; long long totalsegments = 0; for(int i = 1 ; i <= n ; ++ i) { if(i > w) actint -= dp[i - w]; if(a[i] + actint < minvalue) { dp[i] = (minvalue - a[i] - actint); actint += dp[i]; totalsegments += dp[i]; } if(totalsegments > m) return false; } return totalsegments <= m; } int main() { #ifndef ONLINE_JUDGE freopen("460c.in", "r", stdin); freopen("460c.out", "w", stdout); #endif cin >> n >> m >> w; for(int i = 1 ; i <= n ; ++ i) cin >> a[i]; ans = *min_element(a + 1, a + n + 1); long long st = 1, dr = 1000000000000000LL; while(st <= dr) { long long mid = (st + (dr - st) / 2); if(check(mid)) { st = mid + 1; ans = mid; } else dr = mid - 1; } cout << ans << '\n'; }
dweggyness/gazelle-server
src/components/admin/lib/__tests__/form-field-updaters.test.js
<filename>src/components/admin/lib/__tests__/form-field-updaters.test.js<gh_stars>10-100 /* eslint-disable */ /* Remove the eslint-disable when you remove the .skip and refactor this to fit with jest 20 */ import { updateFieldValue, trimField } from '../form-field-updaters'; describe.skip('updateFieldValue', () => { beforeEach(() => { // Simple implementation of our setState const safeSetState = function(updater) { if (typeof updater !== 'function') { const newState = Object.assign({}, updater); updater = () => newState; } this.state = Object.assign({}, this.state, updater(this.state)); }; this.setupTestEnvironment = initialState => { if (!initialState) { throw new Error('setupTestEnvironment needs an initialState'); } // Setup the event object for use but expect test to fill in value itself this.e = { target: {}, }; // Create mock component const _this = {}; _this.safeSetState = safeSetState.bind(_this); _this.state = initialState; return _this; }; }); // Test the safeSetState we just wrote above describe('.test.safeSetState', () => { it('handles function argument', () => { const _this = this.setupTestEnvironment({ a: 1 }); _this.safeSetState(prevState => ({ a: prevState.a + 1 })); expect(_this.state).toEqual({ a: 2 }); _this.safeSetState(prevState => ({ a: 5 })); expect(_this.state).toEqual({ a: 5 }); _this.safeSetState(prevState => ({ a: 17, b: 3 })); expect(_this.state).toEqual({ a: 17, b: 3 }); _this.safeSetState(prevState => ({ b: 10 })); expect(_this.state).toEqual({ a: 17, b: 10 }); }); it('handles object argument', () => { const _this = this.setupTestEnvironment({ a: 1 }); _this.safeSetState({ a: 5 }); expect(_this.state).toEqual({ a: 5 }); _this.safeSetState({ a: 17, b: 3 }); expect(_this.state).toEqual({ a: 17, b: 3 }); _this.safeSetState({ b: 10 }); expect(_this.state).toEqual({ a: 17, b: 10 }); }); }); it('updates state with simple keys', () => { const _this = this.setupTestEnvironment({ a: 'initial' }); const e = this.e; const key = 'a'; const boundUpdate = updateFieldValue.bind(_this, key, undefined); e.target.value = 'test'; boundUpdate(e); expect(_this.state).toEqual({ a: 'test' }); }); it('updates state with complex keys', () => { const initialState = { form: { subset: { keyA: 'initial', }, }, }; const targetState = { form: { subset: { keyA: 'test', }, }, }; const _this = this.setupTestEnvironment(initialState); const e = this.e; const key = 'form.subset.keyA'; const boundUpdate = updateFieldValue.bind(_this, key, undefined); e.target.value = 'test'; boundUpdate(e); expect(_this.state).toEqual(targetState); }); it("doesn't delete other keys in nested objects", () => { const initialState = { form: { subset: { keyA: 'initial', keyB: 'dummyB', keyC: 'dummyC', }, }, }; const targetState = { form: { subset: { keyA: 'test', keyB: 'dummyB', keyC: 'dummyC', }, }, }; const _this = this.setupTestEnvironment(initialState); const e = this.e; const key = 'form.subset.keyA'; const boundUpdate = updateFieldValue.bind(_this, key, undefined); e.target.value = 'test'; boundUpdate(e); expect(_this.state).toEqual(targetState); }); it('handles sequential updates', () => { const _this = this.setupTestEnvironment({ a: 'initial' }); const e = this.e; const key = 'a'; const boundUpdate = updateFieldValue.bind(_this, key, undefined); e.target.value = 'first'; boundUpdate(e); expect(_this.state).toEqual({ a: 'first' }); e.target.value = 'second'; boundUpdate(e); expect(_this.state).toEqual({ a: 'second' }); }); it('throws error correctly relating to keypath', () => { const _this = this.setupTestEnvironment({ a: 'initial' }); const e = this.e; e.target.value = 'test'; const key1 = 'b'; const boundUpdate1 = updateFieldValue.bind(_this, key1, undefined); expect(boundUpdate1.bind(null, e)).not.toThrow(); _this.state = { a: 'initial' }; const key2 = 'a.b'; const boundUpdate2 = updateFieldValue.bind(_this, key2, undefined); expect(boundUpdate2.bind(null, e)).toThrow(); _this.state = { a: 'initial' }; const key3 = 'b.c'; const boundUpdate3 = updateFieldValue.bind(_this, key3, undefined); expect(boundUpdate3.bind(null, e)).toThrow(); }); it('throws error on invalid option', () => { const _this = this.setupTestEnvironment({ a: 'initial' }); const e = this.e; const key = 'a'; const boundUpdate = updateFieldValue.bind(_this, key); const options = { invalidOption: 'test', }; expect(boundUpdate.bind(null, options, e)).toThrow(); // Check when there is also a valid one options.isMaterialSelect = true; expect(boundUpdate.bind(null, options, e)).toThrow(); }); it('handles Material Select element correctly', () => { const _this = this.setupTestEnvironment({ a: 'initial' }); const e = this.e; const key = 'a'; const options = { isMaterialSelect: true, }; const boundUpdate = updateFieldValue.bind(_this, key, options); e.target.value = 'wrong'; const value = 'right'; boundUpdate(e, null, value); expect(_this.state).toEqual({ a: 'right' }); }); it('handles trim option', () => { const _this = this.setupTestEnvironment({ a: 'initial' }); const e = this.e; const key = 'a'; const options = { trim: 5, }; const boundUpdate = updateFieldValue.bind(_this, key, options); e.target.value = 'hello this is a test'; boundUpdate(e); expect(_this.state).toEqual({ a: 'hello' }); }); }); describe('trimField', () => { // 20 characters long value const value = 'hello this is a test'; it('trims field', () => { expect(trimField(5, value)).toBe('hello'); expect(trimField(25, value)).toBe(value); }); it('handles empty/null values', () => { expect(trimField(5, '')).toBe(''); expect(trimField(5, null)).toBe(''); expect(trimField(5, undefined)).toBe(''); }); });
mjwestcott/fennel
tests/unit/client/test_actions.py
<filename>tests/unit/client/test_actions.py<gh_stars>10-100 import pytest from fennel.client.actions import purge_dead, read_dead, replay_dead from fennel.client.state import get_job, get_state from fennel.exceptions import JobNotFound from fennel.status import DEAD, SENT from tests.helpers import random_job @pytest.fixture def dead_job(app, failing_job): failing_job.tries = 1 failing_job.max_retries = 0 failing_job.status = DEAD app.client.hset(app.keys.status(failing_job), mapping=failing_job.serialise()) app.client.xadd(app.keys.dead, {"uuid": failing_job.uuid}) state = get_state(app) assert len(state.queue.messages) == 0 assert len(state.dead.messages) == 1 job = get_job(app, failing_job.uuid) assert job.tries == 1 assert job.max_retries == 0 assert job.status == DEAD def test_read(app, broker, failing_job, dead_job): results = read_dead(app) assert len(results) == 1 state = get_state(app) assert len(state.queue.messages) == 0 assert len(state.dead.messages) == 1 job = get_job(app, failing_job.uuid) assert job.tries == 1 assert job.max_retries == 0 assert job.status == DEAD def test_replay(app, broker, failing_job, dead_job): results = replay_dead(app) assert len(results) == 1 state = get_state(app) assert len(state.queue.messages) == 1 assert len(state.dead.messages) == 0 job = get_job(app, failing_job.uuid) assert job.tries == 1 assert job.max_retries == 0 assert job.status == SENT def test_purge(app, broker, failing_job, dead_job): results = purge_dead(app) assert len(results) == 1 state = get_state(app) assert len(state.queue.messages) == 0 assert len(state.dead.messages) == 0 with pytest.raises(JobNotFound): get_job(app, failing_job.uuid) def test_replay_filter(app, broker, failing_job): @app.task def mytask(): return "1" for _ in range(10): job = random_job(tries=1, max_retries=0, status=DEAD, task=mytask.name) app.client.hset(app.keys.status(job), mapping=job.serialise()) app.client.xadd(app.keys.dead, {"uuid": job.uuid}) @app.task def anothertask(): return "2" for _ in range(5): job = random_job(tries=4, max_retries=3, status=DEAD, task=anothertask.name) app.client.hset(app.keys.status(job), mapping=job.serialise()) app.client.xadd(app.keys.dead, {"uuid": job.uuid}) state = get_state(app) assert len(state.queue.messages) == 0 assert len(state.dead.messages) == 15 results = replay_dead(app, filter=lambda job: job.task.endswith("mytask")) assert len(results) == 10 state = get_state(app) assert len(state.queue.messages) == 10 assert len(state.dead.messages) == 5
psamatt/OrderFulfilmentCQRSDemo
src/main/java/co/uk/acme/query/availableslots/AvailableSlotsForDayProjector.java
<filename>src/main/java/co/uk/acme/query/availableslots/AvailableSlotsForDayProjector.java package co.uk.acme.query.availableslots; import co.uk.acme.deliveryday.*; import org.axonframework.eventhandling.annotation.EventHandler; import org.springframework.beans.factory.annotation.Autowired; /** * @author psamatt */ final public class AvailableSlotsForDayProjector { private AvailableSlotsForDayRepository repository; @Autowired public void setAvailableSlotsRepository(AvailableSlotsForDayRepository repository) { this.repository = repository; } @EventHandler void on(DeliveryDayScheduled event) { AvailableSlotsForDay daySlots = new AvailableSlotsForDay(event.getId().toString(), event.getDate().toString(), event.getCapacity().getAmount()); repository.save(daySlots); } @EventHandler void on(DeliverySlotReserved event) { AvailableSlotsForDay daySlots = repository.findOne(event.getDeliveryDayId().toString()); daySlots.decrementCapacity(); repository.save(daySlots); } @EventHandler void on(DeliverySlotRetracted event) { AvailableSlotsForDay daySlots = repository.findOne(event.getDeliveryDayId().toString()); daySlots.incrementCapacity(); repository.save(daySlots); } }
BlakePetersen/.io
components/nav/PageProgress.js
import { useRef, useEffect } from 'react'; import ProgressBar from '../../lib/progress-bar' import styled from 'styled-components'; const _ProgressBar = styled.div` height: 6px; width: 100%; display: flex; `; const PageProgress = () => { const _ProgressBarRef = useRef(null); useEffect(() => { ProgressBar(_ProgressBarRef.current); }); return <_ProgressBar ref={_ProgressBarRef} /> }; export default PageProgress
RockChinQ/RFTX2
src/com/rftx/core/FileTaskInfo.java
<reponame>RockChinQ/RFTX2<gh_stars>1-10 package com.rftx.core; public class FileTaskInfo { public String taskToken; public String localPath; public long size; public String remoteOSCode; public String remotePath; public long progress; public static final int SENDER = 0, RECEIVER = 1; public int localHostIdentity=0; public String remoteAddr=""; public int remotePort=0; public long launchTime=0; }
erard22/camel
components/camel-jms/src/test/java/org/apache/camel/component/jms/activemq/ActiveMQConsumeWildcardQueuesTest.java
/* * 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.camel.component.jms.activemq; import javax.jms.ConnectionFactory; import org.apache.camel.CamelContext; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.jms.CamelJmsTestHelper; import org.apache.camel.test.junit5.CamelTestSupport; import org.junit.jupiter.api.Test; import static org.apache.camel.component.jms.JmsComponent.jmsComponentAutoAcknowledge; /** * ActiveMQ specific unit test */ public class ActiveMQConsumeWildcardQueuesTest extends CamelTestSupport { @Test public void testWildcard() throws Exception { getMockEndpoint("mock:chelsea").expectedBodiesReceived("B"); getMockEndpoint("mock:1st").expectedBodiesReceived("D"); getMockEndpoint("mock:other").expectedBodiesReceivedInAnyOrder("A", "C"); template.sendBody("activemq:queue:sport.pl.manu", "A"); template.sendBody("activemq:queue:sport.pl.chelsea", "B"); template.sendBody("activemq:queue:sport.pl.arsenal", "C"); template.sendBody("activemq:queue:sport.1st.leeds", "D"); assertMockEndpointsSatisfied(); } @Override protected CamelContext createCamelContext() throws Exception { CamelContext camelContext = super.createCamelContext(); ConnectionFactory connectionFactory = CamelJmsTestHelper.createConnectionFactory(); camelContext.addComponent("activemq", jmsComponentAutoAcknowledge(connectionFactory)); return camelContext; } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { public void configure() throws Exception { // use wildcard to consume from all sports from("activemq:queue:sport.>") .to("log:received?showHeaders=true") .choice() // the JMSDestination contains from which queue the message was consumed from .when(header("JMSDestination").isEqualTo("queue://sport.pl.chelsea")) .to("mock:chelsea") // we can use a reg exp to match any message from 1st division .when(header("JMSDestination").regex("queue://sport.1st.*")) .to("mock:1st") .otherwise() .to("mock:other") .end(); } }; } }
xzhuah/codingDimension
xinyu/java/src/main/java/nodes/stockinfoNode/StockInfoModelProvider.java
package nodes.stockinfoNode; import common.framework.BaseModelProvider; import nodes.stockinfoNode.models.ChineseStockCompanyPOJO; import nodes.stockinfoNode.models.ChineseStockDailyRecordPOJO; import nodes.stockinfoNode.models.StockCompanyPOJO; import nodes.stockinfoNode.models.StockDailyRecordPOJO; /** * Created by <NAME> on 2020/12/7, 22:00 * nodes.stockinfoNode in codingDimensionTemplate */ public class StockInfoModelProvider extends BaseModelProvider { @Override protected void configure() { super.configure(); this.register(StockDailyRecordPOJO.class); this.register(StockCompanyPOJO.class); this.register(ChineseStockDailyRecordPOJO.class); this.register(ChineseStockCompanyPOJO.class); } }
XuanYuan1122/momole
app/src/main/java/com/moemoe/lalala/presenter/CommentContract.java
<filename>app/src/main/java/com/moemoe/lalala/presenter/CommentContract.java<gh_stars>0 package com.moemoe.lalala.presenter; /** * Created by yi on 2016/11/29. */ public interface CommentContract { interface Presenter extends BasePresenter{ void doRequest(int data,int type); } interface View extends BaseView{ void onSuccess(Object entities,boolean pull); void onChangeSuccess(Object entities); } }
jad-hamza/smart
frontends/benchmarks/smartcontracts/failCompilation/DuplicateIdentifier2.scala
import stainless.smartcontracts._ trait DuplicateIdentifier2 extends Contract { def foo() = { val i: Uint256 = Uint256.ZERO if (true) { val i: Uint256 = Uint256.ZERO true } else false } }
OpenGGEngine/OpenGG-Project
modules/core/classes/com/opengg/core/gui/UIButton.java
<gh_stars>1-10 package com.opengg.core.gui; import com.opengg.core.engine.OpenGG; import com.opengg.core.gui.layout.DirectionalLayout; import com.opengg.core.io.input.mouse.MouseButton; import com.opengg.core.io.input.mouse.MouseButtonListener; import com.opengg.core.io.input.mouse.MouseController; import com.opengg.core.math.Vector2f; public class UIButton extends UIPane implements MouseButtonListener{ private Runnable onClick = () -> {}; private Runnable onRelease = () -> {}; private Runnable onClickOutside = () -> {}; private Runnable onHoverStart = () -> {}; private Runnable onHoverStop = () -> {}; private Vector2f buttonSize; private boolean fixedButtonSize = false; private boolean hovering = false; public UIButton(UIItem background, Runnable onClick){ this(onClick); setBackground(background); } public UIButton(Runnable onClick){ super(new DirectionalLayout(DirectionalLayout.Direction.VERTICAL)); setOnClick(onClick); } public UIButton(){ this(() -> {}); } public UIButton setBackground(UIItem background){ this.addItem("backOn", background); this.repack(); return this; } public void click(){ OpenGG.asyncExec(() -> onClick.run()); } public UIButton setOnClick(Runnable runnable){ this.onClick = runnable; return this; } public UIButton setOnClickOutside(Runnable runnable){ this.onClickOutside = runnable; return this; } public UIButton setOnHoverStart(Runnable runnable) { this.onHoverStart = runnable; return this; } public UIButton setOnHoverStop(Runnable runnable) { this.onHoverStop = runnable; return this; } public UIButton setOnRelease(Runnable runnable){ this.onRelease = runnable; return this; } public UIButton setOverrideSize(Vector2f size){ this.buttonSize = size; this.fixedButtonSize = true; return this; } private Vector2f getActiveButtonSize(){ return fixedButtonSize ? buttonSize : getSize(); } @Override public void onDisable() { if(hovering){ hovering = false; onHoverStop.run(); } } @Override public void update(float delta) { super.update(delta); if(hovering && (!checkIn(MouseController.get()) || !isEnabled())) { hovering = false; onHoverStop.run(); }else if(!hovering && (checkIn(MouseController.get()) && isEnabled())){ hovering = true; onHoverStart.run(); } } @Override public void setParent(UIGroup parent) { super.setParent(parent); if(parent == null) MouseController.removeButtonListener(this); else MouseController.onButtonPress(this); } private boolean checkIn(Vector2f pos){ var size = getActiveButtonSize(); float left = this.getPosition().x * OpenGG.getWindow().getWidth(); float right = (this.getPosition().x + size.x) * OpenGG.getWindow().getWidth(); float top = (1-this.getPosition().y) * OpenGG.getWindow().getHeight(); float bottom = (1-this.getPosition().y - size.y) * OpenGG.getWindow().getHeight(); return pos.x > left && pos.x < right && pos.y < top && pos.y > bottom; } @Override public void onButtonPress(int button) { if(!this.isEnabled()) return; if(button == MouseButton.LEFT && checkIn(MouseController.get())){ OpenGG.asyncExec(() -> onClick.run()); }else if(button == MouseButton.LEFT){ onClickOutside.run(); } } @Override public void onButtonRelease(int button) { if(!this.isEnabled()) return; if(button == MouseButton.LEFT && checkIn(MouseController.get())){ OpenGG.asyncExec(() -> onRelease.run()); } } }
christopher-burke/python-scripts
cb_scripts/print_months.py
<reponame>christopher-burke/python-scripts #!/usr/bin/python # -*- coding: utf-8 -*- """Print the calendars for last, this, and next month to display on the desktop.""" import calendar from termcolor import colored from datetime import datetime class GeekToolCalendar: """Geektool Commandlet for displaying calendar months.""" def __init__(self): """Pass.""" now = datetime.now() calendar.setfirstweekday(calendar.SUNDAY) self.year = now.year self.month = now.month self.day = now.day self.format_string = str('%s' + '%3s' * 6) def spaces(self, digit): """Pass.""" if digit == "0": return " " else: return '%2s' % (digit) def color(self, today_string): """Pass.""" return colored(today_string, 'grey', 'on_yellow') def return_print_month(self, year, month): """Yield the last, this and next month.""" pcal = calendar.month for mon in range(month - 1, month + 2): if mon == 0: yield pcal(year - 1, 12) elif mon == 13: yield pcal(year + 1, 1) else: yield pcal(year, mon) def current_month(self): """Pass""" # Print the Month Header form the pmonth object. pmonth = calendar.month(self.year, self.month) mcal = calendar.monthcalendar print(pmonth[str(pmonth).index('\n') + 22].upper(),) # For each list (week) in mcal list. for week in mcal(self.year, self.month): try: # Try to find the current day. ind = week.index(self.day) week.pop(ind) output_date = '%2s' date = self.color(output_date % (self.day)) if ind == 0: insert = '{0}' else: insert = ' {0}' week.insert(ind, insert.format(date)) print(str(self.format_string % tuple([self.spaces(str(day)) for day in week]))) except ValueError: print(self.format_string % tuple([self.spaces(str(day)) for day in week])) print() # Print new line def print_month(self, yr, mon, multi=True, pass_mon=1, future_mon=1): """Print the last, this and next month.""" pcal = calendar.month if multi: for test_mon in range(mon - (pass_mon), mon + (future_mon + 1)): if test_mon == 0: yr = yr - 1 test_mon = 12 elif test_mon == 13: yr = yr + 1 test_mon = 1 if self.month == test_mon: self.current_month() else: pmonth = pcal(yr, test_mon) print(pmonth.upper()) else: self.current_month() if __name__ == "__main__": # Using the now.month get last, this and next month and print the calendar. gtc = GeekToolCalendar() gtc.print_month(gtc.year, gtc.month)
eric-erki/iD
modules/id.js
import 'browser-polyfills'; import 'string.fromcodepoint'; import 'abortcontroller-polyfill/dist/polyfill-patch-fetch'; // polyfill requestIdleCallback window.requestIdleCallback = window.requestIdleCallback || function(cb) { var start = Date.now(); return window.requestAnimationFrame(function() { cb({ didTimeout: false, timeRemaining: function() { return Math.max(0, 50 - (Date.now() - start)); } }); }); }; window.cancelIdleCallback = window.cancelIdleCallback || function(id) { window.cancelAnimationFrame(id); }; import * as iD from './index'; window.iD = iD;
Kone0/webcam-capture
webcam-capture-drivers/driver-ffmpeg-cli/src/example/java/com/github/sarxos/webcam/WebcamViewerExample.java
package com.github.sarxos.webcam; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import javax.swing.JFrame; import javax.swing.SwingUtilities; import com.github.sarxos.webcam.ds.ffmpegcli.FFmpegCliDriver; /** * Proof of concept of how to handle webcam video stream from Java * * @author <NAME> (SarXos) */ public class WebcamViewerExample extends JFrame implements Runnable, WebcamListener, WindowListener { private static final long serialVersionUID = 1L; private Webcam webcam = null; private WebcamPanel viewer = null; @Override public void run() { // IMPORTANT! Replace default driver by FFmpegCliDriver. Webcam.setDriver(new FFmpegCliDriver()); setTitle("Java Webcam Capture MJPEG POC"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); addWindowListener(this); webcam = Webcam.getDefault(); if (webcam == null) { System.out.println("No webcams supporting MJPEG format has been found..."); System.exit(1); } webcam.setViewSize(WebcamResolution.QVGA.getSize()); webcam.addWebcamListener(WebcamViewerExample.this); viewer = new WebcamPanel(webcam, false); viewer.setFPSDisplayed(true); setContentPane(viewer); pack(); setVisible(true); Thread t = new Thread() { @Override public void run() { viewer.start(); } }; t.setDaemon(true); t.start(); } public static void main(String[] args) { SwingUtilities.invokeLater(new WebcamViewerExample()); } @Override public void webcamOpen(WebcamEvent we) { System.out.println("webcam open"); } @Override public void webcamClosed(WebcamEvent we) { System.out.println("webcam closed"); } @Override public void webcamDisposed(WebcamEvent we) { System.out.println("webcam disposed"); } @Override public void webcamImageObtained(WebcamEvent we) { } @Override public void windowActivated(WindowEvent e) { } @Override public void windowClosed(WindowEvent e) { webcam.close(); } @Override public void windowClosing(WindowEvent e) { } @Override public void windowOpened(WindowEvent e) { } @Override public void windowDeactivated(WindowEvent e) { } @Override public void windowDeiconified(WindowEvent e) { System.out.println("webcam viewer resumed"); viewer.resume(); } @Override public void windowIconified(WindowEvent e) { System.out.println("webcam viewer paused"); viewer.pause(); } }
benhunter/ctf
htb/fatty-10.10.10.174/fatty-client/org/springframework/context/expression/EnvironmentAccessor.java
/* */ package org.springframework.context.expression; /* */ /* */ import org.springframework.core.env.Environment; /* */ import org.springframework.expression.AccessException; /* */ import org.springframework.expression.EvaluationContext; /* */ import org.springframework.expression.PropertyAccessor; /* */ import org.springframework.expression.TypedValue; /* */ import org.springframework.lang.Nullable; /* */ import org.springframework.util.Assert; /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public class EnvironmentAccessor /* */ implements PropertyAccessor /* */ { /* */ public Class<?>[] getSpecificTargetClasses() { /* 38 */ return new Class[] { Environment.class }; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ public boolean canRead(EvaluationContext context, @Nullable Object target, String name) throws AccessException { /* 47 */ return true; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ public TypedValue read(EvaluationContext context, @Nullable Object target, String name) throws AccessException { /* 56 */ Assert.state(target instanceof Environment, "Target must be of type Environment"); /* 57 */ return new TypedValue(((Environment)target).getProperty(name)); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ public boolean canWrite(EvaluationContext context, @Nullable Object target, String name) throws AccessException { /* 65 */ return false; /* */ } /* */ /* */ public void write(EvaluationContext context, @Nullable Object target, String name, @Nullable Object newValue) throws AccessException {} /* */ } /* Location: /home/kali/ctf/htb/fatty-10.10.10.174/ftp/fatty-client.jar!/org/springframework/context/expression/EnvironmentAccessor.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
vizee/misc
go/stdmv/stdmv.go
//go:build go1.18 package main import ( "bytes" "encoding/json" "flag" "fmt" "go/parser" "go/token" "os" "os/exec" "path" "path/filepath" "regexp" "runtime" "strconv" "strings" ) var ctx struct { GOROOT string GOOS string GOARCH string GO1VER int GOTAGS map[string]bool StdDir string BasePkg string SrcRoot string DstRoot string ModName string PkgName string } var ( recursive bool distArch map[string]bool distOS map[string]bool syncInternal bool depInternals = make(map[string]bool) newPkgName string ) func main() { initCtx() files := flag.Args() if len(files) == 1 && isDir(filepath.Join(ctx.SrcRoot, files[0])) { copyPkgDir(filepath.Join(ctx.SrcRoot, files[0]), filepath.Join(ctx.DstRoot, files[0]), recursive) } else { copyPkgFiles(ctx.SrcRoot, ctx.DstRoot, files) } if syncInternal { movedDeps := make(map[string]bool) for len(depInternals) > 0 { pending := make([]string, 0, len(depInternals)) for pkgPath := range depInternals { if !movedDeps[pkgPath] { pending = append(pending, pkgPath) } delete(depInternals, pkgPath) } for _, pkgPath := range pending { mapped := mapInternalPkgPath(pkgPath) origPath := filepath.Join(ctx.StdDir, pkgPath) mappedPath := filepath.Join(ctx.DstRoot, mapped[len(ctx.ModName):]) copyPkgDir(origPath, mappedPath, false) movedDeps[pkgPath] = true } } } } func copyPkgDir(srcDir string, dstDir string, rec bool) { debugf("copyPkgDir %s -> %s\n", srcDir, dstDir) entries, err := os.ReadDir(srcDir) stopOnErr("read dir", err) var ( subDirs []string files []string ) for _, e := range entries { if e.IsDir() { subDirs = append(subDirs, e.Name()) continue } name := e.Name() if !strings.HasSuffix(name, ".go") && !strings.HasSuffix(name, ".s") { continue } if strings.HasSuffix(name, "_test.go") { continue } distos, distarch := parseConstraintFromName(name) if (distos != "" && distos != ctx.GOOS) || (distarch != "" && distarch != ctx.GOARCH) { continue } files = append(files, name) } if len(files) > 0 { copyPkgFiles(srcDir, dstDir, files) } if !rec { return } for _, subDir := range subDirs { subSrcDir := filepath.Join(srcDir, subDir) subDstDir := filepath.Join(dstDir, subDir) copyPkgDir(subSrcDir, subDstDir, rec) } } func copyPkgFiles(srcDir string, dstDir string, files []string) { debugf("copyPkgFiles %s -> %s\n", srcDir, dstDir) if !isDir(dstDir) { stopOnErr("mkdir", os.MkdirAll(dstDir, 0755)) } if dstDir == ctx.DstRoot { newPkgName = ctx.PkgName } else { newPkgName = "" } for _, file := range files { srcName := filepath.Join(srcDir, file) if !isRegularFile(srcName) { continue } dstName := filepath.Join(dstDir, file) if strings.HasSuffix(file, ".go") { stopOnErr("copy .go file", processGoFile(srcName, dstName)) } else if strings.HasSuffix(file, ".s") { stopOnErr("copy .s file", copyAsmFile(srcName, dstName)) } else { stopOnErr("copy file", copyFile(srcName, dstName)) } } goFmt := exec.Command("gofmt", "-w", ".") goFmt.Stderr = os.Stderr goFmt.Dir = dstDir err := goFmt.Run() if err != nil { fmt.Fprintf(os.Stderr, "run gofmt: %v\n", err) } } func copyAsmFile(srcName string, dstName string) error { data, err := os.ReadFile(srcName) if err != nil { return err } var buildExpr string p := 0 for p < len(data) { l := bytes.IndexByte(data[p:], '\n') if l < 0 { break } if l > 0 { if !bytes.HasPrefix(data[p:], []byte("//")) { break } if bytes.HasPrefix(data[p:], []byte("//go:build")) { buildExpr = string(bytes.TrimSpace(data[p+10 : p+l])) } } p = p + l + 1 } if !evalGoBuildConstraint(buildExpr) { debugf("skip file: %s\n", srcName) return nil } debugf("process .s: %s -> %s\n", srcName, dstName) return os.WriteFile(dstName, data, 0644) } func processGoFile(srcName string, dstName string) error { srcData, err := os.ReadFile(srcName) if err != nil { return err } metadata, err := scanGoMetadata(srcData) if err != nil { return err } if !evalGoBuildConstraint(metadata.build) { debugf("skip file: %s\n", srcName) return nil } debugf("process .go: %s -> %s\n", srcName, dstName) content := [][]byte{srcData} if newPkgName != "" { content = shallowReplace(content, []byte(fmt.Sprintf("package %s", metadata.pkgname)), []byte(fmt.Sprintf("package %s", newPkgName)), 1) } for _, pkgPath := range metadata.imports { orig := pkgPath[1 : len(pkgPath)-1] mapped := mapInternalPkgPath(orig) if mapped == orig { continue } depInternals[orig] = true debugf("map internal: %s -> %s\n", orig, mapped) content = shallowReplace(content, []byte(pkgPath), []byte("\""+mapped+"\""), 1) } content = shallowReplace(content, []byte("//go:"), func(next []byte) []byte { if bytes.HasPrefix(next, []byte("build")) { return []byte("//go:") } else { return []byte("//!go:") } }, -1) f, err := os.Create(dstName) if err != nil { return err } defer f.Close() for _, seg := range content { _, err := f.Write(seg) if err != nil { return err } } return nil } func shallowReplace(segs [][]byte, find []byte, to any, n int) [][]byte { var sep func([]byte) []byte switch val := to.(type) { case []byte: sep = func(b []byte) []byte { return val } case func([]byte) []byte: sep = val default: panic("invalid `to` type") } return xflatn(n, segs, func(t []byte, m int) ([][]byte, int) { if m > 0 { m++ } parts := bytes.SplitN(t, find, m) if len(parts) == 1 { return parts, 0 } return xjoin(parts, sep), len(parts) - 1 }) } func parseConstraintFromName(name string) (goos string, goarch string) { ext := path.Ext(name) if ext == "" { return } segs := strings.Split(name[:len(name)-len(ext)], "_") n := len(segs) if n > 1 && distArch[segs[n-1]] { goarch = segs[n-1] n-- } if n > 1 && distOS[segs[n-1]] { goos = segs[n-1] } return } func mapInternalPkgPath(pkgPath string) string { if pkgPath == "internal" || strings.HasPrefix(pkgPath, "internal/") { return path.Join(ctx.ModName, "internal/std", pkgPath[8:]) } p := strings.Index(pkgPath, "/internal/") if p < 0 { if !strings.HasSuffix(pkgPath, "/internal") { return pkgPath } p = len(pkgPath) - 9 } if strings.HasPrefix(pkgPath, ctx.BasePkg) { return path.Join(ctx.ModName, pkgPath[len(ctx.BasePkg):]) } return path.Join(ctx.ModName, "internal/std", pkgPath[:p], pkgPath[p+9:]) } type goMetadata struct { build string pkgname string imports []string } func scanGoMetadata(src []byte) (*goMetadata, error) { f, err := parser.ParseFile(token.NewFileSet(), "", src, parser.ImportsOnly|parser.ParseComments) if err != nil { return nil, err } metadata := &goMetadata{ pkgname: f.Name.Name, } for _, i := range f.Imports { metadata.imports = append(metadata.imports, i.Path.Value) } stop := false for _, cg := range f.Comments { if cg.Pos() > f.Name.Pos() { break } for _, c := range cg.List { if c.Text[1] == '*' { stop = true } if strings.HasPrefix(c.Text, "//go:build") { metadata.build = strings.TrimSpace(c.Text[10:]) break } if strings.HasPrefix(strings.TrimSpace(c.Text[2:]), "+build") { fatalf("unsupport +build constraint syntax") } } if stop { break } } return metadata, nil } func isId(c byte) bool { return 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9' || c == '.' || c == '_' } func checkGoBuildable(id string) bool { if ctx.GOOS == id || ctx.GOARCH == id || ctx.GOTAGS[id] { return true } if strings.HasPrefix(id, "go1.") { ver, _ := strconv.Atoi(id[4:]) return ver <= ctx.GO1VER } return false } func evalGoBuildConstraint(expr string) bool { if expr == "" { return true } if expr == "ignore" { return false } bad := false i := 0 var eval func() bool eval = func() bool { reg := false not := false binop := byte(0) for !bad { for i < len(expr) && (expr[i] == ' ' || expr[i] == '\t') { i++ } if i >= len(expr) { break } c := expr[i] switch c { case '!': not = !not i++ case '&', '|': if binop == 0 && !not { binop = c i += 2 } else { bad = true } case ')': return reg default: var unary bool if c == '(' { i++ unary = eval() if i < len(expr) && expr[i] == ')' { i++ } else { bad = true } } else { b := i for i < len(expr) && isId(expr[i]) { i++ } if b == i { bad = true return false } id := expr[b:i] if checkGoBuildable(id) { unary = true } } if not { unary = !unary not = false } switch binop { case '&': reg = reg && unary case '|': reg = reg || unary default: reg = unary } binop = 0 } } return reg } res := eval() if bad { fmt.Fprintf(os.Stderr, "bad go:build constraint: %s\n", expr) return false } return res } func xjoin[T any](a []T, sep func(T) T) []T { r := make([]T, 0, len(a)+len(a)-1) for i, x := range a { if i > 0 { r = append(r, sep(x)) } r = append(r, x) } return r } func xflatn[T any](n int, a []T, f func(T, int) ([]T, int)) []T { r := make([]T, 0, len(a)) for i, x := range a { if n == 0 { r = append(r, a[i:]...) break } b, k := f(x, n) for _, j := range b { r = append(r, j) } if n > 0 { if n > k { n -= k } else { n = 0 } } } return r } func copyFile(srcName string, dstName string) error { data, err := os.ReadFile(srcName) if err == nil { err = os.WriteFile(dstName, data, 0644) } return err } func isDir(path string) bool { fi, err := os.Stat(path) return err == nil && fi.IsDir() } func isRegularFile(path string) bool { fi, err := os.Stat(path) return err == nil && fi.Mode().IsRegular() } func initCtx() { flag.Usage = func() { fmt.Fprintf(os.Stderr, "%s: [options] files...\n\n", filepath.Base(os.Args[0])) flag.PrintDefaults() } // TODO: load build config from go/build goVer, _ := strconv.Atoi(runtime.Version()[4:]) var ( gotags string userDeps string basePkg string dstRoot string printCtx bool ) flag.StringVar(&ctx.GOROOT, "goroot", runtime.GOROOT(), "GOROOT") flag.StringVar(&ctx.GOOS, "goos", runtime.GOOS, "GOOS") flag.StringVar(&ctx.GOARCH, "goarch", runtime.GOARCH, "GOARCH") flag.IntVar(&goVer, "gover", goVer, "go1 sub-version") flag.StringVar(&gotags, "gotags", "", "GOTAGS") flag.StringVar(&userDeps, "deps", "", "user deps") flag.StringVar(&basePkg, "base", "", "base package") flag.StringVar(&dstRoot, "d", ".", "destination directory") flag.StringVar(&ctx.PkgName, "pkgname", "", "destination package") flag.BoolVar(&recursive, "r", false, "recursive") flag.BoolVar(&syncInternal, "internal", false, "copy internal") flag.BoolVar(&printCtx, "printctx", false, "print ctx") flag.Parse() if flag.NArg() == 0 { flag.Usage() os.Exit(1) } ctx.GO1VER = goVer ctx.GOTAGS = map[string]bool{ "goexperiment.regabiwrappers": true, "goexperiment.regabireflect": true, "goexperiment.regabiargs": true, "goexperiment.pacerredesign": true, } if gotags != "" { for _, tag := range strings.Split(gotags, ",") { if strings.HasPrefix(tag, "!") { delete(ctx.GOTAGS, tag[1:]) } else { ctx.GOTAGS[tag] = true } } } if userDeps != "" { for _, dep := range strings.Split(userDeps, ",") { depInternals[dep] = true } } ctx.StdDir = filepath.Join(ctx.GOROOT, "src") ctx.BasePkg = basePkg if basePkg != "" { ctx.SrcRoot = filepath.Join(ctx.StdDir, basePkg) } else { ctx.SrcRoot = ctx.StdDir } ctx.DstRoot = filepath.Clean(dstRoot) if ctx.DstRoot != "." && !isDir(ctx.DstRoot) { stopOnErr("mkdir", os.MkdirAll(ctx.DstRoot, 0755)) } var distData bytes.Buffer goDistList := exec.Command("go", "tool", "dist", "list", "-json") goDistList.Stderr = os.Stderr goDistList.Stdout = &distData stopOnErr("go tool dist list", goDistList.Run()) var dists []struct { CgoSupported bool `json:"CgoSupported"` FirstClass bool `json:"FirstClass"` GOARCH string `json:"GOARCH"` GOOS string `json:"GOOS"` } stopOnErr("parse go dist list", json.Unmarshal(distData.Bytes(), &dists)) distArch = make(map[string]bool) distOS = make(map[string]bool) for _, dist := range dists { distArch[dist.GOARCH] = true distOS[dist.GOOS] = true } goModFile := filepath.Join(ctx.DstRoot, "go.mod") if !isRegularFile(goModFile) { goModInit := exec.Command("go", "mod", "init") goModInit.Stderr = os.Stderr goModInit.Dir = ctx.DstRoot stopOnErr("go mod init", goModInit.Run()) } modName, err := loadGoModName(goModFile) stopOnErr("load go module name", err) ctx.ModName = modName if printCtx { data, _ := json.MarshalIndent(&ctx, "", " ") fmt.Printf("context: %s\n", data) } } func loadGoModName(gomod string) (string, error) { data, err := os.ReadFile(gomod) if err != nil { return "", err } match := regexp.MustCompile(`module\s*(\S+)`).FindSubmatch(data) if len(match) == 0 { return "", fmt.Errorf("no module found") } return string(match[1]), err } func debugf(format string, args ...any) { fmt.Printf(format, args...) } func fatalf(format string, args ...any) { fmt.Fprintf(os.Stderr, format, args...) os.Exit(1) } func stopOnErr(op string, err error) { if err != nil { fatalf("%s: %v\n", op, err) } }
RobotLocomotion/drake-python3.7
solvers/fbstab/components/mpc_residual.cc
#include "drake/solvers/fbstab/components/mpc_residual.h" #include <algorithm> #include <cmath> #include <stdexcept> #include <Eigen/Dense> #include "drake/solvers/fbstab/components/mpc_data.h" #include "drake/solvers/fbstab/components/mpc_variable.h" namespace drake { namespace solvers { namespace fbstab { MpcResidual::MpcResidual(int N, int nx, int nu, int nc) { if (N <= 0 || nx <= 0 || nu <= 0 || nc <= 0) { throw std::runtime_error( "All inputs to MpcResidual::MpcResidual must be >= 1."); } N_ = N; nx_ = nx; nu_ = nu; nc_ = nc; nz_ = (N_ + 1) * (nx_ + nu_); nl_ = (N_ + 1) * nx_; nv_ = (N_ + 1) * nc_; z_.resize(nz_); l_.resize(nl_); v_.resize(nv_); Fill(0.0); } void MpcResidual::Fill(double a) { z_.setConstant(a); l_.setConstant(a); v_.setConstant(a); } void MpcResidual::Negate() { z_ *= -1; l_ *= -1; v_ *= -1; } double MpcResidual::Norm() const { return sqrt(znorm_ * znorm_ + lnorm_ * lnorm_ + vnorm_ * vnorm_); } double MpcResidual::Merit() const { const double temp = this->Norm(); return 0.5 * temp * temp; } void MpcResidual::InnerResidual(const MpcVariable& x, const MpcVariable& xbar, double sigma) { const MpcData* const data = x.data(); if (xbar.data_ != data) { throw std::runtime_error( "In MpcResidual::InnerResidual: x and xbar have mismatched problem " "data."); } // r.z = H*z + f + G'*l + A'*v + sigma*(z-zbar) z_.setConstant(0.0); data->axpyf(1.0, &z_); data->gemvH(x.z(), 1.0, 1.0, &z_); data->gemvGT(x.l(), 1.0, 1.0, &z_); data->gemvAT(x.v(), 1.0, 1.0, &z_); z_.noalias() += sigma * (x.z() - xbar.z()); // r.l = h - G*z + sigma(l - lbar) l_.setConstant(0.0); data->axpyh(1.0, &l_); data->gemvG(x.z(), -1.0, 1.0, &l_); l_.noalias() += sigma * (x.l() - xbar.l()); // rv = phi(y + sigma*(v-vbar),v) for (int i = 0; i < nv_; i++) { const double ys = x.y()(i) + sigma * (x.v()(i) - xbar.v()(i)); v_(i) = pfb(ys, x.v()(i), alpha_); } znorm_ = z_.norm(); lnorm_ = l_.norm(); vnorm_ = v_.norm(); } void MpcResidual::NaturalResidual(const MpcVariable& x) { const MpcData* const data = x.data(); // r.z = H*z + f + G'*l + A'*v z_.setConstant(0.0); data->axpyf(1.0, &z_); data->gemvH(x.z(), 1.0, 1.0, &z_); data->gemvGT(x.l(), 1.0, 1.0, &z_); data->gemvAT(x.v(), 1.0, 1.0, &z_); // r.l = h - G*z + sigma(l - lbar) l_.setConstant(0.0); data->axpyh(1.0, &l_); data->gemvG(x.z(), -1.0, 1.0, &l_); // rv = min(y,v) for (int i = 0; i < nv_; i++) { v_(i) = std::min(x.y()(i), x.v()(i)); } znorm_ = z_.norm(); lnorm_ = l_.norm(); vnorm_ = v_.norm(); } void MpcResidual::PenalizedNaturalResidual(const MpcVariable& x) { NaturalResidual(x); for (int i = 0; i < nv_; i++) { v_(i) = alpha_ * v_(i) + (1 - alpha_) * std::max(0.0, x.y()(i)) * std::max(0.0, x.v()(i)); } znorm_ = z_.norm(); lnorm_ = l_.norm(); vnorm_ = v_.norm(); } double MpcResidual::pfb(double a, double b, double alpha) { double fb = a + b - sqrt(a * a + b * b); return alpha * fb + (1.0 - alpha) * std::max(0.0, a) * std::max(0.0, b); } } // namespace fbstab } // namespace solvers } // namespace drake
vchoudhari45/codingcargo
src/main/java/com/vc/medium/L921.java
package com.vc.medium; import java.util.*; class L921 { public int minAddToMakeValid(String S) { Stack<Character> st = new Stack<>(); int res = 0; for(int i = 0; i < S.length(); i++) { char ch = S.charAt(i); if(ch == '(') st.push(ch); else { if(!st.isEmpty()) st.pop(); else res++; } } return res + st.size(); } }
frosenberg/elasticsearch-nvd-river
src/main/java/gov/nist/scap/schema/cvss_v2/_0/EnvironmentalMetricsType.java
<reponame>frosenberg/elasticsearch-nvd-river // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.07.30 at 11:36:03 AM CEST // package gov.nist.scap.schema.cvss_v2._0; import java.math.BigDecimal; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.datatype.XMLGregorianCalendar; /** * <p>Java class for environmentalMetricsType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="environmentalMetricsType"> * &lt;complexContent> * &lt;extension base="{http://scap.nist.gov/schema/cvss-v2/0.2}metricsType"> * &lt;sequence> * &lt;element name="score" type="{http://scap.nist.gov/schema/cvss-v2/0.2}zeroToTenDecimalType" minOccurs="0"/> * &lt;group ref="{http://scap.nist.gov/schema/cvss-v2/0.2}environmentalVectorsGroup"/> * &lt;element name="source" type="{http://www.w3.org/2001/XMLSchema}anyURI"/> * &lt;element name="generated-on-datetime" type="{http://www.w3.org/2001/XMLSchema}dateTime" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "environmentalMetricsType", propOrder = { "score", "collateralDamagePotential", "targetDistribution", "confidentialityRequirement", "integrityRequirement", "availabilityRequirement", "source", "generatedOnDatetime" }) public class EnvironmentalMetricsType extends MetricsType { protected BigDecimal score; @XmlElement(name = "collateral-damage-potential") protected CollateralDamagePotentialType collateralDamagePotential; @XmlElement(name = "target-distribution") protected TargetDistributionType targetDistribution; @XmlElement(name = "confidentiality-requirement") protected CiaRequirementType confidentialityRequirement; @XmlElement(name = "integrity-requirement") protected CiaRequirementType integrityRequirement; @XmlElement(name = "availability-requirement") protected CiaRequirementType availabilityRequirement; @XmlElement(required = true) @XmlSchemaType(name = "anyURI") protected String source; @XmlElement(name = "generated-on-datetime") @XmlSchemaType(name = "dateTime") protected XMLGregorianCalendar generatedOnDatetime; /** * Gets the value of the score property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getScore() { return score; } /** * Sets the value of the score property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setScore(BigDecimal value) { this.score = value; } /** * Gets the value of the collateralDamagePotential property. * * @return * possible object is * {@link CollateralDamagePotentialType } * */ public CollateralDamagePotentialType getCollateralDamagePotential() { return collateralDamagePotential; } /** * Sets the value of the collateralDamagePotential property. * * @param value * allowed object is * {@link CollateralDamagePotentialType } * */ public void setCollateralDamagePotential(CollateralDamagePotentialType value) { this.collateralDamagePotential = value; } /** * Gets the value of the targetDistribution property. * * @return * possible object is * {@link TargetDistributionType } * */ public TargetDistributionType getTargetDistribution() { return targetDistribution; } /** * Sets the value of the targetDistribution property. * * @param value * allowed object is * {@link TargetDistributionType } * */ public void setTargetDistribution(TargetDistributionType value) { this.targetDistribution = value; } /** * Gets the value of the confidentialityRequirement property. * * @return * possible object is * {@link CiaRequirementType } * */ public CiaRequirementType getConfidentialityRequirement() { return confidentialityRequirement; } /** * Sets the value of the confidentialityRequirement property. * * @param value * allowed object is * {@link CiaRequirementType } * */ public void setConfidentialityRequirement(CiaRequirementType value) { this.confidentialityRequirement = value; } /** * Gets the value of the integrityRequirement property. * * @return * possible object is * {@link CiaRequirementType } * */ public CiaRequirementType getIntegrityRequirement() { return integrityRequirement; } /** * Sets the value of the integrityRequirement property. * * @param value * allowed object is * {@link CiaRequirementType } * */ public void setIntegrityRequirement(CiaRequirementType value) { this.integrityRequirement = value; } /** * Gets the value of the availabilityRequirement property. * * @return * possible object is * {@link CiaRequirementType } * */ public CiaRequirementType getAvailabilityRequirement() { return availabilityRequirement; } /** * Sets the value of the availabilityRequirement property. * * @param value * allowed object is * {@link CiaRequirementType } * */ public void setAvailabilityRequirement(CiaRequirementType value) { this.availabilityRequirement = value; } /** * Gets the value of the source property. * * @return * possible object is * {@link String } * */ public String getSource() { return source; } /** * Sets the value of the source property. * * @param value * allowed object is * {@link String } * */ public void setSource(String value) { this.source = value; } /** * Gets the value of the generatedOnDatetime property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getGeneratedOnDatetime() { return generatedOnDatetime; } /** * Sets the value of the generatedOnDatetime property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setGeneratedOnDatetime(XMLGregorianCalendar value) { this.generatedOnDatetime = value; } }
blindsubmissions/icse19replication
generated-tests/qmosa/tests/s1005/92_jcvi-javacommon/evosuite-tests/org/jcvi/jillion/core/residue/nt/DefaultNucleotideCodec_ESTest.java
/* * This file was automatically generated by EvoSuite * Fri Aug 24 11:01:21 GMT 2018 */ package org.jcvi.jillion.core.residue.nt; import org.junit.Test; import static org.junit.Assert.*; import static org.evosuite.runtime.EvoAssertions.*; import java.nio.BufferUnderflowException; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.NoSuchElementException; import java.util.Set; import org.evosuite.runtime.EvoRunner; import org.evosuite.runtime.EvoRunnerParameters; import org.jcvi.jillion.core.Range; import org.jcvi.jillion.core.residue.nt.DefaultNucleotideCodec; import org.jcvi.jillion.core.residue.nt.Nucleotide; import org.junit.runner.RunWith; @RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true, useJEE = true) public class DefaultNucleotideCodec_ESTest extends DefaultNucleotideCodec_ESTest_scaffolding { /** //Test case number: 0 /*Coverage entropy=2.1972245773362196 */ @Test(timeout = 4000) public void test00() throws Throwable { DefaultNucleotideCodec defaultNucleotideCodec0 = DefaultNucleotideCodec.INSTANCE; byte[] byteArray0 = new byte[9]; byteArray0[0] = (byte)124; byteArray0[1] = (byte) (-1); byte byte0 = (byte)0; byteArray0[2] = (byte)0; byteArray0[3] = (byte)7; byteArray0[4] = (byte)0; byteArray0[5] = (byte)69; byte byte1 = (byte)13; byteArray0[6] = (byte)13; byte byte2 = (byte) (-63); byteArray0[7] = (byte) (-63); defaultNucleotideCodec0.iterator(byteArray0); byte byte3 = (byte) (-40); byteArray0[8] = (byte) (-40); // Undeclared exception! try { defaultNucleotideCodec0.getGapOffsets(byteArray0); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // 9 // verifyException("org.jcvi.jillion.core.residue.nt.DefaultNucleotideCodec$IteratorImpl", e); } } /** //Test case number: 1 /*Coverage entropy=2.4849066497880012 */ @Test(timeout = 4000) public void test01() throws Throwable { DefaultNucleotideCodec defaultNucleotideCodec0 = DefaultNucleotideCodec.INSTANCE; byte[] byteArray0 = new byte[6]; byte byte0 = (byte) (-125); byteArray0[0] = (byte) (-125); byte byte1 = (byte) (-12); byteArray0[1] = (byte) (-12); byte byte2 = (byte)24; byteArray0[2] = (byte)24; defaultNucleotideCodec0.decode(byteArray0, 0L); byteArray0[3] = (byte)66; byte byte3 = (byte)0; defaultNucleotideCodec0.getUngappedLength(byteArray0); byteArray0[4] = (byte)0; byte byte4 = (byte)0; // Undeclared exception! try { defaultNucleotideCodec0.decode(byteArray0, (byte)66); fail("Expecting exception: IndexOutOfBoundsException"); } catch(IndexOutOfBoundsException e) { // // index 66 corresponds to encodedIndex 37 encodedglyph length is 6 // verifyException("org.jcvi.jillion.core.residue.nt.DefaultNucleotideCodec", e); } } /** //Test case number: 2 /*Coverage entropy=2.1972245773362196 */ @Test(timeout = 4000) public void test02() throws Throwable { DefaultNucleotideCodec.values(); DefaultNucleotideCodec defaultNucleotideCodec0 = DefaultNucleotideCodec.INSTANCE; DefaultNucleotideCodec defaultNucleotideCodec1 = DefaultNucleotideCodec.INSTANCE; byte[] byteArray0 = new byte[6]; defaultNucleotideCodec0.getNumberOfGaps(byteArray0); byteArray0[0] = (byte) (-21); byte byte0 = (byte)53; byteArray0[1] = (byte)53; byteArray0[2] = (byte)116; byte byte1 = (byte)29; byteArray0[3] = (byte)29; byteArray0[4] = (byte) (-1); byteArray0[5] = (byte)0; Iterator<Nucleotide> iterator0 = defaultNucleotideCodec1.iterator(byteArray0); // Undeclared exception! try { defaultNucleotideCodec0.encode((-379), iterator0); fail("Expecting exception: IllegalArgumentException"); } catch(IllegalArgumentException e) { // // no message in exception (getMessage() returned null) // verifyException("java.nio.ByteBuffer", e); } } /** //Test case number: 3 /*Coverage entropy=1.9913464134109882 */ @Test(timeout = 4000) public void test03() throws Throwable { DefaultNucleotideCodec defaultNucleotideCodec0 = DefaultNucleotideCodec.INSTANCE; byte[] byteArray0 = new byte[6]; byteArray0[0] = (byte)0; byteArray0[1] = (byte) (-36); byteArray0[2] = (byte)71; byteArray0[3] = (byte)32; byteArray0[4] = (byte)81; byteArray0[5] = (byte) (-76); // Undeclared exception! try { defaultNucleotideCodec0.getUngappedLength(byteArray0); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // 6 // verifyException("org.jcvi.jillion.core.residue.nt.DefaultNucleotideCodec$IteratorImpl", e); } } /** //Test case number: 4 /*Coverage entropy=2.6023807799324814 */ @Test(timeout = 4000) public void test04() throws Throwable { DefaultNucleotideCodec defaultNucleotideCodec0 = DefaultNucleotideCodec.INSTANCE; byte[] byteArray0 = new byte[9]; byteArray0[0] = (byte)15; byte byte0 = (byte)0; byteArray0[1] = (byte)0; byteArray0[2] = (byte)0; byteArray0[3] = (byte) (-100); byteArray0[4] = (byte)28; byteArray0[5] = (byte)0; byteArray0[6] = (byte)0; defaultNucleotideCodec0.decode(byteArray0, 0L); byteArray0[7] = (byte)0; byteArray0[8] = (byte)3; Iterator<Nucleotide> iterator0 = defaultNucleotideCodec0.iterator(byteArray0); defaultNucleotideCodec0.encode(8, iterator0); byte[] byteArray1 = new byte[0]; // Undeclared exception! try { defaultNucleotideCodec0.decode(byteArray1, (-4233L)); fail("Expecting exception: IndexOutOfBoundsException"); } catch(IndexOutOfBoundsException e) { // // index can not be negative: -4233 // verifyException("org.jcvi.jillion.core.residue.nt.DefaultNucleotideCodec", e); } } /** //Test case number: 5 /*Coverage entropy=1.7917594692280547 */ @Test(timeout = 4000) public void test05() throws Throwable { DefaultNucleotideCodec defaultNucleotideCodec0 = DefaultNucleotideCodec.INSTANCE; // Undeclared exception! try { defaultNucleotideCodec0.getUngappedOffsetFor((byte[]) null, 2851); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("java.nio.ByteBuffer", e); } } /** //Test case number: 6 /*Coverage entropy=2.70805020110221 */ @Test(timeout = 4000) public void test06() throws Throwable { DefaultNucleotideCodec defaultNucleotideCodec0 = DefaultNucleotideCodec.INSTANCE; byte[] byteArray0 = new byte[8]; byteArray0[0] = (byte) (-35); byteArray0[1] = (byte)0; byteArray0[2] = (byte)0; byteArray0[3] = (byte)0; byteArray0[4] = (byte)14; byteArray0[5] = (byte)0; byteArray0[6] = (byte)0; byteArray0[7] = (byte) (-1); defaultNucleotideCodec0.getGapOffsets(byteArray0); defaultNucleotideCodec0.getGappedOffsetFor(byteArray0, 87); Nucleotide nucleotide0 = Nucleotide.Adenine; Set<Nucleotide> set0 = nucleotide0.getAllPossibleAmbiguities(); defaultNucleotideCodec0.encode((Collection<Nucleotide>) set0); defaultNucleotideCodec0.encode((Collection<Nucleotide>) set0); // Undeclared exception! try { defaultNucleotideCodec0.toString((byte[]) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("java.nio.ByteBuffer", e); } } /** //Test case number: 7 /*Coverage entropy=1.8711604142318068 */ @Test(timeout = 4000) public void test07() throws Throwable { DefaultNucleotideCodec.values(); DefaultNucleotideCodec.values(); DefaultNucleotideCodec defaultNucleotideCodec0 = DefaultNucleotideCodec.INSTANCE; byte[] byteArray0 = new byte[9]; byteArray0[0] = (byte)64; byteArray0[1] = (byte) (-105); byteArray0[2] = (byte)90; byteArray0[3] = (byte)47; byteArray0[4] = (byte) (-97); byteArray0[5] = (byte)0; byteArray0[6] = (byte)4; byteArray0[7] = (byte)9; byteArray0[8] = (byte)11; // Undeclared exception! try { defaultNucleotideCodec0.getGappedOffsetFor(byteArray0, (byte) (-97)); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // 9 // verifyException("org.jcvi.jillion.core.residue.nt.DefaultNucleotideCodec$IteratorImpl", e); } } /** //Test case number: 8 /*Coverage entropy=1.6094379124341005 */ @Test(timeout = 4000) public void test08() throws Throwable { DefaultNucleotideCodec defaultNucleotideCodec0 = DefaultNucleotideCodec.INSTANCE; byte[] byteArray0 = new byte[6]; byteArray0[0] = (byte)0; byteArray0[1] = (byte) (-36); byteArray0[2] = (byte)71; byteArray0[3] = (byte)32; byteArray0[2] = (byte)81; defaultNucleotideCodec0.decodedLengthOf(byteArray0); Range range0 = Range.of((long) (byte)71); // Undeclared exception! try { defaultNucleotideCodec0.iterator(byteArray0, range0); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // 39 // verifyException("org.jcvi.jillion.core.residue.nt.DefaultNucleotideCodec$IteratorImpl", e); } } /** //Test case number: 9 /*Coverage entropy=1.0986122886681096 */ @Test(timeout = 4000) public void test09() throws Throwable { DefaultNucleotideCodec defaultNucleotideCodec0 = DefaultNucleotideCodec.INSTANCE; byte[] byteArray0 = new byte[6]; byteArray0[0] = (byte)0; byteArray0[1] = (byte) (-36); byteArray0[2] = (byte)71; LinkedList<Nucleotide> linkedList0 = new LinkedList<Nucleotide>(); Nucleotide nucleotide0 = Nucleotide.Unknown; linkedList0.offerFirst(nucleotide0); Range range0 = Range.of((-4200L)); range0.iterator(); DefaultNucleotideCodec defaultNucleotideCodec1 = DefaultNucleotideCodec.INSTANCE; // Undeclared exception! try { defaultNucleotideCodec1.iterator(byteArray0, range0); fail("Expecting exception: IndexOutOfBoundsException"); } catch(IndexOutOfBoundsException e) { // // range [ -4200 .. -4200 ]/0B is out of range of sequence which is only [ 0 .. 14436095 ]/0B // verifyException("org.jcvi.jillion.core.residue.nt.DefaultNucleotideCodec$IteratorImpl", e); } } /** //Test case number: 10 /*Coverage entropy=1.0986122886681096 */ @Test(timeout = 4000) public void test10() throws Throwable { DefaultNucleotideCodec defaultNucleotideCodec0 = DefaultNucleotideCodec.INSTANCE; byte[] byteArray0 = new byte[4]; byteArray0[0] = (byte)10; byteArray0[1] = (byte)10; byteArray0[2] = (byte)10; byteArray0[3] = (byte)10; // Undeclared exception! try { defaultNucleotideCodec0.toString(byteArray0); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // 4 // verifyException("org.jcvi.jillion.core.residue.nt.DefaultNucleotideCodec", e); } } /** //Test case number: 11 /*Coverage entropy=1.8946891171539901 */ @Test(timeout = 4000) public void test11() throws Throwable { DefaultNucleotideCodec defaultNucleotideCodec0 = DefaultNucleotideCodec.INSTANCE; byte[] byteArray0 = new byte[9]; byteArray0[0] = (byte)52; byteArray0[1] = (byte)0; byteArray0[2] = (byte)10; byteArray0[3] = (byte)127; byteArray0[4] = (byte)69; byteArray0[5] = (byte)24; byteArray0[6] = (byte) (-118); byteArray0[7] = (byte)4; byteArray0[8] = (byte)32; // Undeclared exception! try { defaultNucleotideCodec0.getNumberOfGaps(byteArray0); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // 9 // verifyException("org.jcvi.jillion.core.residue.nt.DefaultNucleotideCodec$IteratorImpl", e); } } /** //Test case number: 12 /*Coverage entropy=2.7516666169315167 */ @Test(timeout = 4000) public void test12() throws Throwable { DefaultNucleotideCodec.values(); DefaultNucleotideCodec.values(); DefaultNucleotideCodec defaultNucleotideCodec0 = DefaultNucleotideCodec.INSTANCE; byte[] byteArray0 = new byte[9]; byteArray0[0] = (byte)64; byteArray0[1] = (byte) (-105); byteArray0[2] = (byte)90; byteArray0[3] = (byte)47; byteArray0[4] = (byte) (-97); byteArray0[5] = (byte)0; DefaultNucleotideCodec defaultNucleotideCodec1 = DefaultNucleotideCodec.INSTANCE; defaultNucleotideCodec1.getGappedOffsetFor(byteArray0, 12); Nucleotide nucleotide0 = Nucleotide.Adenine; Set<Nucleotide> set0 = nucleotide0.getAllPossibleAmbiguities(); DefaultNucleotideCodec defaultNucleotideCodec2 = DefaultNucleotideCodec.INSTANCE; defaultNucleotideCodec2.encode((Collection<Nucleotide>) set0); defaultNucleotideCodec1.encode((Collection<Nucleotide>) set0); // Undeclared exception! defaultNucleotideCodec0.toString(byteArray0); } /** //Test case number: 13 /*Coverage entropy=2.5232109529528914 */ @Test(timeout = 4000) public void test13() throws Throwable { DefaultNucleotideCodec defaultNucleotideCodec0 = DefaultNucleotideCodec.INSTANCE; byte[] byteArray0 = new byte[3]; Nucleotide nucleotide0 = Nucleotide.Adenine; Set<Nucleotide> set0 = nucleotide0.getBasesFor(); byte[] byteArray1 = defaultNucleotideCodec0.encode((Collection<Nucleotide>) set0); defaultNucleotideCodec0.toString(byteArray1); LinkedList<Nucleotide> linkedList0 = new LinkedList<Nucleotide>(); linkedList0.parallelStream(); DefaultNucleotideCodec defaultNucleotideCodec1 = DefaultNucleotideCodec.INSTANCE; defaultNucleotideCodec1.encode((Collection<Nucleotide>) linkedList0); // Undeclared exception! try { defaultNucleotideCodec0.iterator(byteArray0); fail("Expecting exception: BufferUnderflowException"); } catch(BufferUnderflowException e) { // // no message in exception (getMessage() returned null) // verifyException("java.nio.Buffer", e); } } /** //Test case number: 14 /*Coverage entropy=1.945910149055313 */ @Test(timeout = 4000) public void test14() throws Throwable { DefaultNucleotideCodec defaultNucleotideCodec0 = DefaultNucleotideCodec.INSTANCE; byte[] byteArray0 = new byte[6]; DefaultNucleotideCodec defaultNucleotideCodec1 = DefaultNucleotideCodec.INSTANCE; defaultNucleotideCodec1.decodedLengthOf(byteArray0); Range.of(1L); defaultNucleotideCodec0.decode(byteArray0, 1L); Range.CoordinateSystem range_CoordinateSystem0 = Range.CoordinateSystem.ZERO_BASED; // Undeclared exception! try { Range.parseRange("+", range_CoordinateSystem0); fail("Expecting exception: IllegalArgumentException"); } catch(IllegalArgumentException e) { // // can not parse + into a Range // verifyException("org.jcvi.jillion.core.Range", e); } } /** //Test case number: 15 /*Coverage entropy=2.0431918705451206 */ @Test(timeout = 4000) public void test15() throws Throwable { DefaultNucleotideCodec defaultNucleotideCodec0 = DefaultNucleotideCodec.INSTANCE; byte[] byteArray0 = new byte[8]; int int0 = 6; defaultNucleotideCodec0.getUngappedLength(byteArray0); Range range0 = Range.of((long) 6, 1631L); // Undeclared exception! try { defaultNucleotideCodec0.iterator(byteArray0, range0); fail("Expecting exception: IndexOutOfBoundsException"); } catch(IndexOutOfBoundsException e) { // // range [ 6 .. 1631 ]/0B is out of range of sequence which is only [ 0 .. -1 ]/0B // verifyException("org.jcvi.jillion.core.residue.nt.DefaultNucleotideCodec$IteratorImpl", e); } } /** //Test case number: 16 /*Coverage entropy=1.9730014063936125 */ @Test(timeout = 4000) public void test16() throws Throwable { DefaultNucleotideCodec defaultNucleotideCodec0 = DefaultNucleotideCodec.INSTANCE; byte[] byteArray0 = new byte[6]; byteArray0[0] = (byte)0; DefaultNucleotideCodec defaultNucleotideCodec1 = DefaultNucleotideCodec.INSTANCE; defaultNucleotideCodec1.decodedLengthOf(byteArray0); Range.of(4L); Range range0 = Range.ofLength(0); defaultNucleotideCodec1.iterator(byteArray0, range0); int int0 = defaultNucleotideCodec1.getNumberOfGapsUntil(byteArray0, 2146997901); assertEquals(0, int0); } /** //Test case number: 17 /*Coverage entropy=2.1972245773362196 */ @Test(timeout = 4000) public void test17() throws Throwable { byte[] byteArray0 = new byte[8]; DefaultNucleotideCodec defaultNucleotideCodec0 = DefaultNucleotideCodec.INSTANCE; defaultNucleotideCodec0.decodedLengthOf(byteArray0); DefaultNucleotideCodec defaultNucleotideCodec1 = DefaultNucleotideCodec.INSTANCE; defaultNucleotideCodec1.getGapOffsets(byteArray0); DefaultNucleotideCodec defaultNucleotideCodec2 = DefaultNucleotideCodec.INSTANCE; defaultNucleotideCodec2.getNumberOfGapsUntil(byteArray0, 0); String string0 = defaultNucleotideCodec1.toString(byteArray0); assertEquals("", string0); int int0 = defaultNucleotideCodec1.getNumberOfGapsUntil(byteArray0, 0); assertEquals(0, int0); Nucleotide nucleotide0 = Nucleotide.NotCytosine; byte[] byteArray1 = defaultNucleotideCodec0.encode(nucleotide0); assertArrayEquals(new byte[] {(byte)0, (byte)0, (byte)0, (byte)1, (byte)96}, byteArray1); } /** //Test case number: 18 /*Coverage entropy=2.607805034342705 */ @Test(timeout = 4000) public void test18() throws Throwable { DefaultNucleotideCodec defaultNucleotideCodec0 = DefaultNucleotideCodec.INSTANCE; Nucleotide nucleotide0 = Nucleotide.Amino; Set<Nucleotide> set0 = nucleotide0.getBasesFor(); DefaultNucleotideCodec defaultNucleotideCodec1 = DefaultNucleotideCodec.INSTANCE; byte[] byteArray0 = defaultNucleotideCodec1.encode((Collection<Nucleotide>) set0); defaultNucleotideCodec1.toString(byteArray0); DefaultNucleotideCodec defaultNucleotideCodec2 = DefaultNucleotideCodec.INSTANCE; defaultNucleotideCodec2.iterator(byteArray0); DefaultNucleotideCodec defaultNucleotideCodec3 = DefaultNucleotideCodec.INSTANCE; defaultNucleotideCodec3.getNumberOfGapsUntil(byteArray0, (-622)); DefaultNucleotideCodec defaultNucleotideCodec4 = DefaultNucleotideCodec.INSTANCE; defaultNucleotideCodec4.getNumberOfGapsUntil(byteArray0, 0); // Undeclared exception! try { DefaultNucleotideCodec.valueOf("qtpsJi)]-q"); fail("Expecting exception: IllegalArgumentException"); } catch(IllegalArgumentException e) { // // No enum constant org.jcvi.jillion.core.residue.nt.DefaultNucleotideCodec.qtpsJi)]-q // verifyException("java.lang.Enum", e); } } /** //Test case number: 19 /*Coverage entropy=2.7878762280875935 */ @Test(timeout = 4000) public void test19() throws Throwable { DefaultNucleotideCodec defaultNucleotideCodec0 = DefaultNucleotideCodec.INSTANCE; Nucleotide nucleotide0 = Nucleotide.Gap; Set<Nucleotide> set0 = nucleotide0.getBasesFor(); byte[] byteArray0 = defaultNucleotideCodec0.encode((Collection<Nucleotide>) set0); defaultNucleotideCodec0.toString(byteArray0); defaultNucleotideCodec0.iterator(byteArray0); DefaultNucleotideCodec defaultNucleotideCodec1 = DefaultNucleotideCodec.INSTANCE; defaultNucleotideCodec1.getGapOffsets(byteArray0); DefaultNucleotideCodec defaultNucleotideCodec2 = DefaultNucleotideCodec.INSTANCE; defaultNucleotideCodec2.getNumberOfGapsUntil(byteArray0, 42); DefaultNucleotideCodec defaultNucleotideCodec3 = DefaultNucleotideCodec.INSTANCE; defaultNucleotideCodec3.toString(byteArray0); DefaultNucleotideCodec defaultNucleotideCodec4 = DefaultNucleotideCodec.INSTANCE; defaultNucleotideCodec4.isGap(byteArray0, 42); defaultNucleotideCodec3.getNumberOfGapsUntil(byteArray0, 31); defaultNucleotideCodec1.isGap(byteArray0, 42); byte[] byteArray1 = new byte[1]; byteArray1[0] = (byte)48; // Undeclared exception! try { defaultNucleotideCodec4.getNumberOfGapsUntil(byteArray1, 1); fail("Expecting exception: BufferUnderflowException"); } catch(BufferUnderflowException e) { // // no message in exception (getMessage() returned null) // verifyException("java.nio.Buffer", e); } } /** //Test case number: 20 /*Coverage entropy=2.7886260379670387 */ @Test(timeout = 4000) public void test20() throws Throwable { DefaultNucleotideCodec defaultNucleotideCodec0 = DefaultNucleotideCodec.INSTANCE; Nucleotide nucleotide0 = Nucleotide.Gap; Set<Nucleotide> set0 = nucleotide0.getBasesFor(); byte[] byteArray0 = defaultNucleotideCodec0.encode((Collection<Nucleotide>) set0); defaultNucleotideCodec0.toString(byteArray0); defaultNucleotideCodec0.iterator(byteArray0); DefaultNucleotideCodec defaultNucleotideCodec1 = DefaultNucleotideCodec.INSTANCE; defaultNucleotideCodec1.getGapOffsets(byteArray0); DefaultNucleotideCodec defaultNucleotideCodec2 = DefaultNucleotideCodec.INSTANCE; defaultNucleotideCodec2.getGapOffsets(byteArray0); defaultNucleotideCodec2.getNumberOfGapsUntil(byteArray0, (-541)); DefaultNucleotideCodec defaultNucleotideCodec3 = DefaultNucleotideCodec.INSTANCE; defaultNucleotideCodec1.toString(byteArray0); DefaultNucleotideCodec defaultNucleotideCodec4 = DefaultNucleotideCodec.INSTANCE; defaultNucleotideCodec4.isGap(byteArray0, 0); byte[] byteArray1 = new byte[2]; byteArray1[0] = (byte)14; byteArray1[1] = (byte) (-13); // Undeclared exception! try { defaultNucleotideCodec3.getNumberOfGapsUntil(byteArray1, (-541)); fail("Expecting exception: BufferUnderflowException"); } catch(BufferUnderflowException e) { // // no message in exception (getMessage() returned null) // verifyException("java.nio.Buffer", e); } } /** //Test case number: 21 /*Coverage entropy=2.833213344056216 */ @Test(timeout = 4000) public void test21() throws Throwable { DefaultNucleotideCodec defaultNucleotideCodec0 = DefaultNucleotideCodec.INSTANCE; Nucleotide nucleotide0 = Nucleotide.Strong; Set<Nucleotide> set0 = nucleotide0.getAllPossibleAmbiguities(); byte[] byteArray0 = defaultNucleotideCodec0.encode((Collection<Nucleotide>) set0); defaultNucleotideCodec0.toString(byteArray0); Iterator<Nucleotide> iterator0 = defaultNucleotideCodec0.iterator(byteArray0); DefaultNucleotideCodec defaultNucleotideCodec1 = DefaultNucleotideCodec.INSTANCE; defaultNucleotideCodec0.getGapOffsets(byteArray0); defaultNucleotideCodec1.getNumberOfGapsUntil(byteArray0, 1656); DefaultNucleotideCodec defaultNucleotideCodec2 = DefaultNucleotideCodec.INSTANCE; defaultNucleotideCodec2.toString(byteArray0); defaultNucleotideCodec0.isGap(byteArray0, 1656); defaultNucleotideCodec1.getNumberOfGapsUntil(byteArray0, 4); int int0 = (-2698); // Undeclared exception! try { defaultNucleotideCodec0.encode(4, iterator0); fail("Expecting exception: NoSuchElementException"); } catch(NoSuchElementException e) { // // no more elements // verifyException("org.jcvi.jillion.core.residue.nt.DefaultNucleotideCodec$IteratorImpl", e); } } }
niho/libwave
doc/public/html/search/variables_0.js
<reponame>niho/libwave var searchData= [ ['controleventfifolevel',['controlEventFIFOLevel',['../struct_wave_dev_info.html#a28ddda9b0daeff0f0534ec911249e8ac',1,'WaveDevInfo']]], ['controleventfifounderrun',['controlEventFIFOUnderrun',['../struct_wave_dev_info.html#a4572ca13c1ee4ac268656cc43b89aeed',1,'WaveDevInfo']]] ];
himnay/j2ee-jboss-examples
jpa/src/main/java/com/org/jpa/dao/EmployeeDAO.java
<reponame>himnay/j2ee-jboss-examples package com.org.jpa.dao; import java.util.List; import com.org.jpa.entity.EmployeeEntity; public interface EmployeeDAO { List<EmployeeEntity> getAllEmployees(); List<EmployeeEntity> getAllEmployeesByDeptId(Integer id); EmployeeEntity getEmployeeById(Integer id); boolean addEmployee(EmployeeEntity employee); boolean removeEmployee(EmployeeEntity employee); boolean removeAllEmployees(); }
ozoneplatform/owf-framework-patch
javascript/src/components/dashboard/DashboardContainer.js
Ext.define('Ozone.components.dashboard.DashboardContainer', { extend: 'Ext.panel.Panel', alias: ['widget.dashboardContainer', 'widget.Ozone.components.dashboard.DashboardContainer'], plugins: new Ozone.plugins.DashboardContainer(), activeDashboard: null, previousActiveDashboard: null, dashboardMenuItems: null, dashboardStore: null, widgetStore: null, dashboards: null, autoSaveEnabled: true, layout: 'fit', refreshUrl: window.location, // current user user: null, // the number of milliseconds to wait between checks to determine if a save is needed // 900000 = 15 minutes pollingInterval: Ozone.config.autoSaveInterval ? Ozone.config.autoSaveInterval : 900000, suppressLockWarning: false, // ZIndexManagers for the various z-index levels, must be instantiated in // index.gsp so the tooltipManager can be used and still be created last floatingWidgetManager: null, bannerManager: null, dashboardDesignerManager: null, modalWindowManager: null, tooltipManager: null, //if set to true when the dashboard switcher is opened, the //dashboards will refresh before the switcher opens dashboardsNeedRefresh: false, // state of app component menu appComponentsViewState: null, MY_APPS_WINDOW_ID: 'my-apps-window', // private initComponent: function() { var me = this; this.loadMask = Ext.create('Ozone.components.mask.LoadMask', Ext.getBody(), { zIndexManager: this.modalWindowManager }); this.reloadStacks(); this.originalDashboardStore = Ext.create('Ozone.data.DashboardStore', {}); this.dashboardMenuItems = []; this.dashboards = []; // eventing configuration this.initEventing(); OWF.Container = OWF.Container || {}; OWF.Container.Eventing = Ozone.eventing.Container; // initialize widget launcher OWF.Container.Launcher = new Ozone.launcher.WidgetLauncherContainer(OWF.Container.Eventing); this.addWidgetContainer = new Ozone.marketplace.AddWidgetContainer(OWF.Container.Eventing, this); OWF.Container.DragAndDrop = new Ozone.dragAndDrop.WidgetDragAndDropContainer({ eventingContainer: OWF.Container.Eventing }); OWF.Container.DragAndDrop.addCallback('dragStart', Ext.bind(function(data) { Ext.getCmp(this.activeDashboard.id).fireEvent('widgetStartDrag', data); }, this)); OWF.Container.DragAndDrop.addCallback('dragStop', Ext.bind(function(data) { Ext.getCmp(this.activeDashboard.id).fireEvent('widgetStopDrag', data); }, this)); //initialize widgetchrome api OWF.Container.Chrome = new Ozone.chrome.WidgetChromeContainer({ eventingContainer: OWF.Container.Eventing }); // initialize widget state event container for receiving events OWF.Container.State = new Ozone.state.WidgetStateContainer(OWF.Container.Eventing); this.user = Ozone.config.user; this.widgetStore.on('datachanged', this.updateTitlesandBanner, this); //setup component properties Ext.apply(this, { layout: { type: 'vbox', align: 'stretch' }, items: [ //putting the banner as an actual child component because there are window contraining issues if the //banner is an actual docked toolbar { itemId: 'owfbanner', xtype: 'owfbanner', user: this.user, dashboardContainer: this }, { id: 'dashboardCardPanel', itemId: 'dashboardCardPanel', xtype: 'panel', flex: 1, layout: { type: 'dashboardbufferedcard' }, cls: 'usableCentralRegion', listeners: { afterlayout: { fn: function(cmp) { cmp.isLayedOut = true; }, scope: this, single: true } }, items: [] } ] }); //call super init this.callParent(arguments); //start autosaving after layout is complete this.on('afterlayout', this.startAutoSave, this, { single: true }); this.onBeforeUnload = function(evt) { if (this.activeDashboard != null) { Ext.getCmp(this.activeDashboard.id).saveToServer(true, true); } if(this.appComponentsView) { this.appComponentsView.save(true); } //tell History to shutdown cleanly because the browser is leaving OWFs if (!this.shareButtonClicked) { Ext.History.shutDown(); } else { this.shareButtonClicked = false; } }; //setup save on unload Ext.EventManager.on(window, 'beforeunload', this.onBeforeUnload, this); this.addKeyBindings(); this.addEvents({ dashboardChanged: true }); // delegate all mousedown to document // enables moving widgets from one pane to another Ext.getDoc().on('mousedown', this.onWidgetMouseDown, this, { delegate: '.widgetheader' }); this.updateTitlesandBanner(); this.initLoad(); this.setupDashboardChangeListeners(); OWF.Collections.AppComponents.on('remove', this.removeAppComponent, this); this.setupUserListingCheckService(); $(window).on('resize', function () { if(me.appComponentsView && me.appComponentsView.isHidden()) { me._refreshAppComponent = true; } }); }, reloadStacks: function() { var model, dashboard, stack; var stackModels = {}; this.stackStore = Ext.create('Ozone.data.StackStore', {}); for (var i = 0, len = this.dashboardStore.getCount(); i < len; i++) { model = this.dashboardStore.getAt(i); dashboard = model.data; stack = dashboard.stack; if (stack) { if (stackModels[stack.id]) { stackModels[stack.id].get('dashboards').push(model); } else { var stackModel = this.stackStore.add(stack)[0]; // Set phantom to 'false' to overcome a quirk of ExtJS, which considers models with id of 0 // to be new (phantom = true). stackModel.phantom = false; stackModel.set('dashboards', [model]); stackModels[stack.id] = stackModel; } } } }, onWidgetMouseDown: function(evt, target) { var widgetEl, widgetId, targetEl, widget; if (evt.getTarget().nodeName === "IMG") { return; } // if only one pane, don't enable drag n drop // if (this.activeDashboard.query('pane').length === 1) { // return; // } targetEl = Ext.get(target); widgetEl = targetEl.up('.x-closable'); widgetId = widgetEl ? widgetEl.dom.id : target.id; // cache widget to move and src pane guid to use later widget = Ext.getCmp(widgetId); widget = widget.card || widget; //Return if not a widget or is floating if (!widget.isWidget || widget.floatingWidget || this.activeDashboard.panes.length === 1) { return; } Ext.getDoc().on('mousemove', this.onMouseMove, this); Ext.getDoc().on('mouseup', this.onMouseUp, this); this._widgetToMove = widget; this._sourcePane = this._widgetToMove.pane; this._paneWidgets = []; this._paneWidgetsBox = []; var widget, widgetBox; var sourcePaneWidgets = this._sourcePane.getWidgets(), body = Ext.getBody(); for (var pos = 0, len = sourcePaneWidgets.length; pos < len; pos++) { widget = sourcePaneWidgets[pos]; widget._position = pos; this._paneWidgets.push(widget); widgetBox = widget.tab ? widget.tab.getBox() : widget.getBox(); widgetBox.midpoint = widget.tab ? widgetBox.x + (widgetBox.width / 2) : widgetBox.y + (widgetBox.height / 2); this._paneWidgetsBox.push(widgetBox); } }, onMouseMove: function(evt, target) { var xy = evt.getXY(), targetPane = Ext.get(target).up('.pane'), isFloating = this._widgetToMove.isFloating(); this._reorderingWidgets = false; if (this._counter) { this.ddProxy.el.setStyle({ 'left': (xy[0] + 25) + 'px', 'top': (xy[1] + 25) + 'px' }); if (this.activeDashboard.configRecord.get("locked")) { this.ddProxy.setStatus(this.ddProxy.dropNotAllowed); } else { this.ddProxy.setStatus(targetPane ? this.ddProxy.dropAllowed : this.ddProxy.dropNotAllowed); } if (targetPane && this._sourcePane.el === targetPane) { if (isFloating) { // hide proxy for floating widgets this.ddProxy.hide(); } else { // allow reordering via drag and drop this.ddProxy.show(); this._reorderingWidgets = true; var widgetBox, overWidget; var match = false, eventPageX = xy[0], eventPageY = xy[1]; for (var pos = 0, len = this._paneWidgets.length; pos < len; pos++) { overWidget = this._paneWidgets[pos]; widgetBox = this._paneWidgetsBox[pos]; if (overWidget.tab) { if (widgetBox.x < eventPageX && ((widgetBox.x + widgetBox.width) > eventPageX)) { match = true; break; } } else { if (widgetBox.y < eventPageY && ((widgetBox.y + widgetBox.height) > eventPageY)) { match = true; break; } } } pos = (match && overWidget ? pos : this._paneWidgets.length); if (this._lastDropIndicatedWidget) { this._lastDropIndicatedWidget.el.removeCls.call( this._lastDropIndicatedWidget.tab ? this._lastDropIndicatedWidget.tab.el : this._lastDropIndicatedWidget.el, ['indicate-drop-before', 'indicate-drop-after']); } if (pos === this._widgetToMove._position) { // dont move as the widget hasn't been moved this.ddProxy.setStatus(this.ddProxy.dropNotAllowed); } else if (match) { this._lastDropIndicatedWidget = this._paneWidgets[pos]; // var oldPos = pos; var clsToAdd; if ((overWidget.tab && widgetBox.midpoint > eventPageX) || (!overWidget.tab && widgetBox.midpoint > eventPageY)) { //pos = pos === 0 ? 0 : pos - 1; clsToAdd = 'indicate-drop-before'; } else { pos = pos + 1; clsToAdd = 'indicate-drop-after'; } this._lastDropIndicatedWidget.el.addCls.call( this._lastDropIndicatedWidget.tab ? this._lastDropIndicatedWidget.tab.el : this._lastDropIndicatedWidget.el, clsToAdd); this._movePosition = pos; // if(overWidget.tab) // console.log(widgetBox.midpoint > eventPageX ? 'before' : 'after', pos, oldPos); // else // console.log(widgetBox.midpoint > eventPageY ? 'before' : 'after', pos, oldPos); } } } else { this.ddProxy.show(); } } else { this._counter = 1; this.ddProxy = this.ddProxy || Ext.create('Ext.dd.StatusProxy', { shadow: false }); this.ddProxy.update('<img src="' + this._widgetToMove.model.get('image') + '" class="widget-drag-proxy"/>'); //TODO: investigate why I have to call show, hide and show this.ddProxy.show(); this.ddProxy.hide(); this.activeDashboard.enableWidgetMove(targetPane, true); } }, onMouseUp: function(evt, target) { var targetPaneEl; if (this._lastDropIndicatedWidget) { this._lastDropIndicatedWidget.el.removeCls.call( this._lastDropIndicatedWidget.tab ? this._lastDropIndicatedWidget.tab.el : this._lastDropIndicatedWidget.el, ['indicate-drop-before', 'indicate-drop-after']); } Ext.getDoc().un('mousemove', this.onMouseMove, this); Ext.getDoc().un('mouseup', this.onMouseUp, this); if (this._movePosition && this._widgetToMove._position < this._movePosition) this._movePosition -= 1; if (this._reorderingWidgets && this._movePosition !== undefined && this._movePosition !== this._widgetToMove._position) { this._sourcePane.reorderWidget(this._widgetToMove, this._movePosition); } else if (this._widgetToMove && (targetPaneEl = Ext.fly(target).up('.pane'))) { this.activeDashboard.moveWidgetToPane(evt, Ext.getCmp(this._widgetToMove.paneGuid), Ext.getCmp(targetPaneEl.dom.id), this._widgetToMove); } this.activeDashboard.disableWidgetMove(); this.ddProxy && this.ddProxy.hide(); delete this._counter; delete this._movePosition; delete this._widgetToMove; delete this._lastDropIndicatedWidget; delete this._sourcePane; delete this._paneWidgets; delete this._paneWidgetsBox; }, showWidgetDragProxy: function (evt, widgetModel) { if(!evt) { return; } var template = Handlebars.compile( '<div class="widget">' + '<div class="thumb-wrap">' + '<img onerror="this.src="themes/common/images/settings/WidgetsIcon.png"" src="{{image}}" class="thumb">' + '</div>' + '<div class="thumb-text ellipsis" style="word-wrap: break-word;">{{name}}</div>' + '</div>' ); var $document = $(document), $dragProxy = $(template(widgetModel.attributes)); function updateProxy (evt) { var pageX, pageY; pageX = evt instanceof Ext.EventObjectImpl ? evt.getPageX() : evt.pageX; pageY = evt instanceof Ext.EventObjectImpl ? evt.getPageY() : evt.pageY; $dragProxy.css({ 'z-index': 10000000, 'position': 'absolute', 'left': (pageX + 25) + 'px', 'top': (pageY + 25) + 'px' }); return $dragProxy; } $document .on('mousemove.dragProxy', updateProxy) .on('mouseup.dragProxy', function () { $dragProxy.remove(); $document.off('dragProxy'); }); $('body').append(updateProxy(evt)); }, /* * Launches widget on the current dashboard. */ launchWidgets: function(evt, widgetModel, isEnterPressed, isDragAndDrop) { var me = this; if(!isDragAndDrop && this.activeDashboard.panes.length > 1) { this.showWidgetDragProxy(evt, widgetModel); } return me.selectPane(isEnterPressed, isDragAndDrop).then(function(pane, e) { me.activeDashboard.launchWidgets(pane, null, e, { widgetModel: widgetModel }); }, function() { var launchMenu = Ext.getCmp('widget-launcher'); if (launchMenu) { launchMenu.fireEvent('noWidgetLaunched'); } }); }, /* * Launches widget on a dashboard that user selects from Dashboard Switcher. */ selectDashboardAndLaunchWidgets: function(evt, widgetModel, isEnterPressed) { var me = this; // Display dashboard switcher and launch widgets after the user selects a dashboard var dashboardSelectionPromise = me.selectDashboard(); dashboardSelectionPromise.done(function(evt, dashboardId) { me.launchWidgets(evt, widgetModel, isEnterPressed); }); // Show a notification with instructions for selecting a dashboard $.pnotify({ title: Ozone.layout.DialogMessages.launchWidgetTitle, text: Ozone.layout.DialogMessages.launchWidgetAlert, type: 'success', addclass: "stack-bottomright", stack: { "dir1": "up", "dir2": "left", "firstpos1": 25, "firstpos2": 25 }, history: false, sticker: false, icon: false }); }, /* * Selects a Pane from the active dashboard. * * Returns: a promise object that will be resolved with * event and pane selected */ selectPane: function(isUsingKeyboard, isDragAndDrop) { var me = this, deferred = jQuery.Deferred(), panes = this.activeDashboard.panes, doc = Ext.getDoc(); // if one pane resolve right away only if not performing drag and drop if (panes.length === 1 && !isDragAndDrop) { deferred.resolve(panes[0]); } else { this.activeDashboard.enableWidgetMove(isUsingKeyboard === true && panes[0], isDragAndDrop); doc.on('keydown', this._selectPaneOnKeyDown, this, { capture: true, deferred: deferred }); this.el.on('click', this._selectPaneOnClick, this, { deferred: deferred }); this.el.on('mouseup', this._selectPaneOnClick, this, { deferred: deferred }); // cleanup listeners when deferred is either resolved or rejected deferred.always(function() { me.activeDashboard.disableWidgetMove(); doc.un('keydown', me._selectPaneOnKeyDown, me, { capture: true }); me.el.un('click', me._selectPaneOnClick, me); me.el.un('mouseup', me._selectPaneOnClick, me); }); } return deferred.promise(); }, /* * Manages pane selection using keyboard. * Resolves deferred when Enter key is pressed and * rejects when Esc is pressed */ _selectPaneOnKeyDown: function(e, dom, eOpts) { var panes = this.activeDashboard.panes, key = e.getKey(), lastPaneIndex = panes.length - 1, nextPaneIndex; // prevent from bubbling down e.stopEvent(); this._previousPaneIndex = this._previousPaneIndex || 0; if (key === Ext.EventObject.TAB) { if (e.shiftKey) { //Go back a pane if (this._previousPaneIndex === 0) { nextPaneIndex = lastPaneIndex; } else { nextPaneIndex = this._previousPaneIndex - 1; } } else { //Go forward a pane if (this._previousPaneIndex === lastPaneIndex) { nextPaneIndex = 0; } else { nextPaneIndex = this._previousPaneIndex + 1; } } panes[this._previousPaneIndex].blur(); panes[nextPaneIndex].focus(); this._previousPaneIndex = nextPaneIndex; } else if (key === Ext.EventObject.ENTER) { eOpts.deferred.resolve(panes[this._previousPaneIndex], e); delete this._previousPaneIndex; } //Enable ESC to cancel else if (key === Ext.EventObject.ESC) { eOpts.deferred.reject(); } }, /* * Manages pane selection using mouse. */ _selectPaneOnClick: function(e, dom, eOpts) { var paneEl = Ext.get(dom).up('.pane'), deferred = eOpts.deferred; if (paneEl) { deferred.resolve(Ext.getCmp(paneEl.id), e); } else { deferred.reject(); } }, initLoad: function() { var me = this; var records = me.widgetStore.getRange(); //see if the dashboard guid was specified on the hash var hashData = Ext.util.History.getToken(); var data = hashData ? Ext.urlDecode(hashData) : {}; var activeDashboardGuid = data.guid; var stackDashboards = []; var stackContext = data.stack; if (me.dashboardStore.getCount() > 0) { for (var i = 0, len = me.dashboardStore.getCount(); i < len; i++) { var dashRecord = me.dashboardStore.getAt(i); var dash = dashRecord.data; me.dashboards.push(me.createDashboardConfig(dashRecord)); me.originalDashboardStore.add(Ext.JSON.decode(Ext.JSON.encode(dashRecord.data))); // Build an array of dashboards that are in the supplied stack context if (stackContext && dashRecord.data.stack && dashRecord.data.stack.stackContext == stackContext) { stackDashboards.push(me.createDashboardConfig(dashRecord)); } if (activeDashboardGuid != null) { if (dash.guid == activeDashboardGuid) { me.activeDashboard = me.dashboards[me.dashboards.length - 1]; } } if (dash.isdefault) { me.defaultDashboard = me.dashboards[me.dashboards.length - 1]; } } } if ((me.dashboards.length === 1 && me.dashboards[0].config.type === "marketplace") || me.dashboards.length === 0) { me.createEmptyDashboard('desktop', true, Ext.bind(function (record, dashboard) { continueInitLoad(dashboard); }, me)); return; } // Set active dashboard if (me.activeDashboard == null) { // Couldn't find a dashboard based on guid if (stackDashboards.length > 0) { // If a stack context was supplied, set active dashboard to first dashboard in stack me.activeDashboard = stackDashboards[0]; if (me.defaultDashboard) { // If a default dashboard exists and is part of the stack, activate that one for (var i = 0; i < stackDashboards.length; i++) { if (me.defaultDashboard.guid == stackDashboards[i].guid) { me.activeDashboard = stackDashboards[i]; break; } } } continueInitLoad(me.activeDashboard); } else { if (me.defaultDashboard != null) { // Otherwise, set active dashboard to default dashboard continueInitLoad(me.defaultDashboard); } else { if (me.dashboards.length > 0) { // Otherwise, just pick the first dash continueInitLoad(me.dashboards[0]); } else { // And if all else fails, create a new active dashboard me.createEmptyDashboard('desktop', true, Ext.bind(function (dash) { var dashModel = me.createDashboardConfig(Ext.create('Ozone.data.Dashboard', dash)); me.dashboards = [dashModel]; continueInitLoad(dashModel); }, me)); } } } } else { continueInitLoad(me.activeDashboard); } /** * The second half of initLoad. This is a separate function so that it can * execute asynchronously in the case that no dashboard exists and one needs to be created * and saved */ function continueInitLoad(dash) { var currentUrlGuid; //OP-2174 - Fixes a problem where browser URL and activeDashboard guids don't match // TODO: Rewrite dashboard switcher so this can't happen if (Ext.util.History.getHash()) { currentUrlGuid = Ext.urlDecode(Ext.util.History.getHash()).guid; if (me.activeDashboard && currentUrlGuid === me.activeDashboard.guid) { me.defaultDashboard = dash; } else { me.defaultDashboard = me.activeDashboard = dash; } } else { me.defaultDashboard = me.activeDashboard = dash; } Ext.state.Manager.setProvider(Ext.create('Ozone.state.WidgetStateStoreProvider', { store: me.activeDashboard ? me.activeDashboard.stateStore : null })); //attach listener to change dashboard on # change Ext.util.History.on('change', function(hashData) { if (hashData != null) { var data = Ext.urlDecode(hashData); if (data.guid != null && data.guid != 'notFound') { me._activateDashboard(data.guid, data.stack); } else if (data.guid == 'notFound') { //guid was bad me._activateDashboard(null, data.stack); } else { //no data specified on the hash -- pass empty string me._activateDashboard('', data.stack); } } else { //goto the default dashboard me._activateDashboard(me.defaultDashboard.guid, data.stack); } }); var dashboardCardPanel = me.getComponent('dashboardCardPanel'); me.toggleMarketplaceMenuOnDashboardSwitch(me.activeDashboard); var setupInitialDash = Ext.bind(function() { dashboardCardPanel.activeItem = me.activeDashboard.id; dashboardCardPanel.add(me.dashboards); me.activeDashboard = dashboardCardPanel.getComponent(me.activeDashboard.id); // add to buffer to keep removal consistent to respect cardBufferSize set dashboardCardPanel.layout.cardBuffer.add(me.activeDashboard); me.activateDashboard(me.activeDashboard.id, true, me.activeDashboard.stackContext); if (me.activeDashboard.configRecord.get('locked') || me.activeDashboard.configRecord.isMarketplaceDashboard()) { me.getBanner().disableAppComponentsBtn(); me.getBanner().getUserMenuBtn().disableAdminMenuItem(); me.getBanner().getUserMenuBtn().disableMetricsMenuItem(); } else { me.getBanner().enableAppComponentsBtn(); me.getBanner().getUserMenuBtn().enableAdminMenuItem(); me.getBanner().getUserMenuBtn().enableMetricsMenuItem(); } if (me.activeDashboard.configRecord.isMarketplaceDashboard()) { me.getBanner().setMarketplaceToggle(); } }); if (dashboardCardPanel.isLayedOut) { //in case there are already some dashboards in there dashboardCardPanel.removeAll(); setupInitialDash(); } else { dashboardCardPanel.on({ afterlayout: { fn: function() { setupInitialDash(); }, scope: me, single: true } }); } } }, //add global key bindings here instead of in initComponent addKeyBindings: function() { Ext.FocusManager.disable(); Ozone.KeyMap.addBinding([ Ext.apply(Ozone.components.keys.HotKeys.WIDGET_SWITCHER, { scope: this, fn: this.showWidgetSwitcher }), Ext.apply(Ozone.components.keys.HotKeys.CLOSE_WIDGET, { scope: this, fn: this.closeWidget }), Ext.apply(Ozone.components.keys.HotKeys.MAXIMIZE_COLLAPSE_WIDGET, { scope: this, fn: this.maximizeCollapseWidget }), Ext.apply(Ozone.components.keys.HotKeys.MINIMIZE_EXPAND_WIDGET, { scope: this, fn: this.minimizeExpandWidget }), Ext.apply(Ozone.components.keys.HotKeys.ESCAPE_FOCUS, { scope: this, fn: this.esc }), Ext.apply(Ozone.components.keys.MoveHotKeys.MOVE_UP, { scope: this, alt: false, fn: this.saveWidgetState }), Ext.apply(Ozone.components.keys.MoveHotKeys.MOVE_RIGHT, { scope: this, alt: false, fn: this.saveWidgetState }), Ext.apply(Ozone.components.keys.MoveHotKeys.MOVE_DOWN, { scope: this, alt: false, fn: this.saveWidgetState }), Ext.apply(Ozone.components.keys.MoveHotKeys.MOVE_LEFT, { scope: this, alt: false, fn: this.saveWidgetState }) ]); // map move hot keys for widgets Ozone.MoveKeyMap.addBinding([ Ext.apply(Ozone.components.keys.MoveHotKeys.MOVE_UP, { scope: this, fn: function(key, event, widgetInstanceId) { this.activeDashboard.moveWidgetUp(widgetInstanceId); } }), Ext.apply(Ozone.components.keys.MoveHotKeys.MOVE_RIGHT, { scope: this, fn: function(key, event, widgetInstanceId) { this.activeDashboard.moveWidgetRight(widgetInstanceId); } }), Ext.apply(Ozone.components.keys.MoveHotKeys.MOVE_DOWN, { scope: this, fn: function(key, event, widgetInstanceId) { this.activeDashboard.moveWidgetDown(widgetInstanceId); } }), Ext.apply(Ozone.components.keys.MoveHotKeys.MOVE_LEFT, { scope: this, fn: function(key, event, widgetInstanceId) { this.activeDashboard.moveWidgetLeft(widgetInstanceId); } }) ]); }, showWidgetSwitcher: function() { var widgetSwitcherId = 'widget-switcher', widgetSwitcher = Ext.getCmp(widgetSwitcherId); if (!widgetSwitcher) { widgetSwitcher = Ext.widget('widgetswitcher', { id: widgetSwitcherId, dashboardContainer: this, activeDashboard: this.activeDashboard, widgetStore: this.widgetStore, plugins: new Ozone.components.keys.HotKeyComponent(Ozone.components.keys.HotKeys.WIDGET_SWITCHER) }); } else if (widgetSwitcher.isVisible()) { widgetSwitcher.close(); return; } widgetSwitcher.show(); widgetSwitcher.activeDashboard = this.activeDashboard; widgetSwitcher.setStore(this.activeDashboard.stateStore); widgetSwitcher.center(); }, refreshAppComponentsView: function () { var me = this; var search_params = { limitParam: undefined, pageParam: undefined, startParam: undefined }; return $.ajax('person/me').then(function (person) { if(me.appComponentsView) { var isVisible = me.appComponentsView.$el.is(':visible'); // cache current state me.appComponentsViewState.preference = me.appComponentsView.getState(); // remove me.appComponentsView.hide().remove(); me.appComponentsView = null; // show if it was visible before removal isVisible && me.showAppComponentsView(); } // update Ext Store me.widgetStore.loadRecords(me.widgetStore.proxy.reader.read(person.widgets).records); return person; }); }, showAppComponentsView: function () { var me = this, appComponentsBtn, state; if (me.activeDashboard.configRecord.get('locked') === true || me.activeDashboard.configRecord.isMarketplaceDashboard()) { return; } if(!me.appComponentsView) { state = _.isString(this.appComponentsViewState.preference) ? Ozone.util.parseJson(this.appComponentsViewState.preference) : this.appComponentsViewState.preference; me.appComponentsView = new Ozone.components.appcomponents.AppComponentsView({ collection: OWF.Collections.AppComponents, dashboardContainer: me, state: state }); appComponentsBtn = me.getBanner().getComponent('appComponentsBtn'); me.appComponentsView.$el.on('hide.toggle', function () { appComponentsBtn.toggle(false, true); }); me.appComponentsView.$el.on('show.toggle', function () { appComponentsBtn.toggle(true, true); }); $('#dashboardCardPanel').append(me.appComponentsView.render().el); me.appComponentsView.show().shown(); } else { me.appComponentsView.toggle(); if(me._refreshAppComponent) { me._refreshAppComponent = false; me.appComponentsView.refresh(); } } }, hideAppComponentsView: function () { if(this.appComponentsView) { this.appComponentsView.hide(); } }, showMyAppsWindowButtonHandler: function() { return this.showMyAppsWind(false); }, showMyAppsWindToSelectForWidgetLaunch: function() { return this.showMyAppsWind(true, { title: '<strong>Click the App</strong> where you want the App Component to start' }).done(function (myAppsWindow) { var $el = $(myAppsWindow.body.dom); $el.children('.my-apps-window-descriptor').css('visibility', 'hidden'); $el.children('.actions').css('visibility', 'hidden'); }); }, showMyAppsWind: function(hideLockedDashboards, options) { var me = this, myAppsWindowId = this.MY_APPS_WINDOW_ID, myAppsWindow = Ext.getCmp(myAppsWindowId), myAppsWindowDeferred = $.Deferred(), //perform the logic of actually creating and displaying the window show = function() { // OP-1355 // Re-render dashboard switcher and its elements // in case locked dashboards have to be hidden if (myAppsWindow) { myAppsWindow.destroy(); } myAppsWindow = Ext.widget('myappswindow', _.extend({}, options, { id: myAppsWindowId, dashboardContainer: me, activeDashboard: me.activeDashboard, dashboardStore: me.dashboardStore, hideLockedDashboards: hideLockedDashboards, plugins: new Ozone.components.keys.HotKeyComponent(Ozone.components.keys.HotKeys.DASHBOARD_SWITCHER) })); myAppsWindow.activeDashboard = me.activeDashboard; myAppsWindow.show().center(); myAppsWindowDeferred.resolve(myAppsWindow); me.loadMask.hide(); }; if(this.appComponentsView) { this.appComponentsView.hide(); } // If it already is open, close it if (myAppsWindow && myAppsWindow.isVisible()) { myAppsWindow.close(); } else { me.loadMask.show(); //making this asynchronous helps the loading mask appear in a timely //manner in IE setTimeout(function() { // force dashboard save before showing dashboard switcher me.activeDashboard.saveToServer(false, true, false, function(){ //if necessary, refresh the dashboards before calling show if (me.dashboardsNeedRefresh) { if (myAppsWindow) { myAppsWindow.destroy(); myAppsWindow = null; } me.dashboardsNeedRefresh = false; me.reloadDashboards(show); } else { show(); } }); }, 0); } return myAppsWindowDeferred.promise(); }, destroyMyAppsWindow: function() { var myAppsWindowId = this.MY_APPS_WINDOW_ID, myAppsWindow = Ext.getCmp(myAppsWindowId); myAppsWindow && myAppsWindow.destroy(); }, // Displays dashboard switcher and returns a promise which is resolved only after the user selects a dashboard // and it is activated. selectDashboard: function() { var me = this, dashboardActivatedDeferred = $.Deferred(); // Show the switcher var myAppsWindowPromise = this.showMyAppsWindToSelectForWidgetLaunch(); myAppsWindowPromise.done(function(myAppsWindow) { // Dashboard selection promise will resolve if a dashboard is selected in a switcher var dashboardSelectionPromise = myAppsWindow.getDashboardSelectionPromise(); dashboardSelectionPromise.done(function(evt, dashboardGuid) { if (me.activeDashboard.guid === dashboardGuid) { // The user selected the same dashboard dashboardActivatedDeferred.resolve(evt, dashboardGuid); } else { // The user selected different dashboard, wait for it becoming active me.addListener(OWF.Events.Dashboard.CHANGED, function() { dashboardActivatedDeferred.resolve(evt, dashboardGuid); }) } }) }); return dashboardActivatedDeferred.promise(); }, createDashboardConfig: function(dashRecord) { var dash = dashRecord.data; var stateStore = Ext.create('Ozone.data.StateStore', { storeId: dash.guid, data: [] }); // if (typeof dash.defaultSettings === "string" && !Ext.isEmpty(dash.defaultSettings)) { // dash.defaultSettings = Ext.JSON.decode(dash.defaultSettings); // } // //we always want this to be defaulted to an empty object if it is null or an empty string // if (dash.defaultSettings == null || dash.defaultSettings == "") { // dash.defaultSettings = {}; // } return { id: dash.guid, itemId: dash.guid, guid: dash.guid, xtype: 'dashboard', config: dash, configRecord: dashRecord, // defaultSettings: dash.defaultSettings, widgetStore: this.widgetStore, stateStore: stateStore, eventingContainer: OWF.Container.Eventing, widgetLauncher: OWF.Container.Launcher, addWidgetContainer: this.addWidgetContainer, widgetStateContainer: OWF.Container.State, widgetDragAndDrop: OWF.Container.DragAndDrop, dashboardContainer: this, viewportId: this.viewportId, name: dash.name, userId: this.user.id, userName: this.user.displayName, stackContext: dash.stack ? dash.stack.stackContext : null }; }, activateDashboard: function(guid, silent, stackContext, forceActivation) { if(this.activeDashboard.guid != guid || forceActivation) { //set dashboard in history but disable events so we don't activate the dashboard twice var params = {}; if (stackContext) { params.stack = stackContext; } params.guid = guid; if (silent) { Ext.util.History.shutDown(); } Ext.util.History.add(Ext.urlEncode(params)); if (silent) { Ext.util.History.startUp(); } this.fireEvent(OWF.Events.Dashboard.SELECTED, guid); } }, /** * * Activates previously selected dashboard. * **/ activatePreviousDashboard: function() { var guid, stack, previousActiveDashboardModel; if (this.previousActiveDashboard && this.previousActiveDashboard !== this.activeDashboard) { previousActiveDashboardModel = this.previousActiveDashboard.configRecord; } else { // Sort in descending order by edited date // Sort on array to prevent store positions from being udpated var sortedDashboards = Ext.Array.sort(Ext.Array.pluck(this.dashboardStore.data.items, 'data'), function(a, b) { return ((new Date(b.editedDate).getTime()) - (new Date(a.editedDate).getTime())); }); // If more than 1 dashboards are found, verify that we dont select the same dashboard to activate if (sortedDashboards.length >= 2) { if (sortedDashboards[0].guid === this.activeDashboard.guid) { guid = sortedDashboards[1].guid; } else { guid = sortedDashboards[0].guid; } previousActiveDashboardModel = this.dashboardStore.getById(guid); } } if (previousActiveDashboardModel) { stack = previousActiveDashboardModel.get('stack'); guid = previousActiveDashboardModel.get('guid'); this.activateDashboard(guid, false, stack ? stack.stackContext : null); return true; } else { return false; } }, //this function is private, do not call outside of this class - use activateDashboard instead _activateDashboard: function(guid, stackContext) { var dashboardCardPanel = this.getDashboardCardPanel(); if (!dashboardCardPanel) { return; } this.previousActiveDashboard = dashboardCardPanel.layout.getActiveItem(); if (guid && guid !== '') { //make the new dashboard active and visible var dashboardPanel = dashboardCardPanel.layout.setActiveItem(guid); if (dashboardPanel) { //save a reference this.activeDashboard = dashboardPanel; this.toggleMarketplaceMenuOnDashboardSwitch(this.activeDashboard); // OP-772: blur iframe when switching dashboards. // Blur the focused element. // Only this approach worked; bluring the active iframe directly didn't. var activeEl = document.activeElement; // OP-1056: use small delay to avoid IE7/9 issue where browser is sent to the background if (activeEl) { if (activeEl.nodeName.toLowerCase() != 'body') { setTimeout(function() { activeEl.blur(); }, 1); } else { setTimeout(function() { $("input:focus, textarea:focus, select:focus").blur(); }, 1); } } if (dashboardPanel.cssanimations) { dashboardPanel.on(OWF.Events.Dashboard.SHOWN, function() { var me = this; setTimeout(function () { me.fireEvent(OWF.Events.Dashboard.CHANGED, guid, dashboardPanel, me.previousActiveDashboard); }, 0); }, this, { single: true }) } else { this.fireEvent(OWF.Events.Dashboard.CHANGED, guid, dashboardPanel, this.previousActiveDashboard); } this.setDefaultDashboard(guid); } } else { var params = {}; if (stackContext) { params.stack = stackContext; var stackDashGuids = []; if (this.dashboardStore.getCount() > 0) { for (var i = 0, len = this.dashboardStore.getCount(); i < len; i++) { var dashRecord = this.dashboardStore.getAt(i); // Build an array of dashboard guids that are in the supplied stack context if (stackContext && dashRecord.data.stack && dashRecord.data.stack.stackContext == stackContext) { stackDashGuids.push(dashRecord.data.guid); } } } if (stackDashGuids.length > 0) { // If a stack context was supplied, set active dashboard to first dashboard in stack params.guid = stackDashGuids[0]; if (this.defaultDashboard) { // If a default dashboard exists and is part of the stack, activate that one for (var i = 0; i < stackDashGuids.length; i++) { if (this.defaultDashboard.guid == stackDashGuids[i]) { params.guid = stackDashGuids[i]; break; } } } } } if (!params.guid) { if (guid == '') { //no guid specified set to default params.guid = this.defaultDashboard.guid; } else { params.guid = this.activeDashboard.guid; //todo remove this defer when there are events on dashboards Ext.defer(Ozone.Msg.alert, 100, this, [Ozone.util.ErrorMessageString.invalidDashboard, this.activeDashboard.isdefault ? Ozone.util.ErrorMessageString.invalidDashboardMsg : Ozone.util.ErrorMessageString.invalidDashboardGotoDefaultMsg, null, null, null, this.modalWindowManager ]); } } if (params.guid) { Ext.util.History.add(Ext.urlEncode(params)); } } }, getBanner: function() { return this.getComponent('owfbanner'); }, getDashboardCardPanel: function() { return this.getComponent('dashboardCardPanel'); }, /* * the escape key has dual functionality. * From within a widget, it escapes the widget. * From within the container, it blurs * in order to reset the focus to the beginning */ esc: function(key, evt, guid) { if (evt.fromWidget) { this.unfocusWidget(key, evt, guid); } else { this.getBanner().focus(); } }, unfocusWidget: function(key, event, guid) { var widget = Ext.getCmp(guid), header; if (widget) { header = widget.tab ? widget.tab.header : widget.header; if (header) { header.titleCmp.focus(); } else { this.getBanner().focus(); } } }, openDashboardMgr: function() { var winId = "user-manage-dashboards"; var win = Ext.getCmp(winId); if (win) { win.show(); return; } Ext.create('Ozone.components.window.DashboardsManager', { ownerCt: this, dashboardContainer: this, id: winId, itemId: winId, modal: true, border: false, bodyBorder: false }).show(); }, showCreateWindow: function() { var dashPanelHeight = this.getHeight(); var dashPanelWidth = this.getWidth(); var winHeight = (dashPanelHeight > 339) ? 330 : dashPanelHeight - 10; var winWidth = (dashPanelWidth > 559) ? 550 : dashPanelWidth - 10; var createNewDashboardWindowId = 'createNewDashboardWindowId'; var win = Ext.getCmp(createNewDashboardWindowId); if (!win) { var createNewDashboardWindowConfig = { id: createNewDashboardWindowId, title: Ozone.layout.tooltipString.createDashboardTitle, ownerCt: this, constrain: Ext.isIE, constrainHeader: true, cls: "manageContainer", closeAction: 'destroy', draggable: true, items: [{ xtype: 'owfCreateDashboardsContainer', dashboardContainer: this, winId: createNewDashboardWindowId } ], width: winWidth + 20, height: winHeight, listeners: { show: function(cmp) { var newDashboardPanel = this.getComponent('createNewDashboardPanel'); var titleBox = newDashboardPanel.getComponent('titleBox'); titleBox.setRawValue(''); var importFileupload = newDashboardPanel.down('#importFileupload'); importFileupload.setRawValue(''); newDashboardPanel.refreshData(); if (newDashboardPanel.afterRenderInitComplete == false) { newDashboardPanel.down('#viewCb').enable(); newDashboardPanel.down('#viewCb').validate(); var existViewCb = newDashboardPanel.down('#existViewCb'); existViewCb.reset(); existViewCb.disable(); importFileupload.reset(); importFileupload.disable(); newDashboardPanel.afterRenderInitComplete = true; } newDashboardPanel.focusTitleBox(); titleBox.clearInvalid(); this.setupFocus(titleBox.el, this.down('#cancelBtn').el); } } }; win = Ext.widget('managerwindow', createNewDashboardWindowConfig); } if (win.isVisible()) { win.close(); } else { win.show(); } }, navigate: function(incr) { var cmp = this.getComponent('dashboardCardPanel'); var layout = cmp.getLayout(); var index = cmp.items.indexOf(layout.activeItem); index = index + incr; layout.activeItem.windowGroup.hideAll(); if (index > 0 && index < cmp.items.getCount()) { layout.setActiveItem(cmp.items.get(index)); } }, getPanes: function () { var panes = this.activeDashboard.panes; return _.map(panes, function (pane) { return pane.getPaneUIState(); }); }, initEventing: function() { Ozone.eventing.Container.init({ //override getIframeId directly lookup iframe ids via ext components getIframeId: { fn: function(uniqueId) { var widgetCmp = Ext.getCmp(uniqueId); if (widgetCmp != null) { var iframeCmp = widgetCmp.down('#widgetIframe'); if (iframeCmp != null) { return iframeCmp.el.dom.id; } } }, scope: this }, getPanes: _.bind(this.getPanes, this), //override getOpenedWidgets getOpenedWidgets: { fn: this.getOpenedWidgets, scope: this }, //hook widgetEventingReady so loadTime may be captured per widget widgetEventingReady: { fn: function(sender, message) { var initMessage = gadgets.json.parse(message); if (initMessage.loadTime != null) { var widgetCfg = gadgets.json.parse(initMessage.id); var loadTimeCfg = { id: widgetCfg.id, msg: 'Loaded in ' + initMessage.loadTime + ' (ms)', loadTime: initMessage.loadTime }; //get widget display name var activeWidgets = this.activeDashboard.stateStore; if (activeWidgets != null) { var wrec = activeWidgets.getById(widgetCfg.id); if (wrec != null) { loadTimeCfg.name = wrec.get('name'); loadTimeCfg.widgetGuid = wrec.get('widgetGuid'); this.sendLoadTime(loadTimeCfg); } else { //widget is not in the store however it will be so attach a listener on add activeWidgets.on({ add: { fn: function(store, records, index) { var w = store.getById(widgetCfg.id); if (w != null) { loadTimeCfg.name = w.get('name'); loadTimeCfg.widgetGuid = w.get('widgetGuid'); this.sendLoadTime(loadTimeCfg); } }, scope: this, single: true } }); } } } }, scope: this }, onRoute: { fn: function(sender, subscriber, channel, message) { var returnValue = false; //if the sender or subscriber is the container then always let the message through if (sender != '..' && subscriber != '..') { //check if the sender and subscriber are on the same dashboard if so allow the message else deny it var senderObj = Ozone.util.parseJson(sender); var senderDashboard = this.findParentDashboard(senderObj.id); var subscriberObj = Ozone.util.parseJson(subscriber); var subscriberDashboard = this.findParentDashboard(subscriberObj.id); if (senderDashboard != null && senderDashboard == subscriberDashboard) { returnValue = true; } } else { returnValue = true; } return returnValue; }, scope: this } }); this.eventingContainer = Ozone.eventing.Container; OWF.IntentsContainer.init({ onRoute: { fn: function(sender, intent, data, dest, container) { var sendingId = Ozone.util.parseJson(sender).id; var sendingCmp = Ext.getCmp(sendingId); var intentConfig = sendingCmp.intentConfig; //check for any saved preference that routes this intent if (!dest || (dest.length != null && dest.length <= 0)) { if (intentConfig != null && intentConfig[owfdojo.toJson(intent)] != null) { var intentConfigDest = intentConfig[owfdojo.toJson(intent)]; //check if dest widgets exists on the dashboard, if they all don't delete the data var existsOnDashboardCount = 0; for (var i = 0, len = intentConfigDest.length; i < len; i++) { var destFrameId = intentConfigDest[i]; var destId = Ozone.util.parseJson(destFrameId).id; if (this.activeDashboard.stateStore.indexOfId(destId) > -1) { existsOnDashboardCount++; } } //only send if dest widgets are on the current dashboard if (existsOnDashboardCount == intentConfigDest.length) { //just send the intent if destination(s) is specified via saved intentConfig container.send(sender, intent, data, null, intentConfigDest); container.callback(intentConfigDest); return; } else { //remove data delete intentConfig[owfdojo.toJson(intent)]; } } //handle opening launch menu and routing the intent this.showIntentsWindow(intent, container, sender, data, sendingCmp); } else { //todo handle error here if the widget doesn't exist //just send the intent if destination(s) is specified container.send(sender, intent, data, null, dest); container.callback(dest); } }, scope: this } }); }, showIntentsWindow: function(intent, container, sender, data, sendingCmp) { var me = this, intentConfig, deferredSendIntentListener, isRememberSelection = false, bodyEl = Ext.getBody(), maskEl = bodyEl.mask().addCls('intent-modal-mask'); this.hideAppComponentsView(); function onHide() { isRememberSelection = me.intentsWindow.isRememberSelection(); me.intentsWindow.$el.off('hide', onHide); maskEl.un('click', onHide); bodyEl.unmask(); setTimeout(function () { me.intentsWindow.remove(); me.intentsWindow = null; Ozone.KeyMap.enable(); }, 0); } maskEl.on('click', onHide); Ozone.KeyMap.disable(); me._initIntentsWindow(intent).show(); me.intentsWindow.$el .on('cancel', function () { me.intentsWindow.$el.off('cancel'); //unattach the listeners no widget will be launched me.un(widgetLaunchListener); if (deferredSendIntentListener) { container.removeListener('onIntentsReady', deferredSendIntentListener, me); } //fire callback to startActivity container.callback([]); }) .on('hide', onHide); var widgetLaunchListener = { beforewidgetlaunch: { fn: function(pane, model) { var data = { intents: true }; model.set('launchData', gadgets.json.stringify(data)); }, single: true }, afterwidgetlaunch: { fn: function(widget, model, wasAlreadyLaunched) { var id = widget.uniqueId; var destIdString = '{\"id\":\"' + id + '\"}'; !sendingCmp.intentConfig && (sendingCmp.intentConfig = {}); intentConfig = sendingCmp.intentConfig; function sendIntent () { container.send(sender, intent, data, null, destIdString); //check if the intentcheckbox is checked if so save to intentConfig if (isRememberSelection) { if (intentConfig[owfdojo.toJson(intent)] == null) { intentConfig[owfdojo.toJson(intent)] = []; } intentConfig[owfdojo.toJson(intent)].push(destIdString); } } //the widget is already open, send intent immeditaly if (wasAlreadyLaunched) { sendIntent(); } //widget is not launched yet else { //create a listener function to send the intent once the launched widget //and has registered to receive the intent deferredSendIntentListener = function(i, destWidgetId) { //send the data to the dest widgets only if intent and dest widget match if (i != null && owfdojo.toJson(i) === owfdojo.toJson(intent) && destWidgetId === destIdString) { sendIntent(); //remove this listener now that the intent has been sent container.removeListener('onIntentsReady', deferredSendIntentListener, me); } //todo perhaps put a timer to timeout the intent, and remove the listener //this would only need to be done if a widget was opened that never registered //for the specified intent }; //hook event that will fire when the dest widget is ready for the intent container.addListener('onIntentsReady', deferredSendIntentListener, me); } //fire callback to startActivity call once dest widgets have been identified container.callback([destIdString]); }, single: true } }; me.on(widgetLaunchListener); }, _initIntentsWindow: function (intent) { var matchingOpenedAppComponents = this.activeDashboard.stateStore.findByReceiveIntent(intent); matchingOpenedAppComponents = _.map(matchingOpenedAppComponents, function (match) { var data = _.extend({}, match.data); data.image = match.get('image'); return data; }); var matchingAppComponents = OWF.Collections.AppComponents.findByReceiveIntent(intent); this.intentsWindow = new Ozone.components.appcomponents.IntentsWindow({ matchingOpenedAppComponents: new Ozone.data.collections.Widgets(matchingOpenedAppComponents), matchingAppComponents: new Ozone.data.collections.Widgets(matchingAppComponents), dashboardContainer: this }); $('body').append(this.intentsWindow.render().el); this.intentsWindow.shown(); return this.intentsWindow; }, _showIntentsWindow: function(intent, container, sender, data, sendingCmp) { var intentConfig = sendingCmp.intentConfig; //open launch menu var launchMenu = Ext.getCmp('widget-launcher'); if (launchMenu) { //if the user didn't actually launch a widget remove the other listeners noWidgetLaunchListener = { noWidgetLaunched: { fn: function() { }, scope: this, single: true } }; launchMenu.on(noWidgetLaunchListener); } }, findParentDashboard: function(widgetId) { var dashboardCardPanel = this.getComponent('dashboardCardPanel'); var parentDashboard = null; for (var i = 0; i < dashboardCardPanel.items.getCount(); i++) { var dashboard = dashboardCardPanel.items.getAt(i); if (dashboard.stateStore.getById(widgetId) != null) { parentDashboard = dashboard; break; } } return parentDashboard; }, sendLoadTime: function(loadTimeCfg) { //send to server if (Ozone.config.sendWidgetLoadTimesToServer === true) { Ozone.util.Transport.send({ url: Ozone.util.contextPath() + '/widgetLoadTime', method: 'POST', async: true, content: loadTimeCfg, onSuccess: function() { //do nothing } }); } //send to channel if (Ozone.config.publishWidgetLoadTimes === true) { var payload = gadgets.json.stringify(loadTimeCfg); Ozone.eventing.Container.publish('Ozone.eventing.widget.public', payload); } }, getOpenedWidgets: function() { var returnValue = []; if (this.activeDashboard != null && this.activeDashboard.stateStore != null) { var recs = this.activeDashboard.stateStore.getRange(); for (var i = 0; i < recs.length; i++) { var rec = recs[i].data; var widgetCmp = Ext.getCmp(rec.uniqueId); var widgetDefRec = this.widgetStore.getById(rec.widgetGuid); if (widgetDefRec != null) { var widgetDef = widgetDefRec.data; if (widgetDef != null && widgetCmp != null) { var iframeCmp = widgetCmp.down('#widgetIframe'); if (iframeCmp != null) { returnValue.push({ //kernel fields id: rec.uniqueId, name: rec.name, url: widgetDef.url, //kernel fields //extra info frameId: iframeCmp.id, widgetGuid: rec.widgetGuid, widgetName: widgetDef.name, universalName: widgetDef.universalName }); } } } } } return returnValue; }, startAutoSave: function() { if (this.autoSaveId) { clearInterval(this.autoSaveId); } this.autoSaveId = setInterval(Ext.bind(function() { if (this.autoSaveClear) { clearInterval(this.autoSaveId); this.autoSaveClear = false; } else if (this.autoSaveEnabled) { //get active dashboard and save it if (this.activeDashboard) { Ext.getCmp(this.activeDashboard.id).saveToServer(); } } }, this), this.pollingInterval); }, deleteDashboards: function(dashboardsToDelete, destroyMyAppsWin) { // ----------------------------------------------------------- // Remove dashboards from all dashboard-related components. // Incoming argument is an array of dashboard guids to remove. // ----------------------------------------------------------- var deleteCount = dashboardsToDelete.length; if (deleteCount == 0) { return; } var dashPanel = this.getDashboardCardPanel(); // Remove dashboards contained in incoming array parameter. for (var i1 = 0; i1 < deleteCount; i1++) { // Remove from dashboard store. var dsIndex = this.dashboardStore.find('guid', dashboardsToDelete[i1]); if (dsIndex != -1) { // If default dashboard is deleted reset default to first dashboard. if (this.dashboardStore.getAt(dsIndex).get('isDefault') == true) { this.dashboardStore.getAt(0).get('isDefault') == true; this.activeDashboard = this.dashboards[0]; this.defaultDashboard = this.activeDashboard; } this.dashboardStore.removeAt(dsIndex); } // Remove from banner tabs and card layout. dashPanel.remove(dashboardsToDelete[i1]); // Remove from 'dashboards' array. for (var i3 = 0, dblen = this.dashboards.length; i3 < dblen; i3++) { if (this.dashboards[i3].id == dashboardsToDelete[i1]) { this.dashboards.splice(i3, 1); break; } } } if (destroyMyAppsWin !== false) { this.destroyMyAppsWindow(); } }, /** * Update all dashboard-related components with newly-refreshed * dashboardStore data. * @private * @param dashboardGuidToActivate GUID of dashboard to activate. * @param stackContextToActivate Context ID of stack to activate. Will * take precedence over dashboardGuidToActivate if found. */ updateDashboardsFromStore: function(storeRecords, callbackOptions, loadSuccess, dashboardGuidToActivate, stackContextToActivate) { var me = this; var updateDeferred = $.Deferred(); if (storeRecords.length === 0 || (storeRecords.length === 1 && storeRecords[0].get("type") === "marketplace")) { me.createEmptyDashboard('desktop', true, function () { me.updateDashboardsFromStore( storeRecords, callbackOptions, loadSuccess, dashboardGuidToActivate, stackContextToActivate).then( function() { updateDeferred.resolve(); } ); }); return updateDeferred.promise(); } // Set default tab guid. var defaultTabGuid = storeRecords[0].get('guid'); var stack = storeRecords[0].get('stack'); var stackContext = stack ? stack.stackContext : null; var dashboardGuidFound = false; // Clear 'this.dashboards' array. this.dashboards.length = 0; var dashPanel = this.getDashboardCardPanel(); dashPanel.removeAll(true); this.destroyMyAppsWindow(); // Without the timeout, updateDashboardsFromStore causes problems when dashboards are restored // because widget destruction is delayed by 100ms to prevent memory leaks. // Because of the delay, widgets on a dashboard get rerendered while previous ones haven't been destroyed. setTimeout(function() { var dashboards = []; // Update various dashboard-related components. for (var i1 = 0, len = storeRecords.length; i1 < len; i1++) { var dsRecord = storeRecords[i1]; if (!dashboardGuidFound || stackContextToActivate) { var recordStack = dsRecord.get('stack'); var recordGuid = dsRecord.get('guid'); // stackContextToActivate takes precedence over // dashboardGuidToActivate if (stackContextToActivate && recordStack && recordStack.stackContext && recordStack.stackContext === stackContextToActivate) { // Force dashboard associated with target stack dashboardGuidToActivate = recordGuid; stackContext = stackContextToActivate; dashboardGuidFound = true; // Stop this check after first match stackContextToActivate = null; } else if (!dashboardGuidFound) { dashboardGuidFound = dashboardGuidToActivate === recordGuid; // OP-2799: Have to get the stack context from this // record so the URL can change correctly to the new // dashboard when activated if (dashboardGuidFound) { stackContext = recordStack ? recordStack.stackContext : null; } } } // Add dashboard object to local array. me.dashboards.push(me.createDashboardConfig(dsRecord)); me.dashboards[i1].hidden = true; //start all dashboards hidden, the //active one will be shown later // Add dashboard to buffered card panel. var addedDash = dashPanel.add(me.dashboards[i1]); // Save default dashboard Guid and set active dashboard instance. if (dsRecord.get('isdefault')) { defaultTabGuid = dsRecord.get('guid'); if (!dashboardGuidFound) { stack = dsRecord.get('stack'); stackContext = stack ? stack.stackContext : null; } me.activeDashboard = addedDash; me.defaultDashboard = addedDash; } // disable animations when rerendering deleted dashboards addedDash.disableCssAnimations(); dashboards.push(addedDash); } // validate dashboardGuidToActivate dashboardGuidToActivate = dashboardGuidFound === true ? dashboardGuidToActivate : defaultTabGuid; // activate dashboard me._activateDashboard(dashboardGuidToActivate); // Focus the default dashboard. me.activateDashboard(dashboardGuidToActivate, true, stackContext, true); //If browser uses animations, enable them now that dashboards are added to card layout if (Modernizr.cssanimations) { for (var j = 0, len = dashboards.length; j < len; j++) { dashboards[j].enableCssAnimations(); } } updateDeferred.resolve(); }, 200); return updateDeferred.promise(); }, /** * Reloads the dashboard store from the server. * * @param callback A callback function to execute when the * load is complete. This function is passed a boolean parameter * indicating whether or not the refresh was successful. * @param stackContextToActivate Context ID of stack to activate. If * null or not found the current dashboard will remain active. */ reloadDashboards: function(callback, stackContextToActivate) { // TODO improvement: only restored dashboards should be refresh and deleted dashboard be removed var me = this; me.dashboardStore.load({ callback: function(records, options, success) { me.reloadStacks(); records = me.dashboardStore.data.items; var onCompletion = function() { Ext.isFunction(callback) && callback(success); } if (success == true) { me.updateDashboardsFromStore( records, options, success, me.activeDashboard.getGuid(), stackContextToActivate).then(onCompletion); } else { onCompletion(); } } }); }, saveActiveDashboardToServer: function() { // only save if the active dashboard is in store // it may have been deleted if (this.dashboardStore.getById(this.activeDashboard.id)) { Ext.getCmp(this.activeDashboard.id).saveToServer(true, true, false); } }, saveDashboard: function(json, createOrUpdate, success, failure) { var me = this; if (!failure) { failure = function() { Ozone.Msg.alert('Dashboard Manager', "Error creating or updating page.", null, null, null, me.modalWindowManager); return; }; } Ozone.pref.PrefServer.createOrUpdateDashboard({ json: json, saveAsNew: createOrUpdate == 'create' ? true : false, onSuccess: function(json) { me.destroyMyAppsWindow(); var dashboard = me.dashboardCreated(json); success && success(json, dashboard); me = null; }, onFailure: failure }); }, createEmptyDashboard: function(type, setAsDefault, callback) { // create a blank dashboard of the specified type and go to it var newGuid = guid.util.guid(); var newJson = { "name": 'Untitled', "guid": newGuid, "isdefault": setAsDefault, "state": [], "layoutConfig": Ozone.config.defaultLayoutConfig, "publishedToStore": true //allow the user to get their own copy of the //dashboard }; this.saveDashboard(newJson, 'create', callback); }, createDashboard: function(model) { this.designDashboard(model, false); }, editDashboard: function(model) { var dashboard = this.getDashboardCardPanel().getComponent(model.get('guid')); this.designDashboard(dashboard || model, dashboard ? true : false); }, dashboardCreated: function(json) { // if it already exists in store return if (this.dashboardStore.getById(json.guid)) { return; } var dashboard = Ext.create('Ozone.data.Dashboard', json); this.dashboardStore.add(dashboard); // If the stack was created, add it to the store var stack = dashboard.get('stack'); if (stack && stack.id && !this.stackStore.getById(stack.id)) { this.stackStore.add(stack); } // Add new dashboard object to local array. this.dashboards.push(this.createDashboardConfig(dashboard)); // Add new dashboard to buffered card panel. var dashPanel = this.getDashboardCardPanel(); return dashPanel.add(this.dashboards[this.dashboards.length - 1]); }, designDashboard: function(dashboard, dashboardExists) { Ozone.KeyMap.disable(); var banner = this.getBanner(), me = this; banner.el.mask(); var dashboardCardPanel = Ext.getCmp('dashboardCardPanel'); var dashboardDesigner = Ext.widget('dashboarddesigner', { dashboardContainer: this, dashboard: dashboard || this.activeDashboard, dashboardStore: this.dashboardStore, dashboardExists: dashboardExists, renderTo: dashboardCardPanel.el, ownerCt: dashboardCardPanel }); dashboardDesigner.on('destroy', function() { banner.el.unmask(); Ozone.KeyMap.enable(); }); }, setDefaultDashboard: function(guid) { var newDefault = this.getDashboardCardPanel().getComponent(guid); if (newDefault && this.defaultDashboard != newDefault) { //set old dashboard as not default //todo remove using isdefault in favor of using the configRecord this.defaultDashboard.isdefault = false; this.defaultDashboard.configRecord.set('isdefault', false); this.defaultDashboard.configRecord.commit(true); //set newDefault newDefault.isdefault = true; newDefault.configRecord.set('isdefault', true); newDefault.configRecord.commit(true); this.defaultDashboard = newDefault; } }, storeContains: function(widgetGuid) { var store = this.activeDashboard.stateStore; if (store) { return store.findRecord('widgetGuid', widgetGuid); } return null; }, closeWidget: function(key, event, widgetInstanceId) { var activeWidget = widgetInstanceId ? Ext.getCmp(widgetInstanceId) : this.activeDashboard.getActiveWidget(); activeWidget && activeWidget.close(); }, maximizeCollapseWidget: function(key, event, widgetInstanceId) { var activeWidget = widgetInstanceId ? Ext.getCmp(widgetInstanceId) : this.activeDashboard.getActiveWidget(); activeWidget && activeWidget.pane.maximizeCollapseWidget(activeWidget); }, minimizeExpandWidget: function(key, event, widgetInstanceId) { var activeWidget = widgetInstanceId ? Ext.getCmp(widgetInstanceId) : this.activeDashboard.getActiveWidget(); activeWidget && activeWidget.pane.minimizeExpandWidget(activeWidget); }, saveWidgetState: function(key, event, widgetInstanceId) { var widget = widgetInstanceId ? Ext.getCmp(widgetInstanceId) : this.activeDashboard.getActiveWidget(); if (widget && widget.isFloating()) { widget.onStateChange(); } }, updateTitlesandBanner: function() { //if we have a marketplace widget or marketplace config, tell the banner to add a button var mpWidgets = this.getMpWidgets(); if (mpWidgets && mpWidgets.length > 0) { var singleWidget = (mpWidgets.length == 1) ? mpWidgets[0] : null; this.getBanner().addMarketplaceButton(singleWidget); } else { this.getBanner().removeMarketplaceButton(); } if (this.hasMetricsWidget()) { this.getBanner().getUserMenuBtn().enableMetricsMenuItem(); } else { this.getBanner().getUserMenuBtn().disableMetricsMenuItem(); } }, getMpWidgets: function() { return _.filter(this.widgetStore.getRange(), function(widget) { return (widget.data.widgetTypes.length > 0 && widget.data.widgetTypes[0].name === 'marketplace') }); }, hasMetricsWidget: function() { return Boolean(_.find(this.widgetStore.getRange(), function(widget) { return (widget.data.widgetTypes.length > 0 && widget.data.widgetTypes[0].name === 'metric') })); }, /** * Adds eventing subscriptions to receive messages from the admin widgets indicating * that dashboards/stacks have been associated/dissociated from users or groups. If the * current user is part of what was changed, refresh the dashboards */ setupDashboardChangeListeners: function() { var me = this; //WARNING: If, at some point in the future, there is a need in //some other place to receive AdminChannel info, care will need to be taken //not to override this listener OWF.Container.Eventing.subscribe('AdminChannel', function(sender, msg) { //stack or group dashboard editor used to assign to a user or group if (Ext.Array.contains(['Stack', 'Dashboard'], msg.domain)) { var records = msg.action.resultSet.records, type = msg.action.params.tab, //see if affected records include the current user affectsUser = type === 'users' && Ext.Array.some(records, function(record) { return record.get('username') === Ozone.config.user.displayName; }); //if it is detected that a dashboard or stack may have been added removed from //the current user, refresh the dashboards. if (affectsUser) { me.dashboardsNeedRefresh = true; } } }); }, toggleMarketplaceMenuOnDashboardSwitch: function(dashboard) { var btn = this.getBanner().getUserMenuBtn(); if (dashboard.configRecord.isMarketplaceDashboard()) { btn.enableMarketplaceMenu(); } else { btn.disableMarketplaceMenu(); } }, removeAppComponent: function (model, collection, options) { var me = this, appComponentGuid = model.get('widgetGuid'); // if fetching collection, dont update or delete on server if(options.fetch) { removeAppComponents(); } else { Ozone.pref.PrefServer.updateAndDeleteWidgets({ widgetsToUpdate:[], widgetGuidsToDelete: [appComponentGuid], updateOrder:false, onSuccess: removeAppComponents, onFailure: $.noop }); } function removeAppComponents () { var widgetStoreRecord = me.widgetStore.findRecord('widgetGuid', appComponentGuid), dashboardCardPanel = Ext.getCmp('dashboardCardPanel'); me.widgetStore.remove(widgetStoreRecord); // Iterate through all the open dashboards dashboardCardPanel.items.each(function(dashboard) { // Access state store for each dashboard describing the state of the widgets running inside that dashboard dashboard.stateStore.each(function(widgetState) { // Compare widget GUID to that of the one being removed if (widgetState.get('widgetGuid') == appComponentGuid) { // Remove the widget in question from its dashboard var uniqueId = widgetState.get('uniqueId'); dashboard.closeWidget(uniqueId); } }); }); } }, /** * Reverts stack model change for given dashboard's parent stack * @param dashboardId */ cancelStackChange: function(dashboardId) { var dashboardModel = this.dashboardStore.getById(dashboardId); if (dashboardModel) { var stackModel = dashboardModel.get('stack'); if (stackModel) { var stack = this.stackStore.getById(stackModel.id); stack.reject(); } } }, /** * Reverts dashboard model change * @param dashboardId */ cancelDashboardChange: function(dashboardId) { var dashboardModel = this.dashboardStore.getById(dashboardId); if (dashboardModel) { dashboardModel.reject(); } }, /** * Register a private service that allows the Marketplace widget to * determine via RPC if a particular listing has already been added by * the current OWF user. This will save us a round trip to the server. * Searches for both Apps (formerly stacks) and App Components * (formerly widgets). */ setupUserListingCheckService: function() { var me = this; var serviceName = '_MARKETPLACE_LISTING_CHECK'; // "msg" must contain a "guid" string to lookup OWF.Container.Eventing.registerHandler(serviceName, function (msg) { var result = false; // Check all user Apps for (var i = 0, len = me.dashboardStore.getCount(); i < len; i++) { var model = me.dashboardStore.getAt(i).data; if (model.stack && model.stack.stackContext && model.stack.stackContext == msg.guid) { result = true; break; } } // Check all user App Components if(!result) { result = OWF.Collections.AppComponents.findWhere({widgetGuid: msg.guid}) != null; } return result; }); } });
chiendarrendor/AlbertsAdalogicalAenigmas
common/grid/spring/GridPanelContainer.java
<filename>common/grid/spring/GridPanelContainer.java package grid.spring; import javax.swing.*; import javax.swing.border.Border; import java.awt.*; import java.awt.event.*; import java.util.Arrays; public class GridPanelContainer extends JPanel { GridPanel gp = null; GridPanel.GridListener gl = null; GridPanel.MultiGridListener mgl = null; JButton prevButton = new JButton("<"); JButton nextButton = new JButton(">"); JLabel answer = new JLabel(); private void setAnswer() { String[] lines = gl.getAnswerLines(); StringBuffer sb = new StringBuffer(); sb.append("<html><font size=\"5\">"); Arrays.stream(lines).forEach(line->sb.append(line).append("<br>")); sb.append("</font></html>"); answer.setText(sb.toString()); } private class PrevHandler implements ActionListener { public void actionPerformed(ActionEvent e) { mgl.moveToPrev(); prevButton.setEnabled(mgl.hasPrev()); nextButton.setEnabled(mgl.hasNext()); setAnswer(); gp.repaint(); } } private class NextHandler implements ActionListener { public void actionPerformed(ActionEvent e) { mgl.moveToNext(); prevButton.setEnabled(mgl.hasPrev()); nextButton.setEnabled(mgl.hasNext()); setAnswer(); gp.repaint(); } } public GridPanelContainer(int width, int height,GridPanel.GridListener listener) { this(width,height,listener,null); } public GridPanelContainer(int width, int height,GridPanel.GridListener listener,GridPanel.EdgeListener edgeListener) { super(new BorderLayout()); gl = listener; if (listener instanceof GridPanel.MultiGridListener) { mgl = (GridPanel.MultiGridListener)listener; } gp = new GridPanel(width,height,listener,edgeListener); add(gp, BorderLayout.CENTER); add(answer,BorderLayout.SOUTH); setAnswer(); Border border = BorderFactory.createLineBorder(Color.BLUE, 5); answer.setBorder(border); if (mgl != null) { add(new VerticalCenterPanel(prevButton),BorderLayout.WEST); add(new VerticalCenterPanel(nextButton),BorderLayout.EAST); prevButton.setEnabled(mgl.hasPrev()); nextButton.setEnabled(mgl.hasNext()); prevButton.addActionListener(new PrevHandler()); nextButton.addActionListener(new NextHandler()); } } }
calfgz/dapeng-soa
dapeng-container/dapeng-container-api/src/main/java/com/github/dapeng/api/Container.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.dapeng.api; import com.github.dapeng.core.Application; import com.github.dapeng.core.ProcessorKey; import com.github.dapeng.core.definition.SoaServiceDefinition; import com.github.dapeng.core.filter.Filter; import java.util.List; import java.util.Map; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicInteger; /** * 大鹏容器的主结构,负责管理容器相关的监听器,插件,应用程序。 * * 所有的组件的注册,卸载动作都应该由Container来负责, */ public interface Container { /** * 容器状态 */ int STATUS_UNKNOWN = 0; int STATUS_CREATING = 1; int STATUS_RUNNING = 2; int STATUS_SHUTTING = 3; int STATUS_DOWN = 4; /** * 注册应用程序监听器, * @param listener */ void registerAppListener(AppListener listener); /** * 卸载用用程序监听器 * @param listener */ void unregisterAppListener(AppListener listener); /** * 注册应用程序(保存容器具体的应用信息) * @param app */ void registerApplication(Application app); /** * 卸载应用程序 * @param app */ void unregisterApplication(Application app); /** * 注册插件(like: Zookeeper,netty..etc.) * @param plugin */ void registerPlugin(Plugin plugin); /** * 卸载插件 * @param plugin */ void unregisterPlugin(Plugin plugin); /** * 注册Filter(like: monitor) */ void registerFilter(Filter filter); /** * 卸载Filter * @param filter */ void unregisterFilter(Filter filter); /** * 获取应用程序的相关信息 * @return */ List<Application> getApplications(); List<Plugin> getPlugins(); Map<ProcessorKey, SoaServiceDefinition<?>> getServiceProcessors(); // fixme @Deprecated void registerAppProcessors(Map<ProcessorKey, SoaServiceDefinition<?>> processors); Application getApplication(ProcessorKey key); // fixme @Deprecated void registerAppMap(Map<ProcessorKey,Application> applicationMap); Executor getDispatcher(); List<Filter> getFilters(); void startup(); /** * 0:unknow; * 1:creating; * 2:running; * 3:shutting * 4:down * * @return status of container */ int status(); /** * 容器内未完成的请求计数 */ AtomicInteger requestCounter(); }
microsoftgraph/msgraph-beta-sdk-java
src/main/java/com/microsoft/graph/requests/IosManagedAppProtectionHasPayloadLinksCollectionRequestBuilder.java
// Template Source: BaseMethodCollectionRequestBuilder.java.tt // ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.requests; import com.microsoft.graph.http.IRequestBuilder; import com.microsoft.graph.core.ClientException; import com.microsoft.graph.models.HasPayloadLinkResultItem; import java.util.Arrays; import java.util.EnumSet; import javax.annotation.Nullable; import javax.annotation.Nonnull; import com.microsoft.graph.requests.IosManagedAppProtectionHasPayloadLinksCollectionRequestBuilder; import com.microsoft.graph.requests.IosManagedAppProtectionHasPayloadLinksCollectionRequest; import com.microsoft.graph.requests.IosManagedAppProtectionHasPayloadLinksCollectionResponse; import com.microsoft.graph.models.IosManagedAppProtectionHasPayloadLinksParameterSet; import com.microsoft.graph.options.FunctionOption; import com.microsoft.graph.core.IBaseClient; import com.microsoft.graph.http.BaseActionCollectionRequestBuilder; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The class for the Ios Managed App Protection Has Payload Links Collection Request Builder. */ public class IosManagedAppProtectionHasPayloadLinksCollectionRequestBuilder extends BaseActionCollectionRequestBuilder<HasPayloadLinkResultItem, IosManagedAppProtectionHasPayloadLinksCollectionRequestBuilder, IosManagedAppProtectionHasPayloadLinksCollectionResponse, IosManagedAppProtectionHasPayloadLinksCollectionPage, IosManagedAppProtectionHasPayloadLinksCollectionRequest> { /** * The request builder for this collection of IosManagedAppProtection * * @param requestUrl the request URL * @param client the service client * @param requestOptions the options for this request */ public IosManagedAppProtectionHasPayloadLinksCollectionRequestBuilder(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) { super(requestUrl, client, requestOptions, IosManagedAppProtectionHasPayloadLinksCollectionRequestBuilder.class, IosManagedAppProtectionHasPayloadLinksCollectionRequest.class); } private IosManagedAppProtectionHasPayloadLinksParameterSet body; /** * The request builder for this collection of IosManagedAppProtection * * @param requestUrl the request URL * @param client the service client * @param requestOptions the options for this request * @param parameters the parameters for the service method */ public IosManagedAppProtectionHasPayloadLinksCollectionRequestBuilder(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions, @Nonnull final IosManagedAppProtectionHasPayloadLinksParameterSet parameters) { super(requestUrl, client, requestOptions, IosManagedAppProtectionHasPayloadLinksCollectionRequestBuilder.class, IosManagedAppProtectionHasPayloadLinksCollectionRequest.class); this.body = parameters; } /** * Creates the request * * @param requestOptions the options for this request * @return the IosManagedAppProtectionHasPayloadLinksCollectionRequest instance */ @Override @Nonnull public IosManagedAppProtectionHasPayloadLinksCollectionRequest buildRequest(@Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) { final IosManagedAppProtectionHasPayloadLinksCollectionRequest request = super.buildRequest(requestOptions); request.body = this.body; return request; } }
efedo/Sirelphy
source/core/unitlib/helpers/dimension_templates.h
<filename>source/core/unitlib/helpers/dimension_templates.h // Copyright 2018-19 <NAME> #pragma once #include "Sirelphy/source/core/precomp.h" namespace _units_private { // Built-in dimensions template < class Time = std::ratio<0>, class Length = std::ratio<0>, class Mass = std::ratio<0>, class Charge = std::ratio<0>, class Temperature = std::ratio<0>, class Amount = std::ratio<0>, class Angle = std::ratio<0> > struct unitDimensions { static constexpr long long time_num = Time::num; static constexpr long long time_den = Time::den; static constexpr long long length_num = Length::num; static constexpr long long length_den = Length::den; static constexpr long long mass_num = Mass::num; static constexpr long long mass_den = Mass::den; static constexpr long long charge_num = Charge::num; static constexpr long long charge_den = Charge::den; static constexpr long long temperature_num = Temperature::num; static constexpr long long temperature_den = Temperature::den; static constexpr long long amount_num = Amount::num; static constexpr long long amount_den = Amount::den; static constexpr long long cycle_num = Angle::num; static constexpr long long cycle_den = Angle::den; static void debugPrint() { std::cout << "Unit dimensions:" << "\n"; std::cout << "time (T): " << time_num << "/" << time_den << "\n"; std::cout << "length (L): " << length_num << "/" << length_den << "\n"; std::cout << "mass (M): " << mass_num << "/" << mass_den << "\n"; std::cout << "charge (Q): " << charge_num << "/" << charge_den << "\n"; std::cout << "temperature (K): " << temperature_num << "/" << temperature_den << "\n"; std::cout << "amount (N): " << amount_num << "/" << amount_den << "\n"; std::cout << "angle (A): " << cycle_num << "/" << cycle_den << "\n"; } }; template <class LHS, class RHS> struct _unitDimensions_add { // add two ratios //static_assert(_Is_ratio_v<_R1>&& _Is_ratio_v<_R2>, "ratio_add<R1, R2> requires R1 and R2 to be ratio<>s."); // redirection necessary to make this possible using type = typename unitDimensions< std::ratio_add<std::ratio<LHS::time_num, LHS::time_den>, std::ratio<RHS::time_num, RHS::time_den>>, std::ratio_add<std::ratio<LHS::length_num, LHS::length_den>, std::ratio<RHS::length_num, RHS::length_den>>, std::ratio_add<std::ratio<LHS::mass_num, LHS::mass_den>, std::ratio<RHS::mass_num, RHS::mass_den>>, std::ratio_add<std::ratio<LHS::charge_num, LHS::charge_den>, std::ratio<RHS::charge_num, RHS::charge_den>>, std::ratio_add<std::ratio<LHS::temperature_num, LHS::temperature_den>, std::ratio<RHS::temperature_num, RHS::temperature_den>>, std::ratio_add<std::ratio<LHS::amount_num, LHS::amount_den>, std::ratio<RHS::amount_num, RHS::amount_den>>, std::ratio_add<std::ratio<LHS::cycle_num, LHS::cycle_den>, std::ratio<RHS::cycle_num, RHS::cycle_den>> >; }; template <class LHS, class RHS> using unitDimensions_add = typename _unitDimensions_add<LHS, RHS>::type; template <class LHS, class RHS> struct _unitDimensions_subtract { // add two ratios //static_assert(_Is_ratio_v<_R1>&& _Is_ratio_v<_R2>, "ratio_add<R1, R2> requires R1 and R2 to be ratio<>s."); // redirection necessary to make this possible using type = typename unitDimensions< std::ratio_subtract<std::ratio<LHS::time_num, LHS::time_den>, std::ratio<RHS::time_num, RHS::time_den>>, std::ratio_subtract<std::ratio<LHS::length_num, LHS::length_den>, std::ratio<RHS::length_num, RHS::length_den>>, std::ratio_subtract<std::ratio<LHS::mass_num, LHS::mass_den>, std::ratio<RHS::mass_num, RHS::mass_den>>, std::ratio_subtract<std::ratio<LHS::charge_num, LHS::charge_den>, std::ratio<RHS::charge_num, RHS::charge_den>>, std::ratio_subtract<std::ratio<LHS::temperature_num, LHS::temperature_den>, std::ratio<RHS::temperature_num, RHS::temperature_den>>, std::ratio_subtract<std::ratio<LHS::amount_num, LHS::amount_den>, std::ratio<RHS::amount_num, RHS::amount_den>>, std::ratio_subtract<std::ratio<LHS::cycle_num, LHS::cycle_den>, std::ratio<RHS::cycle_num, RHS::cycle_den>> >; }; template <class LHS, class RHS> using unitDimensions_subtract = typename _unitDimensions_subtract<LHS, RHS>::type; }
akashtalole/python-flask-restful-api
app/api/helpers/permissions.py
<reponame>akashtalole/python-flask-restful-api from functools import wraps from flask import current_app as app from flask_jwt_extended import verify_jwt_in_request, current_user from app.api.helpers.db import save_to_db from app.api.helpers.errors import ForbiddenError from flask import request from datetime import datetime def second_order_decorator(inner_dec): """ Second order decorator. Decorator to apply on a decorator. https://stackoverflow.com/questions/5952641/decorating-decorators-try-to-get-my-head-around-understanding-it :param inner_dec: :return: """ def ddmain(outer_dec): def decwrapper(f): wrapped = inner_dec(outer_dec(f)) def fwrapper(*args, **kwargs): return wrapped(*args, **kwargs) return fwrapper return decwrapper return ddmain def jwt_required(fn, realm=None): """ Modified from original jwt_required to comply with `flask-rest-jsonapi` decorator conventions View decorator that requires a valid JWT token to be present in the request :param fn: function to be decorated :param realm: an optional realm """ @wraps(fn) def decorator(*args, **kwargs): verify_jwt_in_request() current_user.last_accessed_at = datetime.utcnow() save_to_db(current_user) return fn(*args, **kwargs) return decorator @second_order_decorator(jwt_required) def is_super_admin(f): """ Decorator function for things allowed exclusively to super admin. Do not use this if the resource is also accessible by a normal admin, use the is_admin decorator instead. :param f: :return: """ @wraps(f) def decorated_function(*args, **kwargs): user = current_user if not user.is_super_admin: return ForbiddenError({'source': ''}, 'Super admin access is required').respond() return f(*args, **kwargs) return decorated_function @second_order_decorator(jwt_required) def is_admin(f): """ Decorator function for things allowed to admins and super admins. :param f: :return: """ @wraps(f) def decorated_function(*args, **kwargs): user = current_user if not user.is_admin and not user.is_super_admin: return ForbiddenError({'source': ''}, 'Admin access is required').respond() return f(*args, **kwargs) return decorated_function @second_order_decorator(jwt_required) def is_user_itself(f): """ Allows admin and super admin access to any resource irrespective of id. Otherwise the user can only access his/her resource. :param f: :return: """ @wraps(f) def decorated_function(*args, **kwargs): user = current_user if not user.is_admin and not user.is_super_admin and user.id != kwargs['id']: return ForbiddenError({'source': ''}, 'Access Forbidden').respond() return f(*args, **kwargs) return decorated_function @second_order_decorator(jwt_required) def is_owner(f): """ Allows only Owner to access the event resources. :param f: :return: """ @wraps(f) def decorated_function(*args, **kwargs): user = current_user if user.is_staff: return f(*args, **kwargs) if 'event_id' in kwargs and user.is_owner(kwargs['event_id']): return f(*args, **kwargs) return ForbiddenError({'source': ''}, 'Owner access is required').respond() return decorated_function @second_order_decorator(jwt_required) def is_organizer(f): """ Allows only Organizer to access the event resources. :param f: :return: """ @wraps(f) def decorated_function(*args, **kwargs): user = current_user if user.is_staff: return f(*args, **kwargs) if 'event_id' in kwargs and user.is_organizer(kwargs['event_id']): return f(*args, **kwargs) return ForbiddenError({'source': ''}, 'Organizer access is required').respond() return decorated_function @second_order_decorator(jwt_required) def is_coorganizer(f): """ Allows Organizer and Co-organizer to access the event resources. :param f: :return: """ @wraps(f) def decorated_function(*args, **kwargs): user = current_user if user.is_staff: return f(*args, **kwargs) if 'event_id' in kwargs and user.has_event_access(kwargs['event_id']): return f(*args, **kwargs) return ForbiddenError({'source': ''}, 'Co-organizer access is required.').respond() return decorated_function @second_order_decorator(jwt_required) def is_registrar(f): """ Allows Organizer, Co-organizer and registrar to access the event resources. :param f: :return: """ @wraps(f) def decorated_function(*args, **kwargs): user = current_user if user.is_staff: return f(*args, **kwargs) if 'event_id' in kwargs and ( user.is_registrar(kwargs['event_id']) or user.has_event_access(kwargs['event_id'])): return f(*args, **kwargs) return ForbiddenError({'source': ''}, 'Registrar Access is Required.').respond() return decorated_function @second_order_decorator(jwt_required) def is_track_organizer(f): """ Allows Organizer, Co-organizer and Track Organizer to access the resource(s). :param f: :return: """ @wraps(f) def decorated_function(*args, **kwargs): user = current_user if user.is_staff: return f(*args, **kwargs) if 'event_id' in kwargs and ( user.is_track_organizer(kwargs['event_id']) or user.has_event_access(kwargs['event_id'])): return f(*args, **kwargs) return ForbiddenError({'source': ''}, 'Track Organizer access is Required.').respond() return decorated_function @second_order_decorator(jwt_required) def is_moderator(f): """ Allows Organizer, Co-organizer and Moderator to access the resource(s). :param f: :return: """ @wraps(f) def decorated_function(*args, **kwargs): user = current_user if user.is_staff: return f(*args, **kwargs) if 'event_id' in kwargs and ( user.is_moderator(kwargs['event_id']) or user.has_event_access(kwargs['event_id'])): return f(*args, **kwargs) return ForbiddenError({'source': ''}, 'Moderator Access is Required.').respond() return decorated_function @second_order_decorator(jwt_required) def accessible_events(f): """ Filter the accessible events to the current authorized user If the user is not admin then only events created by user is accessible. :param f: :return: """ @wraps(f) def decorated_function(*args, **kwargs): user = current_user if 'POST' in request.method: kwargs['user_id'] = user.id else: if not user.is_staff: kwargs['user_id'] = user.id return f(*args, **kwargs) return decorated_function
Senither/Yuuko
src/main/java/com/yuuko/core/modules/fun/commands/ChooseCommand.java
package com.yuuko.core.modules.fun.commands; import com.yuuko.core.modules.Command; import com.yuuko.core.modules.fun.FunModule; import com.yuuko.core.utilities.MessageHandler; import net.dv8tion.jda.core.EmbedBuilder; import net.dv8tion.jda.core.events.message.MessageReceivedEvent; import java.util.Random; public class ChooseCommand extends Command { public ChooseCommand() { super("choose", FunModule.class, 1, new String[]{"-choose [choice], [choice]..."}, null); } @Override public void executeCommand(MessageReceivedEvent e, String[] command) { String[] commandParameters = command[1].split("\\s*(,)\\s*"); EmbedBuilder embed = new EmbedBuilder().setTitle((commandParameters.length > 1) ? commandParameters[new Random().nextInt(commandParameters.length)] : commandParameters[0]); MessageHandler.sendMessage(e, embed.build()); } }
run-dong-zhu/Software-Engineer
Algorithm/Recursive/Subset.java
<filename>Algorithm/Recursive/Subset.java package recursive; import java.util.ArrayList; import java.util.List; /** * * @description LeetCode 78, level: Medium * * Given a set of distinct integers, nums, return all possible subsets (the power set). * Note: The solution set must not contain duplicate subsets. * * Input: nums = [1,2,3] * Output: * [ * [3], * [1], * [2], * [1,2,3], * [1,3], * [2,3], * [1,2], * [ * ] */ public class Subset { public static void generator(int count, int[] nums, List<Integer> item, List<List<Integer>> result) { if(count >= nums.length) { return; } item.add(nums[count]); result.add(new ArrayList<>(item)); generator(count + 1, nums, item, result); item.remove(item.size() - 1); generator(count + 1, nums, item, result); } public static List<List<Integer>> solution(int[] nums) { List<List<Integer>> result = new ArrayList<>(); result.add(new ArrayList<>()); generator(0, nums, new ArrayList<>(), result); return result; } public static void main(String[] args) { int[] nums = {1, 2, 3}; List<List<Integer>> result = solution(nums); for(int i = 0; i < result.size(); i++) { List<Integer> item = result.get(i); for(int j = 0; j < item.size(); j++) { System.out.print(item.get(j) + " "); } System.out.println(); } } }
yanglr/LeetCodeOJ
cpp-leetcode/leetcode493-reverse-pairs_merge_sort2.cpp
#include<vector> #include<map> #include<algorithm> #include<iostream> using namespace std; class Solution { int res = 0; int temp[50001]; public: int reversePairs(vector<int>& nums) { int n = nums.size(); vector<int> sorted = nums; helper(nums, sorted, 0, n - 1); return res; } void helper(vector<int>& nums, vector<int>& sorted, int a, int b) { if (a >= b) return; int mid = a + (b - a) / 2; helper(nums, sorted, a, mid); helper(nums, sorted, mid + 1, b); for (int j = mid + 1; j <= b; j++) { auto it = upper_bound(sorted.begin() + a, sorted.begin() + mid + 1, 2 * (long)nums[j]); res += sorted.begin() + mid + 1 - it; } int i = a, j = mid + 1, p = 0; while (i <= mid && j <= b) { if (sorted[i] <= sorted[j]) { temp[p] = sorted[i]; i++; } else { temp[p] = sorted[j]; j++; } p++; } while (i <= mid) { temp[p] = sorted[i]; i++; p++; } while (j <= b) { temp[p] = sorted[j]; j++; p++; } for (int i = 0; i < b - a + 1; i++) sorted[a + i] = temp[i]; } }; // Test int main() { Solution sol; vector<int> nums = {1, 3, 2, 2, 5, 2, 3, 7}; auto res = sol.reversePairs(nums); cout << res << endl; return 0; }
lechium/tvOS130Headers
System/Library/Frameworks/AVKit.framework/AVBehaviorStorage.h
/* * This header is generated by classdump-dyld 1.0 * on Tuesday, November 5, 2019 at 2:48:35 AM Mountain Standard Time * Operating System: Version 13.0 (Build 17J586) * Image Source: /System/Library/Frameworks/AVKit.framework/AVKit * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. */ @class NSMapTable; @interface AVBehaviorStorage : NSObject { id _AVKitOwner; NSMapTable* _behaviorsAndBehaviorContexts; } @property (assign,nonatomic,__weak) id AVKitOwner; //@synthesize AVKitOwner=_AVKitOwner - In the implementation block @property (nonatomic,readonly) NSMapTable * behaviorsAndBehaviorContexts; //@synthesize behaviorsAndBehaviorContexts=_behaviorsAndBehaviorContexts - In the implementation block -(id)behaviors; -(id)initWithAVKitOwner:(id)arg1 ; -(void)addBehavior:(id)arg1 ; -(void)removeBehavior:(id)arg1 ; -(void)enumerateAllBehaviorsUsingBlock:(/*^block*/id)arg1 ; -(void)enumerateAllBehaviorsConformingToProtocol:(id)arg1 usingBlock:(/*^block*/id)arg2 ; -(id)behaviorOfClass:(Class)arg1 ; -(void)enumerateAllBehaviorContextsUsingBlock:(/*^block*/id)arg1 ; -(void)enumerateAllBehaviorContextsConformingToProtocol:(id)arg1 usingBlock:(/*^block*/id)arg2 ; -(void)enumerateAllBehaviorContextsImplementingSelector:(SEL)arg1 forProtocol:(id)arg2 usingBlock:(/*^block*/id)arg3 ; -(id)behaviorContextOfClass:(Class)arg1 ; -(id)AVKitOwner; -(void)setAVKitOwner:(id)arg1 ; -(NSMapTable *)behaviorsAndBehaviorContexts; @end
xu0521/xin
xl050224-store-back/src/main/java/com/xuxin/xl050224storeback/service/AddressService.java
<filename>xl050224-store-back/src/main/java/com/xuxin/xl050224storeback/service/AddressService.java<gh_stars>1-10 package com.xuxin.xl050224storeback.service; import com.xuxin.xl050224storeback.entity.Address; import java.util.List; public interface AddressService { Integer create(Address address); List<Address> getAddressList(Integer customerId); Address getById(Integer addressId); void update(Address address); void delete(Integer addressId); }
fjmk/go-chrome
tot/cdtp/tethering/command.go
package tethering /* BindParams represents Tethering.bind parameters. https://chromedevtools.github.io/devtools-protocol/tot/Tethering/#method-bind */ type BindParams struct { // Port number to bind. Port int `json:"port"` } /* BindResult represents the result of calls to Tethering.bind. https://chromedevtools.github.io/devtools-protocol/tot/Tethering/#method-bind */ type BindResult struct { // Error information related to executing this method Err error `json:"-"` } /* UnbindParams represents Tethering.unbind parameters. https://chromedevtools.github.io/devtools-protocol/tot/Tethering/#method-unbind */ type UnbindParams struct { // Port number to unbind. Port int `json:"port"` } /* UnbindResult represents the result of calls to Tethering.unbind. https://chromedevtools.github.io/devtools-protocol/tot/Tethering/#method-unbind */ type UnbindResult struct { // Error information related to executing this method Err error `json:"-"` }
untillpro/airc-shell3-plugin-core
src/components/common/plan/TableAreaList.js
<filename>src/components/common/plan/TableAreaList.js /* * Copyright (c) 2020-present unTill Pro, Ltd. */ import _ from 'lodash'; import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import cn from 'classnames'; import { translate as t, Button, Empty, Toggler } from 'airc-shell-core'; import { STATE_FIELD_NAME, STATUS_ACTIVE } from '../../../const/Common'; import TableAreaListRow from './TableAreaListRow'; import { PlusOutlined } from '@ant-design/icons'; class TableAreaList extends PureComponent { constructor(props) { super(props); this.state = { closed: this._isClosed(), showHidden: false }; this.handleListToggle = this.handleListToggle.bind(this); this.handleHiddenChage = this.handleHiddenChage.bind(this); } _isClosed() { return !!localStorage.getItem('table_list_closed'); } handleListToggle() { const { closed } = this.state; this.setState({ closed: !closed }); localStorage.setItem('table_list_closed', !closed); } handleHiddenChage() { const { showHidden } = this.state; this.setState({ showHidden: !showHidden }); } renderToggler() { const { toggleable } = this.props; const { closed } = this.state; if (!toggleable) return null; return ( <div className="table-area-list-toggler" onClick={this.handleListToggle}> {closed ? 'Open' : 'Close'} </div> ); } renderHeader() { const { showHidden } = this.state; const { tables } = this.props; const totalCount = showHidden ? tables.length || 0 : _.reduce(tables, (count, t) => count += t && t[STATE_FIELD_NAME] === STATUS_ACTIVE ? 1 : 0, 0) return ( <div className="table-area-list-header"> <Toggler label={t("Show removed", "form")} left onChange={this.handleHiddenChage} checked={showHidden} /> <div className="total">Tables: {totalCount}</div> </div> ); } renderList() { const { showHidden } = this.state; const { tables, onEdit, onCopy, onDelete, onPress, currentTable, numberProp } = this.props; if (!_.isArray(tables) || _.size(tables) === 0) { return <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />; } const tableNumbers = {}; _.forEach(tables, (table, index) => { table.index = index; tableNumbers[table[numberProp]] = tableNumbers[table[numberProp]] ? tableNumbers[table[numberProp]] + 1 : 1; }); const tablesSorted = _.sortBy(tables, (o) => o[numberProp]); return _.map(tablesSorted, (table, index) => { let num = table[numberProp]; if (_.isNil(table) || (!showHidden && table[STATE_FIELD_NAME] !== STATUS_ACTIVE)) return null; return <TableAreaListRow key={`table_${index}_${num}_${table.id}_${table[STATE_FIELD_NAME]}`} current={currentTable === table.index} {...table} //index={index} onEdit={onEdit} onCopy={onCopy} onDelete={onDelete} onPress={onPress} error={tableNumbers[num] > 1} />; } ); } renderAddButton() { const { onAdd } = this.props; return ( <div className="table-area-list-button"> <Button onClick={onAdd} icon={<PlusOutlined />} type="primary" block > {t("Add table", "form")} </Button> </div> ); } render() { const { toggleable } = this.props; const { closed } = this.state; return ( <div className={cn("table-area-list", { "__is_hidden": closed && toggleable })}> {this.renderToggler()} {this.renderHeader()} <div className="table-area-list-container"> {this.renderList()} </div> {this.renderAddButton()} </div> ); } } TableAreaList.propTypes = { tables: PropTypes.arrayOf(PropTypes.object), onAdd: PropTypes.func.isRequired, onEdit: PropTypes.func.isRequired, onCopy: PropTypes.func.isRequired, onDelete: PropTypes.func.isRequired, onPress: PropTypes.func.isRequired, }; export default TableAreaList;
hawkhai/pyinstaller
tests/functional/modules/pyi_import_pyqt_uic_port/PyQt5/uic/port_v3/test.py
__pyinstaller_fake_module_marker__ = '__pyinstaller_fake_module_marker__' import sys assert sys.version_info[0] >= 3, "this does not work for Python 2"
pacokwon/leetcode
solutions/617.py
# Merge Two Binary Trees # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def mergeTrees(self, root1, root2): if root1 is None: return root2 if root2 is None: return root1 newLeft = self.mergeTrees(root1.left, root2.left) newRight = self.mergeTrees(root1.right, root2.right) newTreeNode = TreeNode(root1.val + root2.val, newLeft, newRight) return newTreeNode if __name__ == "__main__": sol = Solution() root1 = TreeNode(1, TreeNode(3, TreeNode(5)), TreeNode(2)) root2 = TreeNode(2, TreeNode(1, None, TreeNode(4)), TreeNode(3, None, TreeNode(7))) root1 = None root2 = None print(sol.mergeTrees(root1, root2))
zhangkn/iOS14Header
System/Library/PrivateFrameworks/HealthUI.framework/HKOverlayRoomViewControllerIntegratedContext.h
<filename>System/Library/PrivateFrameworks/HealthUI.framework/HKOverlayRoomViewControllerIntegratedContext.h /* * This header is generated by classdump-dyld 1.0 * on Sunday, September 27, 2020 at 11:43:10 AM Mountain Standard Time * Operating System: Version 14.0 (Build 18A373) * Image Source: /System/Library/PrivateFrameworks/HealthUI.framework/HealthUI * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. */ #import <libobjc.A.dylib/HKOverlayContext.h> @class HKInteractiveChartOverlayViewController, HKOverlayRoomApplicationItems, HKSampleType, NSMutableDictionary, HKDisplayTypeContextItem, NSString; @interface HKOverlayRoomViewControllerIntegratedContext : NSObject <HKOverlayContext> { long long _overlayMode; HKInteractiveChartOverlayViewController* _overlayChartController; HKOverlayRoomApplicationItems* _applicationItems; HKSampleType* _monitoringSampleType; NSMutableDictionary* _displayTypesForTimeScopes; HKDisplayTypeContextItem* _lastUpdatedContextItem; } @property (nonatomic,retain) HKInteractiveChartOverlayViewController * overlayChartController; //@synthesize overlayChartController=_overlayChartController - In the implementation block @property (nonatomic,retain) HKOverlayRoomApplicationItems * applicationItems; //@synthesize applicationItems=_applicationItems - In the implementation block @property (nonatomic,retain) HKSampleType * monitoringSampleType; //@synthesize monitoringSampleType=_monitoringSampleType - In the implementation block @property (nonatomic,retain) NSMutableDictionary * displayTypesForTimeScopes; //@synthesize displayTypesForTimeScopes=_displayTypesForTimeScopes - In the implementation block @property (nonatomic,retain) HKDisplayTypeContextItem * lastUpdatedContextItem; //@synthesize lastUpdatedContextItem=_lastUpdatedContextItem - In the implementation block @property (assign,nonatomic) long long overlayMode; //@synthesize overlayMode=_overlayMode - In the implementation block @property (readonly) unsigned long long hash; @property (readonly) Class superclass; @property (copy,readonly) NSString * description; @property (copy,readonly) NSString * debugDescription; +(id)distributionContextWithStyle:(long long)arg1 namedPredicate:(id)arg2 overlayChartController:(id)arg3 applicationItems:(id)arg4 optionalDelegate:(id)arg5 options:(long long)arg6 mode:(long long)arg7 ; +(id)quantityContextWithIdentifier:(id)arg1 overlayChartController:(id)arg2 applicationItems:(id)arg3 optionalDelegate:(id)arg4 seriesOptions:(long long)arg5 mode:(long long)arg6 ; -(HKOverlayRoomApplicationItems *)applicationItems; -(id)contextItemForLastUpdate; -(void)updateContextItemForDateInterval:(id)arg1 timeScope:(long long)arg2 completion:(/*^block*/id)arg3 ; -(id)sampleTypeForDateRangeUpdates; -(id)overlayDisplayTypeForTimeScope:(long long)arg1 ; -(void)setApplicationItems:(HKOverlayRoomApplicationItems *)arg1 ; -(id)initWithOverlayChartController:(id)arg1 applicationItems:(id)arg2 mode:(long long)arg3 ; -(id)valueString:(id)arg1 applicationItems:(id)arg2 representativeDisplayType:(id)arg3 ; -(id)unitString:(id)arg1 applicationItems:(id)arg2 representativeDisplayType:(id)arg3 ; -(id)representativeDisplayType; -(long long)overlayMode; -(HKInteractiveChartOverlayViewController *)overlayChartController; -(id)buildContextItemWithValue:(id)arg1 unit:(id)arg2 valueContext:(id)arg3 forTimeScope:(long long)arg4 ; -(id)buildOverlayDisplayTypeForTimeScope:(long long)arg1 ; -(void)fetchCachedDataForTimeScope:(long long)arg1 dateInterval:(id)arg2 completion:(/*^block*/id)arg3 ; -(id)valueContextString:(id)arg1 applicationItems:(id)arg2 representativeDisplayType:(id)arg3 ; -(id)_minMaxValueFromChartPoints:(id)arg1 displayType:(id)arg2 unitPreferenceController:(id)arg3 ; -(HKSampleType *)monitoringSampleType; -(id)_buildMonitoringSampleType; -(void)setMonitoringSampleType:(HKSampleType *)arg1 ; -(NSMutableDictionary *)displayTypesForTimeScopes; -(BOOL)_obsoleteDateRange:(id)arg1 ; -(void)setLastUpdatedContextItem:(HKDisplayTypeContextItem *)arg1 ; -(HKDisplayTypeContextItem *)lastUpdatedContextItem; -(void)setOverlayMode:(long long)arg1 ; -(void)setOverlayChartController:(HKInteractiveChartOverlayViewController *)arg1 ; -(void)setDisplayTypesForTimeScopes:(NSMutableDictionary *)arg1 ; @end
dataspot/dgp-app
etl_server/files/controllers.py
import calendar from urllib.parse import unquote_plus import boto3 from botocore.exceptions import ClientError import json import tempfile import shutil from dgp_oauth2.models import get_user class Controllers(): def __init__(self, bucket_name, endpoint_url, aws_access_key_id, aws_secret_access_key, aws_region): kw = dict( endpoint_url=endpoint_url, aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, region_name=aws_region ) self.s3client = boto3.client('s3', **kw) self.s3 = boto3.resource('s3', **kw) self.bucket = self.s3.Bucket(bucket_name) exists = False try: exists = self.bucket.creation_date is not None except: pass if not exists: try: self.bucket.create(ACL='private') except: # Avoid race conditions pass @staticmethod def ownerid(obj): return obj.metadata.get('Ownerid') or obj.metadata.get('ownerid') @staticmethod def ownername(obj): return obj.metadata.get('Ownername') or obj.metadata.get('ownername') def list_files(self, user=None): filenames = [ unquote_plus(o.key) for o in self.bucket.objects.all() or [] ] objects = [ self.bucket.Object(f) for f in filenames ] ret = [ ( o.key, o.last_modified, o.content_length, self.ownerid(o), self.ownername(o), ) for o in objects ] ret = [ dict( filename=filename, last_modified=calendar.timegm(last_modified.timetuple()), size=size, owner_id=ownerid, owner_name=ownername, ) for filename, last_modified, size, ownerid, ownername in ret if user in (None, ownerid) ] return dict( success=True, result=ret ) def download_file(self, filename): return self.s3client.generate_presigned_url( 'get_object', dict(Bucket=self.bucket.name, Key=filename), HttpMethod='GET' ) def upload_file(self, file_obj, filename, user, admin=False): profile = get_user(user) username = profile.get('name') o = self.bucket.Object(filename) allowed = False try: if admin or self.ownerid(o) == user: allowed = True except ClientError: allowed = True if allowed: metadata = dict( ownerid=user, ownername=username ) with tempfile.NamedTemporaryFile() as t: shutil.copyfileobj(file_obj.stream, t) t.flush() t.seek(0) self.s3client.put_object( Body=t, Bucket=self.bucket.name, Key=filename, ContentType=file_obj.mimetype or 'application/octet-stream', Metadata=metadata, ACL='private' ) return dict( success=True, ) else: return dict( success=False ) def delete_file(self, filename, user, admin=False): o = self.bucket.Object(filename) try: if admin or self.ownerid(o) == user: o.delete() return dict( success=True, ) except: pass return dict( success=False )
vault-the/changes
changes/jobs/delete_old_data.py
<filename>changes/jobs/delete_old_data.py from __future__ import absolute_import, print_function import logging from datetime import datetime, timedelta from changes.config import db, statsreporter from changes.models.project import Project, ProjectOptionsHelper from changes.models.test import TestCase DEFAULT_TEST_RETENTION_DAYS = 120 MINIMUM_TEST_RETENTION_DAYS = 7 logger = logging.getLogger('delete-old-data') def clean_project_tests(project, from_date, chunk_size, num_days=None): # type: (Project, datetime, timedelta, int) -> int """Deletes old tests from a project and returns number of rows deleted. An old test is a test older than num_days or the project's history.test-retention-days compared to the `from_date` chunk_size bounds how far to back to look from num_days ago to have some control over how long this function runs. """ if chunk_size <= timedelta(minutes=0): logger.warning('The minutes worth of tests to delete is %s but it must be positive.' % chunk_size) return 0 test_retention_days = num_days or float( ProjectOptionsHelper.get_option(project, 'history.test-retention-days') or DEFAULT_TEST_RETENTION_DAYS ) if test_retention_days < MINIMUM_TEST_RETENTION_DAYS: logger.warning( 'Test retention days for project %s is %d, which is less than the minimum of %d. ' 'Not cleaning tests for this project.' % (project.slug, test_retention_days, MINIMUM_TEST_RETENTION_DAYS)) return 0 test_delete_date = from_date - timedelta(days=test_retention_days) test_delete_date_limit = test_delete_date - chunk_size rows_deleted = db.session.query(TestCase).filter( TestCase.project_id == project.id, TestCase.date_created < test_delete_date, TestCase.date_created >= test_delete_date_limit, ).delete() db.session.commit() statsreporter.stats().incr('count_tests_deleted', rows_deleted) return rows_deleted def delete_old_data_10m(): # type: () -> None delete_old_data_limited(timedelta(minutes=10), datetime.utcnow()) def delete_old_data_5h_delayed(): # type: () -> None delete_old_data_limited(timedelta(hours=5), datetime.utcnow() - timedelta(hours=1)) def delete_old_data_1h(): # type: () -> None delete_old_data_limited(timedelta(hours=1), datetime.utcnow()) def delete_old_data(): # type: () -> None delete_old_data_1h() def delete_old_data_limited(chunk_size, from_date=None): # type: (timedelta, datetime) -> None if from_date is None: from_date = datetime.utcnow() try: projects = Project.query.all() for project in projects: clean_project_tests(project, from_date, chunk_size) except Exception as e: logger.exception(e.message)
tfermm/plymouth-webapp
webapp/my/js/konami.js
<filename>webapp/my/js/konami.js // Hehe. if ( window.addEventListener ) { var kkeys = [], konami = "38,38,40,40,37,39,37,39,66,65"; var konami2 = "38,38,38,38,40,40,40,40,37,37,39,39,37,37,39,39,66,66,65,65"; var konami_on = false; window.addEventListener("keydown", function(e){ if( !konami_on ) { kkeys.push( e.keyCode ); if ( kkeys.toString().indexOf( konami ) >= 0 || kkeys.toString().indexOf( konami2 ) >= 0){ konami_on = true; var s = document.createElement('script');s.type='text/javascript';document.body.appendChild(s);s.src=HOST + '/webapp/my/js/asteroids.min.js';void(0); } } }, true); }
pumelotea/happyboot-api
happyboot-service/src/main/java/org/happykit/happyboot/sys/factory/SysMsgFactory.java
package org.happykit.happyboot.sys.factory; import org.happykit.happyboot.sys.model.entity.SysMsgDO; import org.happykit.happyboot.sys.model.form.SysMsgForm; import org.mapstruct.Mapper; import org.mapstruct.factory.Mappers; /** * 系统通告表对象转换工厂 * * @author cly * @version 1.0 2020/07/06 */ @Mapper public interface SysMsgFactory { SysMsgFactory INSTANCE = Mappers.getMapper(SysMsgFactory.class); /** * 表单转实体对象 * * @param form * @return */ SysMsgDO form2Do(SysMsgForm form); }
danniesim/cpp_volume_rendering
cppvolrend/structured/rc1pdosct/conegaussiansampler.h
<reponame>danniesim/cpp_volume_rendering /** * Cone Sampling with Gaussian Integrals .h * * <NAME> * . <EMAIL> **************************************************** * Cone directions using circle packing in a circle: * . https://en.wikipedia.org/wiki/Circle_packing_in_a_circle **/ #ifndef CONE_DIRECTIONAL_GAUSSIAN_SAMPLER_H #define CONE_DIRECTIONAL_GAUSSIAN_SAMPLER_H #include <glm/glm.hpp> #include <gl_utils/texture1d.h> #include <vector> #define D_HEMISPHERE_CONE_DIV_3 (1.0 + (2.0 / glm::sqrt(3.0))) // 2.158455 #define D_HEMISPHERE_CONE_DIV_7 3.010000 // 3.010000 class ConeGaussianSampler { public: typedef struct IntervalsInfo { IntervalsInfo (double position, double distance) { s_position = position; s_distance = distance; } double s_position; double s_distance; } IntervalsInfo; // info for each section typedef struct SectionInfo { SectionInfo (int _number_of_gaussians, double _distance_from_origin, double _sec_half_step, double _cone_radius, double _sampled_gaussian_sigma) { number_of_gaussians = _number_of_gaussians; distance_from_origin = _distance_from_origin; sec_half_step = _sec_half_step; cone_radius = _cone_radius; sampled_gaussian_sigma = _sampled_gaussian_sigma; } int number_of_gaussians; double distance_from_origin; double sec_half_step; double cone_radius; double sampled_gaussian_sigma; double coefficient_cut_radius; double coefficient_rescale; double d_integral; double step_integral; double mip_map_level; double amplitude; } SectionInfo; enum CONEPACKING { _1 = 0, _3 = 1, _7 = 2, }; int gaussian_samples_1; int gaussian_samples_3; int gaussian_samples_7; public: ConeGaussianSampler (); ~ConeGaussianSampler (); // \ angle | / // \------| / // \ | / // \ | / // \ | / // \ | / // \ | / // \|/ // * float GetConeHalfAngle (); void SetConeHalfAngle (float angle); void DecreaseConeHalfAngle (); void IncreaseConeHalfAngle (); float GetInitialStep (); void SetInitialStep (float istep); CONEPACKING GetMaxGaussianPacking (); void SetMaxGaussianPacking (CONEPACKING gpk); int GetMaxGaussianPackingInt (); void SetMaxGaussianPacking (int p); void PreviousGaussianPacking (); void NextGaussianPacking (); std::string GetCurrentMaxGaussianPackingStr (); float GetCoveredDistance (); void SetCoveredDistance (float midist); float GetIntegrationHalfStepMultiplier (); void SetIntegrationHalfStepMultiplier (float rdir_sstep_mul); float GetGaussianSigmaLimitMultiplier (); void SetGaussianSigmaLimitMultiplier (float s); int GetNumberOfComputedConeSections (); gl::Texture1D* GetConeSectionsInfoTex (); std::vector<SectionInfo> GetConeSectionsInfoVec (); void ComputeConeIntegrationSteps (double min_sg_gaussian); double GetRay3AdjacentWeight (); double GetRay7AdjacentWeight (); glm::vec3 Get3ConeRayID (int i); glm::vec3 Get7ConeRayID (int i); void SetUIWeightPercentage (float a); bool cut_on_ray_direction; glm::vec3 ray3_axis[3]; double ray3_adj_weight; glm::vec3 ray7_axis[7]; double ray7_adj_weight; float cone_half_angle; float initial_step; CONEPACKING max_gaussian_packing; float covered_distance; float ui_weight_percentage; float d_sigma; float r_sigma; private: std::vector<SectionInfo> data_cone_sectionsinfo; std::vector<IntervalsInfo> data_cone_intervalsinfo; private: void ComputeAdditionalInfo (double min_sg_gaussian); double GaussianEval (double x, double sig); double IntegrateGaussian (double min_sg_gaussian, double cone_radius); bool AddGaussianSampleStep (double curr_pos, double sg_gaussian, int *n_gaussians); bool AddGaussianSampleStepWith3 (double curr_pos, double sg_gaussian, int *n_gaussians); bool AddGaussianSampleStepWith7 (double curr_pos, double sg_gaussian, int *n_gaussians); }; #endif
danielogen/msc_research
selected projects/desktop/mars-sim-v3.1.0/mars-sim-core/org/mars_sim/msp/core/person/Crew.java
<gh_stars>0 /** * Mars Simulation Project * Crew.java * @version 3.1.0 2017-01-24 * @author <NAME> */ package org.mars_sim.msp.core.person; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class Crew implements Serializable { /** default serial id. */ private static final long serialVersionUID = 1L; //private static Logger logger = Logger.getLogger(Crew.class.getName()); private String name; private String destination; //Set<Member> team = new HashSet<>(); List<Member> team = new ArrayList<>(); public Crew(String name) { this.name = name; } public void add(Member m) { team.add(m); } //public void add(Set<Member> members) { // team = members; //} //public void add(List<Member> members) { // members = members; //} //public Set<Member> getTeam() { // return team; //} public List<Member> getTeam() { return team; } public String getName() { return name; } public void setDestination(String value) { destination = value; // TODO: set destination for all members } public String getDestination() { return destination; } }
bibidu/react-to-react-native
packages/core/__test__/mixin-style/output/index.js
// // Created by node lib `react-to-react-native`. // import React from 'react'; import { View, Text } from 'react-native' import * as _util from './tools.js' import styles from './stylesheet.js' class App extends React.Component { activeCls = type => `${type}-btn`; activeStyle = type => ({ padding: type ? "15px" : "20px", border: "1px solid #ccc" }); render() { const { type } = this.props; const defaultStyle = { marginTop: 5 }; const activeWrapper = "abc"; return ( <View UI="UIDiv" style={styles.$merge1}> <View UI="UIDiv2" style={[ styles.$merge2, _util.extend(styles[`${this.activeCls(type)}`]), _util.extend(styles[`${activeWrapper}`]), _util.extend(Object.assign(defaultStyle, this.activeStyle(type))) ]} > <Text UI="UISpan" style={styles.$inherit3}> 123 </Text> </View> </View> ); } } export default App;
jorgdz/svc-infrastructure
EnviarEmailUS/src/main/java/com/righttek/us/enviaremail/event/TopicConsumer.java
<filename>EnviarEmailUS/src/main/java/com/righttek/us/enviaremail/event/TopicConsumer.java<gh_stars>0 package com.righttek.us.enviaremail.event; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.kafka.annotation.KafkaListener; import org.springframework.messaging.MessageHeaders; import org.springframework.messaging.handler.annotation.Headers; import org.springframework.messaging.handler.annotation.Payload; import org.springframework.stereotype.Component; import com.fasterxml.jackson.databind.ObjectMapper; import com.righttek.modelocanonico.email.EmailNotificacionAtraso; import com.righttek.modelocanonico.email.EmailSimple; import com.righttek.us.enviaremail.service.contract.IEnviarEmailSvc; /** * * @author JORGE * */ @Component public class TopicConsumer { private static final Logger LOG = LoggerFactory.getLogger(TopicConsumer.class); @Autowired IEnviarEmailSvc serviceEnviarEmail; @Autowired ObjectMapper objectMapper; @KafkaListener(topics = "EmailSimpleEvent", groupId = "myGroup") public void listenEmailSimple (@Payload String message, @Headers MessageHeaders headers) { LOG.info("Datos recibidos={}", message); headers.keySet().forEach(key -> LOG.info("{}: {}", key, headers.get(key))); try { EmailSimple msg = objectMapper.readValue(message, EmailSimple.class); this.serviceEnviarEmail.enviarEmailSimple(msg); } catch (Exception e) { LOG.error(e.getMessage()); } } @KafkaListener(topics = "NotificacionAtrasoEvent", groupId = "myGroup") public void listenNotificacionAtraso (@Payload String message, @Headers MessageHeaders headers) { LOG.info("Datos recibidos={}", message); headers.keySet().forEach(key -> LOG.info("{}: {}", key, headers.get(key))); try { EmailNotificacionAtraso msg = objectMapper.readValue(message, EmailNotificacionAtraso.class); this.serviceEnviarEmail.enviarNotificacionAtraso(msg); } catch (Exception e) { LOG.error(e.getMessage()); } } }
jj1232727/system_call
linux-3.16/drivers/net/wireless/mwifiex/scan.c
/* * Marvell Wireless LAN device driver: scan ioctl and command handling * * Copyright (C) 2011, Marvell International Ltd. * * This software file (the "File") is distributed by Marvell International * Ltd. under the terms of the GNU General Public License Version 2, June 1991 * (the "License"). You may use, redistribute and/or modify this File in * accordance with the terms and conditions of the License, a copy of which * is available by writing to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA or on the * worldwide web at http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. * * THE FILE IS DISTRIBUTED AS-IS, WITHOUT WARRANTY OF ANY KIND, AND THE * IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE * ARE EXPRESSLY DISCLAIMED. The License provides additional details about * this warranty disclaimer. */ #include "decl.h" #include "ioctl.h" #include "util.h" #include "fw.h" #include "main.h" #include "11n.h" #include "cfg80211.h" /* The maximum number of channels the firmware can scan per command */ #define MWIFIEX_MAX_CHANNELS_PER_SPECIFIC_SCAN 14 #define MWIFIEX_DEF_CHANNELS_PER_SCAN_CMD 4 /* Memory needed to store a max sized Channel List TLV for a firmware scan */ #define CHAN_TLV_MAX_SIZE (sizeof(struct mwifiex_ie_types_header) \ + (MWIFIEX_MAX_CHANNELS_PER_SPECIFIC_SCAN \ *sizeof(struct mwifiex_chan_scan_param_set))) /* Memory needed to store supported rate */ #define RATE_TLV_MAX_SIZE (sizeof(struct mwifiex_ie_types_rates_param_set) \ + HOSTCMD_SUPPORTED_RATES) /* Memory needed to store a max number/size WildCard SSID TLV for a firmware scan */ #define WILDCARD_SSID_TLV_MAX_SIZE \ (MWIFIEX_MAX_SSID_LIST_LENGTH * \ (sizeof(struct mwifiex_ie_types_wildcard_ssid_params) \ + IEEE80211_MAX_SSID_LEN)) /* Maximum memory needed for a mwifiex_scan_cmd_config with all TLVs at max */ #define MAX_SCAN_CFG_ALLOC (sizeof(struct mwifiex_scan_cmd_config) \ + sizeof(struct mwifiex_ie_types_num_probes) \ + sizeof(struct mwifiex_ie_types_htcap) \ + CHAN_TLV_MAX_SIZE \ + RATE_TLV_MAX_SIZE \ + WILDCARD_SSID_TLV_MAX_SIZE) union mwifiex_scan_cmd_config_tlv { /* Scan configuration (variable length) */ struct mwifiex_scan_cmd_config config; /* Max allocated block */ u8 config_alloc_buf[MAX_SCAN_CFG_ALLOC]; }; enum cipher_suite { CIPHER_SUITE_TKIP, CIPHER_SUITE_CCMP, CIPHER_SUITE_MAX }; static u8 mwifiex_wpa_oui[CIPHER_SUITE_MAX][4] = { { 0x00, 0x50, 0xf2, 0x02 }, /* TKIP */ { 0x00, 0x50, 0xf2, 0x04 }, /* AES */ }; static u8 mwifiex_rsn_oui[CIPHER_SUITE_MAX][4] = { { 0x00, 0x0f, 0xac, 0x02 }, /* TKIP */ { 0x00, 0x0f, 0xac, 0x04 }, /* AES */ }; /* * This function parses a given IE for a given OUI. * * This is used to parse a WPA/RSN IE to find if it has * a given oui in PTK. */ static u8 mwifiex_search_oui_in_ie(struct ie_body *iebody, u8 *oui) { u8 count; count = iebody->ptk_cnt[0]; /* There could be multiple OUIs for PTK hence 1) Take the length. 2) Check all the OUIs for AES. 3) If one of them is AES then pass success. */ while (count) { if (!memcmp(iebody->ptk_body, oui, sizeof(iebody->ptk_body))) return MWIFIEX_OUI_PRESENT; --count; if (count) iebody = (struct ie_body *) ((u8 *) iebody + sizeof(iebody->ptk_body)); } pr_debug("info: %s: OUI is not found in PTK\n", __func__); return MWIFIEX_OUI_NOT_PRESENT; } /* * This function checks if a given OUI is present in a RSN IE. * * The function first checks if a RSN IE is present or not in the * BSS descriptor. It tries to locate the OUI only if such an IE is * present. */ static u8 mwifiex_is_rsn_oui_present(struct mwifiex_bssdescriptor *bss_desc, u32 cipher) { u8 *oui; struct ie_body *iebody; u8 ret = MWIFIEX_OUI_NOT_PRESENT; if (((bss_desc->bcn_rsn_ie) && ((*(bss_desc->bcn_rsn_ie)). ieee_hdr.element_id == WLAN_EID_RSN))) { iebody = (struct ie_body *) (((u8 *) bss_desc->bcn_rsn_ie->data) + RSN_GTK_OUI_OFFSET); oui = &mwifiex_rsn_oui[cipher][0]; ret = mwifiex_search_oui_in_ie(iebody, oui); if (ret) return ret; } return ret; } /* * This function checks if a given OUI is present in a WPA IE. * * The function first checks if a WPA IE is present or not in the * BSS descriptor. It tries to locate the OUI only if such an IE is * present. */ static u8 mwifiex_is_wpa_oui_present(struct mwifiex_bssdescriptor *bss_desc, u32 cipher) { u8 *oui; struct ie_body *iebody; u8 ret = MWIFIEX_OUI_NOT_PRESENT; if (((bss_desc->bcn_wpa_ie) && ((*(bss_desc->bcn_wpa_ie)).vend_hdr.element_id == WLAN_EID_VENDOR_SPECIFIC))) { iebody = (struct ie_body *) bss_desc->bcn_wpa_ie->data; oui = &mwifiex_wpa_oui[cipher][0]; ret = mwifiex_search_oui_in_ie(iebody, oui); if (ret) return ret; } return ret; } /* * This function compares two SSIDs and checks if they match. */ s32 mwifiex_ssid_cmp(struct cfg80211_ssid *ssid1, struct cfg80211_ssid *ssid2) { if (!ssid1 || !ssid2 || (ssid1->ssid_len != ssid2->ssid_len)) return -1; return memcmp(ssid1->ssid, ssid2->ssid, ssid1->ssid_len); } /* * This function checks if wapi is enabled in driver and scanned network is * compatible with it. */ static bool mwifiex_is_bss_wapi(struct mwifiex_private *priv, struct mwifiex_bssdescriptor *bss_desc) { if (priv->sec_info.wapi_enabled && (bss_desc->bcn_wapi_ie && ((*(bss_desc->bcn_wapi_ie)).ieee_hdr.element_id == WLAN_EID_BSS_AC_ACCESS_DELAY))) { return true; } return false; } /* * This function checks if driver is configured with no security mode and * scanned network is compatible with it. */ static bool mwifiex_is_bss_no_sec(struct mwifiex_private *priv, struct mwifiex_bssdescriptor *bss_desc) { if (!priv->sec_info.wep_enabled && !priv->sec_info.wpa_enabled && !priv->sec_info.wpa2_enabled && ((!bss_desc->bcn_wpa_ie) || ((*(bss_desc->bcn_wpa_ie)).vend_hdr.element_id != WLAN_EID_VENDOR_SPECIFIC)) && ((!bss_desc->bcn_rsn_ie) || ((*(bss_desc->bcn_rsn_ie)).ieee_hdr.element_id != WLAN_EID_RSN)) && !priv->sec_info.encryption_mode && !bss_desc->privacy) { return true; } return false; } /* * This function checks if static WEP is enabled in driver and scanned network * is compatible with it. */ static bool mwifiex_is_bss_static_wep(struct mwifiex_private *priv, struct mwifiex_bssdescriptor *bss_desc) { if (priv->sec_info.wep_enabled && !priv->sec_info.wpa_enabled && !priv->sec_info.wpa2_enabled && bss_desc->privacy) { return true; } return false; } /* * This function checks if wpa is enabled in driver and scanned network is * compatible with it. */ static bool mwifiex_is_bss_wpa(struct mwifiex_private *priv, struct mwifiex_bssdescriptor *bss_desc) { if (!priv->sec_info.wep_enabled && priv->sec_info.wpa_enabled && !priv->sec_info.wpa2_enabled && ((bss_desc->bcn_wpa_ie) && ((*(bss_desc->bcn_wpa_ie)). vend_hdr.element_id == WLAN_EID_VENDOR_SPECIFIC)) /* * Privacy bit may NOT be set in some APs like * LinkSys WRT54G && bss_desc->privacy */ ) { dev_dbg(priv->adapter->dev, "info: %s: WPA:" " wpa_ie=%#x wpa2_ie=%#x WEP=%s WPA=%s WPA2=%s " "EncMode=%#x privacy=%#x\n", __func__, (bss_desc->bcn_wpa_ie) ? (*(bss_desc->bcn_wpa_ie)). vend_hdr.element_id : 0, (bss_desc->bcn_rsn_ie) ? (*(bss_desc->bcn_rsn_ie)). ieee_hdr.element_id : 0, (priv->sec_info.wep_enabled) ? "e" : "d", (priv->sec_info.wpa_enabled) ? "e" : "d", (priv->sec_info.wpa2_enabled) ? "e" : "d", priv->sec_info.encryption_mode, bss_desc->privacy); return true; } return false; } /* * This function checks if wpa2 is enabled in driver and scanned network is * compatible with it. */ static bool mwifiex_is_bss_wpa2(struct mwifiex_private *priv, struct mwifiex_bssdescriptor *bss_desc) { if (!priv->sec_info.wep_enabled && !priv->sec_info.wpa_enabled && priv->sec_info.wpa2_enabled && ((bss_desc->bcn_rsn_ie) && ((*(bss_desc->bcn_rsn_ie)).ieee_hdr.element_id == WLAN_EID_RSN))) { /* * Privacy bit may NOT be set in some APs like * LinkSys WRT54G && bss_desc->privacy */ dev_dbg(priv->adapter->dev, "info: %s: WPA2: " " wpa_ie=%#x wpa2_ie=%#x WEP=%s WPA=%s WPA2=%s " "EncMode=%#x privacy=%#x\n", __func__, (bss_desc->bcn_wpa_ie) ? (*(bss_desc->bcn_wpa_ie)). vend_hdr.element_id : 0, (bss_desc->bcn_rsn_ie) ? (*(bss_desc->bcn_rsn_ie)). ieee_hdr.element_id : 0, (priv->sec_info.wep_enabled) ? "e" : "d", (priv->sec_info.wpa_enabled) ? "e" : "d", (priv->sec_info.wpa2_enabled) ? "e" : "d", priv->sec_info.encryption_mode, bss_desc->privacy); return true; } return false; } /* * This function checks if adhoc AES is enabled in driver and scanned network is * compatible with it. */ static bool mwifiex_is_bss_adhoc_aes(struct mwifiex_private *priv, struct mwifiex_bssdescriptor *bss_desc) { if (!priv->sec_info.wep_enabled && !priv->sec_info.wpa_enabled && !priv->sec_info.wpa2_enabled && ((!bss_desc->bcn_wpa_ie) || ((*(bss_desc->bcn_wpa_ie)). vend_hdr.element_id != WLAN_EID_VENDOR_SPECIFIC)) && ((!bss_desc->bcn_rsn_ie) || ((*(bss_desc->bcn_rsn_ie)).ieee_hdr.element_id != WLAN_EID_RSN)) && !priv->sec_info.encryption_mode && bss_desc->privacy) { return true; } return false; } /* * This function checks if dynamic WEP is enabled in driver and scanned network * is compatible with it. */ static bool mwifiex_is_bss_dynamic_wep(struct mwifiex_private *priv, struct mwifiex_bssdescriptor *bss_desc) { if (!priv->sec_info.wep_enabled && !priv->sec_info.wpa_enabled && !priv->sec_info.wpa2_enabled && ((!bss_desc->bcn_wpa_ie) || ((*(bss_desc->bcn_wpa_ie)). vend_hdr.element_id != WLAN_EID_VENDOR_SPECIFIC)) && ((!bss_desc->bcn_rsn_ie) || ((*(bss_desc->bcn_rsn_ie)).ieee_hdr.element_id != WLAN_EID_RSN)) && priv->sec_info.encryption_mode && bss_desc->privacy) { dev_dbg(priv->adapter->dev, "info: %s: dynamic " "WEP: wpa_ie=%#x wpa2_ie=%#x " "EncMode=%#x privacy=%#x\n", __func__, (bss_desc->bcn_wpa_ie) ? (*(bss_desc->bcn_wpa_ie)). vend_hdr.element_id : 0, (bss_desc->bcn_rsn_ie) ? (*(bss_desc->bcn_rsn_ie)). ieee_hdr.element_id : 0, priv->sec_info.encryption_mode, bss_desc->privacy); return true; } return false; } /* * This function checks if a scanned network is compatible with the driver * settings. * * WEP WPA WPA2 ad-hoc encrypt Network * enabled enabled enabled AES mode Privacy WPA WPA2 Compatible * 0 0 0 0 NONE 0 0 0 yes No security * 0 1 0 0 x 1x 1 x yes WPA (disable * HT if no AES) * 0 0 1 0 x 1x x 1 yes WPA2 (disable * HT if no AES) * 0 0 0 1 NONE 1 0 0 yes Ad-hoc AES * 1 0 0 0 NONE 1 0 0 yes Static WEP * (disable HT) * 0 0 0 0 !=NONE 1 0 0 yes Dynamic WEP * * Compatibility is not matched while roaming, except for mode. */ static s32 mwifiex_is_network_compatible(struct mwifiex_private *priv, struct mwifiex_bssdescriptor *bss_desc, u32 mode) { struct mwifiex_adapter *adapter = priv->adapter; bss_desc->disable_11n = false; /* Don't check for compatibility if roaming */ if (priv->media_connected && (priv->bss_mode == NL80211_IFTYPE_STATION) && (bss_desc->bss_mode == NL80211_IFTYPE_STATION)) return 0; if (priv->wps.session_enable) { dev_dbg(adapter->dev, "info: return success directly in WPS period\n"); return 0; } if (bss_desc->chan_sw_ie_present) { dev_err(adapter->dev, "Don't connect to AP with WLAN_EID_CHANNEL_SWITCH\n"); return -1; } if (mwifiex_is_bss_wapi(priv, bss_desc)) { dev_dbg(adapter->dev, "info: return success for WAPI AP\n"); return 0; } if (bss_desc->bss_mode == mode) { if (mwifiex_is_bss_no_sec(priv, bss_desc)) { /* No security */ return 0; } else if (mwifiex_is_bss_static_wep(priv, bss_desc)) { /* Static WEP enabled */ dev_dbg(adapter->dev, "info: Disable 11n in WEP mode.\n"); bss_desc->disable_11n = true; return 0; } else if (mwifiex_is_bss_wpa(priv, bss_desc)) { /* WPA enabled */ if (((priv->adapter->config_bands & BAND_GN || priv->adapter->config_bands & BAND_AN) && bss_desc->bcn_ht_cap) && !mwifiex_is_wpa_oui_present(bss_desc, CIPHER_SUITE_CCMP)) { if (mwifiex_is_wpa_oui_present (bss_desc, CIPHER_SUITE_TKIP)) { dev_dbg(adapter->dev, "info: Disable 11n if AES " "is not supported by AP\n"); bss_desc->disable_11n = true; } else { return -1; } } return 0; } else if (mwifiex_is_bss_wpa2(priv, bss_desc)) { /* WPA2 enabled */ if (((priv->adapter->config_bands & BAND_GN || priv->adapter->config_bands & BAND_AN) && bss_desc->bcn_ht_cap) && !mwifiex_is_rsn_oui_present(bss_desc, CIPHER_SUITE_CCMP)) { if (mwifiex_is_rsn_oui_present (bss_desc, CIPHER_SUITE_TKIP)) { dev_dbg(adapter->dev, "info: Disable 11n if AES " "is not supported by AP\n"); bss_desc->disable_11n = true; } else { return -1; } } return 0; } else if (mwifiex_is_bss_adhoc_aes(priv, bss_desc)) { /* Ad-hoc AES enabled */ return 0; } else if (mwifiex_is_bss_dynamic_wep(priv, bss_desc)) { /* Dynamic WEP enabled */ return 0; } /* Security doesn't match */ dev_dbg(adapter->dev, "info: %s: failed: wpa_ie=%#x wpa2_ie=%#x WEP=%s " "WPA=%s WPA2=%s EncMode=%#x privacy=%#x\n", __func__, (bss_desc->bcn_wpa_ie) ? (*(bss_desc->bcn_wpa_ie)).vend_hdr.element_id : 0, (bss_desc->bcn_rsn_ie) ? (*(bss_desc->bcn_rsn_ie)).ieee_hdr.element_id : 0, (priv->sec_info.wep_enabled) ? "e" : "d", (priv->sec_info.wpa_enabled) ? "e" : "d", (priv->sec_info.wpa2_enabled) ? "e" : "d", priv->sec_info.encryption_mode, bss_desc->privacy); return -1; } /* Mode doesn't match */ return -1; } /* * This function creates a channel list for the driver to scan, based * on region/band information. * * This routine is used for any scan that is not provided with a * specific channel list to scan. */ static int mwifiex_scan_create_channel_list(struct mwifiex_private *priv, const struct mwifiex_user_scan_cfg *user_scan_in, struct mwifiex_chan_scan_param_set *scan_chan_list, u8 filtered_scan) { enum ieee80211_band band; struct ieee80211_supported_band *sband; struct ieee80211_channel *ch; struct mwifiex_adapter *adapter = priv->adapter; int chan_idx = 0, i; for (band = 0; (band < IEEE80211_NUM_BANDS) ; band++) { if (!priv->wdev->wiphy->bands[band]) continue; sband = priv->wdev->wiphy->bands[band]; for (i = 0; (i < sband->n_channels) ; i++) { ch = &sband->channels[i]; if (ch->flags & IEEE80211_CHAN_DISABLED) continue; scan_chan_list[chan_idx].radio_type = band; if (user_scan_in && user_scan_in->chan_list[0].scan_time) scan_chan_list[chan_idx].max_scan_time = cpu_to_le16((u16) user_scan_in-> chan_list[0].scan_time); else if (ch->flags & IEEE80211_CHAN_NO_IR) scan_chan_list[chan_idx].max_scan_time = cpu_to_le16(adapter->passive_scan_time); else scan_chan_list[chan_idx].max_scan_time = cpu_to_le16(adapter->active_scan_time); if (ch->flags & IEEE80211_CHAN_NO_IR) scan_chan_list[chan_idx].chan_scan_mode_bitmap |= MWIFIEX_PASSIVE_SCAN; else scan_chan_list[chan_idx].chan_scan_mode_bitmap &= ~MWIFIEX_PASSIVE_SCAN; scan_chan_list[chan_idx].chan_number = (u32) ch->hw_value; if (filtered_scan) { scan_chan_list[chan_idx].max_scan_time = cpu_to_le16(adapter->specific_scan_time); scan_chan_list[chan_idx].chan_scan_mode_bitmap |= MWIFIEX_DISABLE_CHAN_FILT; } chan_idx++; } } return chan_idx; } /* This function appends rate TLV to scan config command. */ static int mwifiex_append_rate_tlv(struct mwifiex_private *priv, struct mwifiex_scan_cmd_config *scan_cfg_out, u8 radio) { struct mwifiex_ie_types_rates_param_set *rates_tlv; u8 rates[MWIFIEX_SUPPORTED_RATES], *tlv_pos; u32 rates_size; memset(rates, 0, sizeof(rates)); tlv_pos = (u8 *)scan_cfg_out->tlv_buf + scan_cfg_out->tlv_buf_len; if (priv->scan_request) rates_size = mwifiex_get_rates_from_cfg80211(priv, rates, radio); else rates_size = mwifiex_get_supported_rates(priv, rates); dev_dbg(priv->adapter->dev, "info: SCAN_CMD: Rates size = %d\n", rates_size); rates_tlv = (struct mwifiex_ie_types_rates_param_set *)tlv_pos; rates_tlv->header.type = cpu_to_le16(WLAN_EID_SUPP_RATES); rates_tlv->header.len = cpu_to_le16((u16) rates_size); memcpy(rates_tlv->rates, rates, rates_size); scan_cfg_out->tlv_buf_len += sizeof(rates_tlv->header) + rates_size; return rates_size; } /* * This function constructs and sends multiple scan config commands to * the firmware. * * Previous routines in the code flow have created a scan command configuration * with any requested TLVs. This function splits the channel TLV into maximum * channels supported per scan lists and sends the portion of the channel TLV, * along with the other TLVs, to the firmware. */ static int mwifiex_scan_channel_list(struct mwifiex_private *priv, u32 max_chan_per_scan, u8 filtered_scan, struct mwifiex_scan_cmd_config *scan_cfg_out, struct mwifiex_ie_types_chan_list_param_set *chan_tlv_out, struct mwifiex_chan_scan_param_set *scan_chan_list) { struct mwifiex_adapter *adapter = priv->adapter; int ret = 0; struct mwifiex_chan_scan_param_set *tmp_chan_list; struct mwifiex_chan_scan_param_set *start_chan; struct cmd_ctrl_node *cmd_node, *tmp_node; unsigned long flags; u32 tlv_idx, rates_size, cmd_no; u32 total_scan_time; u32 done_early; u8 radio_type; if (!scan_cfg_out || !chan_tlv_out || !scan_chan_list) { dev_dbg(priv->adapter->dev, "info: Scan: Null detect: %p, %p, %p\n", scan_cfg_out, chan_tlv_out, scan_chan_list); return -1; } /* Check csa channel expiry before preparing scan list */ mwifiex_11h_get_csa_closed_channel(priv); chan_tlv_out->header.type = cpu_to_le16(TLV_TYPE_CHANLIST); /* Set the temp channel struct pointer to the start of the desired list */ tmp_chan_list = scan_chan_list; /* Loop through the desired channel list, sending a new firmware scan commands for each max_chan_per_scan channels (or for 1,6,11 individually if configured accordingly) */ while (tmp_chan_list->chan_number) { tlv_idx = 0; total_scan_time = 0; radio_type = 0; chan_tlv_out->header.len = 0; start_chan = tmp_chan_list; done_early = false; /* * Construct the Channel TLV for the scan command. Continue to * insert channel TLVs until: * - the tlv_idx hits the maximum configured per scan command * - the next channel to insert is 0 (end of desired channel * list) * - done_early is set (controlling individual scanning of * 1,6,11) */ while (tlv_idx < max_chan_per_scan && tmp_chan_list->chan_number && !done_early) { if (tmp_chan_list->chan_number == priv->csa_chan) { tmp_chan_list++; continue; } radio_type = tmp_chan_list->radio_type; dev_dbg(priv->adapter->dev, "info: Scan: Chan(%3d), Radio(%d)," " Mode(%d, %d), Dur(%d)\n", tmp_chan_list->chan_number, tmp_chan_list->radio_type, tmp_chan_list->chan_scan_mode_bitmap & MWIFIEX_PASSIVE_SCAN, (tmp_chan_list->chan_scan_mode_bitmap & MWIFIEX_DISABLE_CHAN_FILT) >> 1, le16_to_cpu(tmp_chan_list->max_scan_time)); /* Copy the current channel TLV to the command being prepared */ memcpy(chan_tlv_out->chan_scan_param + tlv_idx, tmp_chan_list, sizeof(chan_tlv_out->chan_scan_param)); /* Increment the TLV header length by the size appended */ le16_add_cpu(&chan_tlv_out->header.len, sizeof(chan_tlv_out->chan_scan_param)); /* * The tlv buffer length is set to the number of bytes * of the between the channel tlv pointer and the start * of the tlv buffer. This compensates for any TLVs * that were appended before the channel list. */ scan_cfg_out->tlv_buf_len = (u32) ((u8 *) chan_tlv_out - scan_cfg_out->tlv_buf); /* Add the size of the channel tlv header and the data length */ scan_cfg_out->tlv_buf_len += (sizeof(chan_tlv_out->header) + le16_to_cpu(chan_tlv_out->header.len)); /* Increment the index to the channel tlv we are constructing */ tlv_idx++; /* Count the total scan time per command */ total_scan_time += le16_to_cpu(tmp_chan_list->max_scan_time); done_early = false; /* Stop the loop if the *current* channel is in the 1,6,11 set and we are not filtering on a BSSID or SSID. */ if (!filtered_scan && (tmp_chan_list->chan_number == 1 || tmp_chan_list->chan_number == 6 || tmp_chan_list->chan_number == 11)) done_early = true; /* Increment the tmp pointer to the next channel to be scanned */ tmp_chan_list++; /* Stop the loop if the *next* channel is in the 1,6,11 set. This will cause it to be the only channel scanned on the next interation */ if (!filtered_scan && (tmp_chan_list->chan_number == 1 || tmp_chan_list->chan_number == 6 || tmp_chan_list->chan_number == 11)) done_early = true; } /* The total scan time should be less than scan command timeout value */ if (total_scan_time > MWIFIEX_MAX_TOTAL_SCAN_TIME) { dev_err(priv->adapter->dev, "total scan time %dms" " is over limit (%dms), scan skipped\n", total_scan_time, MWIFIEX_MAX_TOTAL_SCAN_TIME); ret = -1; break; } rates_size = mwifiex_append_rate_tlv(priv, scan_cfg_out, radio_type); priv->adapter->scan_channels = start_chan; /* Send the scan command to the firmware with the specified cfg */ if (priv->adapter->ext_scan) cmd_no = HostCmd_CMD_802_11_SCAN_EXT; else cmd_no = HostCmd_CMD_802_11_SCAN; ret = mwifiex_send_cmd(priv, cmd_no, HostCmd_ACT_GEN_SET, 0, scan_cfg_out, false); /* rate IE is updated per scan command but same starting * pointer is used each time so that rate IE from earlier * scan_cfg_out->buf is overwritten with new one. */ scan_cfg_out->tlv_buf_len -= sizeof(struct mwifiex_ie_types_header) + rates_size; if (ret) { spin_lock_irqsave(&adapter->scan_pending_q_lock, flags); list_for_each_entry_safe(cmd_node, tmp_node, &adapter->scan_pending_q, list) { list_del(&cmd_node->list); cmd_node->wait_q_enabled = false; mwifiex_insert_cmd_to_free_q(adapter, cmd_node); } spin_unlock_irqrestore(&adapter->scan_pending_q_lock, flags); break; } } if (ret) return -1; return 0; } /* * This function constructs a scan command configuration structure to use * in scan commands. * * Application layer or other functions can invoke network scanning * with a scan configuration supplied in a user scan configuration structure. * This structure is used as the basis of one or many scan command configuration * commands that are sent to the command processing module and eventually to the * firmware. * * This function creates a scan command configuration structure based on the * following user supplied parameters (if present): * - SSID filter * - BSSID filter * - Number of Probes to be sent * - Channel list * * If the SSID or BSSID filter is not present, the filter is disabled/cleared. * If the number of probes is not set, adapter default setting is used. */ static void mwifiex_config_scan(struct mwifiex_private *priv, const struct mwifiex_user_scan_cfg *user_scan_in, struct mwifiex_scan_cmd_config *scan_cfg_out, struct mwifiex_ie_types_chan_list_param_set **chan_list_out, struct mwifiex_chan_scan_param_set *scan_chan_list, u8 *max_chan_per_scan, u8 *filtered_scan, u8 *scan_current_only) { struct mwifiex_adapter *adapter = priv->adapter; struct mwifiex_ie_types_num_probes *num_probes_tlv; struct mwifiex_ie_types_wildcard_ssid_params *wildcard_ssid_tlv; struct mwifiex_ie_types_bssid_list *bssid_tlv; u8 *tlv_pos; u32 num_probes; u32 ssid_len; u32 chan_idx; u32 chan_num; u32 scan_type; u16 scan_dur; u8 channel; u8 radio_type; int i; u8 ssid_filter; struct mwifiex_ie_types_htcap *ht_cap; /* The tlv_buf_len is calculated for each scan command. The TLVs added in this routine will be preserved since the routine that sends the command will append channelTLVs at *chan_list_out. The difference between the *chan_list_out and the tlv_buf start will be used to calculate the size of anything we add in this routine. */ scan_cfg_out->tlv_buf_len = 0; /* Running tlv pointer. Assigned to chan_list_out at end of function so later routines know where channels can be added to the command buf */ tlv_pos = scan_cfg_out->tlv_buf; /* Initialize the scan as un-filtered; the flag is later set to TRUE below if a SSID or BSSID filter is sent in the command */ *filtered_scan = false; /* Initialize the scan as not being only on the current channel. If the channel list is customized, only contains one channel, and is the active channel, this is set true and data flow is not halted. */ *scan_current_only = false; if (user_scan_in) { /* Default the ssid_filter flag to TRUE, set false under certain wildcard conditions and qualified by the existence of an SSID list before marking the scan as filtered */ ssid_filter = true; /* Set the BSS type scan filter, use Adapter setting if unset */ scan_cfg_out->bss_mode = (user_scan_in->bss_mode ? (u8) user_scan_in-> bss_mode : (u8) adapter->scan_mode); /* Set the number of probes to send, use Adapter setting if unset */ num_probes = (user_scan_in->num_probes ? user_scan_in-> num_probes : adapter->scan_probes); /* * Set the BSSID filter to the incoming configuration, * if non-zero. If not set, it will remain disabled * (all zeros). */ memcpy(scan_cfg_out->specific_bssid, user_scan_in->specific_bssid, sizeof(scan_cfg_out->specific_bssid)); if (adapter->ext_scan && !is_zero_ether_addr(scan_cfg_out->specific_bssid)) { bssid_tlv = (struct mwifiex_ie_types_bssid_list *)tlv_pos; bssid_tlv->header.type = cpu_to_le16(TLV_TYPE_BSSID); bssid_tlv->header.len = cpu_to_le16(ETH_ALEN); memcpy(bssid_tlv->bssid, user_scan_in->specific_bssid, ETH_ALEN); tlv_pos += sizeof(struct mwifiex_ie_types_bssid_list); } for (i = 0; i < user_scan_in->num_ssids; i++) { ssid_len = user_scan_in->ssid_list[i].ssid_len; wildcard_ssid_tlv = (struct mwifiex_ie_types_wildcard_ssid_params *) tlv_pos; wildcard_ssid_tlv->header.type = cpu_to_le16(TLV_TYPE_WILDCARDSSID); wildcard_ssid_tlv->header.len = cpu_to_le16( (u16) (ssid_len + sizeof(wildcard_ssid_tlv-> max_ssid_length))); /* * max_ssid_length = 0 tells firmware to perform * specific scan for the SSID filled, whereas * max_ssid_length = IEEE80211_MAX_SSID_LEN is for * wildcard scan. */ if (ssid_len) wildcard_ssid_tlv->max_ssid_length = 0; else wildcard_ssid_tlv->max_ssid_length = IEEE80211_MAX_SSID_LEN; memcpy(wildcard_ssid_tlv->ssid, user_scan_in->ssid_list[i].ssid, ssid_len); tlv_pos += (sizeof(wildcard_ssid_tlv->header) + le16_to_cpu(wildcard_ssid_tlv->header.len)); dev_dbg(adapter->dev, "info: scan: ssid[%d]: %s, %d\n", i, wildcard_ssid_tlv->ssid, wildcard_ssid_tlv->max_ssid_length); /* Empty wildcard ssid with a maxlen will match many or potentially all SSIDs (maxlen == 32), therefore do not treat the scan as filtered. */ if (!ssid_len && wildcard_ssid_tlv->max_ssid_length) ssid_filter = false; } /* * The default number of channels sent in the command is low to * ensure the response buffer from the firmware does not * truncate scan results. That is not an issue with an SSID * or BSSID filter applied to the scan results in the firmware. */ if ((i && ssid_filter) || !is_zero_ether_addr(scan_cfg_out->specific_bssid)) *filtered_scan = true; } else { scan_cfg_out->bss_mode = (u8) adapter->scan_mode; num_probes = adapter->scan_probes; } /* * If a specific BSSID or SSID is used, the number of channels in the * scan command will be increased to the absolute maximum. */ if (*filtered_scan) *max_chan_per_scan = MWIFIEX_MAX_CHANNELS_PER_SPECIFIC_SCAN; else *max_chan_per_scan = MWIFIEX_DEF_CHANNELS_PER_SCAN_CMD; /* If the input config or adapter has the number of Probes set, add tlv */ if (num_probes) { dev_dbg(adapter->dev, "info: scan: num_probes = %d\n", num_probes); num_probes_tlv = (struct mwifiex_ie_types_num_probes *) tlv_pos; num_probes_tlv->header.type = cpu_to_le16(TLV_TYPE_NUMPROBES); num_probes_tlv->header.len = cpu_to_le16(sizeof(num_probes_tlv->num_probes)); num_probes_tlv->num_probes = cpu_to_le16((u16) num_probes); tlv_pos += sizeof(num_probes_tlv->header) + le16_to_cpu(num_probes_tlv->header.len); } if (ISSUPP_11NENABLED(priv->adapter->fw_cap_info) && (priv->adapter->config_bands & BAND_GN || priv->adapter->config_bands & BAND_AN)) { ht_cap = (struct mwifiex_ie_types_htcap *) tlv_pos; memset(ht_cap, 0, sizeof(struct mwifiex_ie_types_htcap)); ht_cap->header.type = cpu_to_le16(WLAN_EID_HT_CAPABILITY); ht_cap->header.len = cpu_to_le16(sizeof(struct ieee80211_ht_cap)); radio_type = mwifiex_band_to_radio_type(priv->adapter->config_bands); mwifiex_fill_cap_info(priv, radio_type, &ht_cap->ht_cap); tlv_pos += sizeof(struct mwifiex_ie_types_htcap); } /* Append vendor specific IE TLV */ mwifiex_cmd_append_vsie_tlv(priv, MWIFIEX_VSIE_MASK_SCAN, &tlv_pos); /* * Set the output for the channel TLV to the address in the tlv buffer * past any TLVs that were added in this function (SSID, num_probes). * Channel TLVs will be added past this for each scan command, * preserving the TLVs that were previously added. */ *chan_list_out = (struct mwifiex_ie_types_chan_list_param_set *) tlv_pos; if (user_scan_in && user_scan_in->chan_list[0].chan_number) { dev_dbg(adapter->dev, "info: Scan: Using supplied channel list\n"); for (chan_idx = 0; chan_idx < MWIFIEX_USER_SCAN_CHAN_MAX && user_scan_in->chan_list[chan_idx].chan_number; chan_idx++) { channel = user_scan_in->chan_list[chan_idx].chan_number; (scan_chan_list + chan_idx)->chan_number = channel; radio_type = user_scan_in->chan_list[chan_idx].radio_type; (scan_chan_list + chan_idx)->radio_type = radio_type; scan_type = user_scan_in->chan_list[chan_idx].scan_type; if (scan_type == MWIFIEX_SCAN_TYPE_PASSIVE) (scan_chan_list + chan_idx)->chan_scan_mode_bitmap |= MWIFIEX_PASSIVE_SCAN; else (scan_chan_list + chan_idx)->chan_scan_mode_bitmap &= ~MWIFIEX_PASSIVE_SCAN; if (*filtered_scan) (scan_chan_list + chan_idx)->chan_scan_mode_bitmap |= MWIFIEX_DISABLE_CHAN_FILT; if (user_scan_in->chan_list[chan_idx].scan_time) { scan_dur = (u16) user_scan_in-> chan_list[chan_idx].scan_time; } else { if (scan_type == MWIFIEX_SCAN_TYPE_PASSIVE) scan_dur = adapter->passive_scan_time; else if (*filtered_scan) scan_dur = adapter->specific_scan_time; else scan_dur = adapter->active_scan_time; } (scan_chan_list + chan_idx)->min_scan_time = cpu_to_le16(scan_dur); (scan_chan_list + chan_idx)->max_scan_time = cpu_to_le16(scan_dur); } /* Check if we are only scanning the current channel */ if ((chan_idx == 1) && (user_scan_in->chan_list[0].chan_number == priv->curr_bss_params.bss_descriptor.channel)) { *scan_current_only = true; dev_dbg(adapter->dev, "info: Scan: Scanning current channel only\n"); } chan_num = chan_idx; } else { dev_dbg(adapter->dev, "info: Scan: Creating full region channel list\n"); chan_num = mwifiex_scan_create_channel_list(priv, user_scan_in, scan_chan_list, *filtered_scan); } /* * In associated state we will reduce the number of channels scanned per * scan command to 1 to avoid any traffic delay/loss. */ if (priv->media_connected) *max_chan_per_scan = 1; } /* * This function inspects the scan response buffer for pointers to * expected TLVs. * * TLVs can be included at the end of the scan response BSS information. * * Data in the buffer is parsed pointers to TLVs that can potentially * be passed back in the response. */ static void mwifiex_ret_802_11_scan_get_tlv_ptrs(struct mwifiex_adapter *adapter, struct mwifiex_ie_types_data *tlv, u32 tlv_buf_size, u32 req_tlv_type, struct mwifiex_ie_types_data **tlv_data) { struct mwifiex_ie_types_data *current_tlv; u32 tlv_buf_left; u32 tlv_type; u32 tlv_len; current_tlv = tlv; tlv_buf_left = tlv_buf_size; *tlv_data = NULL; dev_dbg(adapter->dev, "info: SCAN_RESP: tlv_buf_size = %d\n", tlv_buf_size); while (tlv_buf_left >= sizeof(struct mwifiex_ie_types_header)) { tlv_type = le16_to_cpu(current_tlv->header.type); tlv_len = le16_to_cpu(current_tlv->header.len); if (sizeof(tlv->header) + tlv_len > tlv_buf_left) { dev_err(adapter->dev, "SCAN_RESP: TLV buffer corrupt\n"); break; } if (req_tlv_type == tlv_type) { switch (tlv_type) { case TLV_TYPE_TSFTIMESTAMP: dev_dbg(adapter->dev, "info: SCAN_RESP: TSF " "timestamp TLV, len = %d\n", tlv_len); *tlv_data = current_tlv; break; case TLV_TYPE_CHANNELBANDLIST: dev_dbg(adapter->dev, "info: SCAN_RESP: channel" " band list TLV, len = %d\n", tlv_len); *tlv_data = current_tlv; break; default: dev_err(adapter->dev, "SCAN_RESP: unhandled TLV = %d\n", tlv_type); /* Give up, this seems corrupted */ return; } } if (*tlv_data) break; tlv_buf_left -= (sizeof(tlv->header) + tlv_len); current_tlv = (struct mwifiex_ie_types_data *) (current_tlv->data + tlv_len); } /* while */ } /* * This function parses provided beacon buffer and updates * respective fields in bss descriptor structure. */ int mwifiex_update_bss_desc_with_ie(struct mwifiex_adapter *adapter, struct mwifiex_bssdescriptor *bss_entry) { int ret = 0; u8 element_id; struct ieee_types_fh_param_set *fh_param_set; struct ieee_types_ds_param_set *ds_param_set; struct ieee_types_cf_param_set *cf_param_set; struct ieee_types_ibss_param_set *ibss_param_set; u8 *current_ptr; u8 *rate; u8 element_len; u16 total_ie_len; u8 bytes_to_copy; u8 rate_size; u8 found_data_rate_ie; u32 bytes_left; struct ieee_types_vendor_specific *vendor_ie; const u8 wpa_oui[4] = { 0x00, 0x50, 0xf2, 0x01 }; const u8 wmm_oui[4] = { 0x00, 0x50, 0xf2, 0x02 }; found_data_rate_ie = false; rate_size = 0; current_ptr = bss_entry->beacon_buf; bytes_left = bss_entry->beacon_buf_size; /* Process variable IE */ while (bytes_left >= 2) { element_id = *current_ptr; element_len = *(current_ptr + 1); total_ie_len = element_len + sizeof(struct ieee_types_header); if (bytes_left < total_ie_len) { dev_err(adapter->dev, "err: InterpretIE: in processing" " IE, bytes left < IE length\n"); return -1; } switch (element_id) { case WLAN_EID_SSID: bss_entry->ssid.ssid_len = element_len; memcpy(bss_entry->ssid.ssid, (current_ptr + 2), element_len); dev_dbg(adapter->dev, "info: InterpretIE: ssid: %-32s\n", bss_entry->ssid.ssid); break; case WLAN_EID_SUPP_RATES: memcpy(bss_entry->data_rates, current_ptr + 2, element_len); memcpy(bss_entry->supported_rates, current_ptr + 2, element_len); rate_size = element_len; found_data_rate_ie = true; break; case WLAN_EID_FH_PARAMS: fh_param_set = (struct ieee_types_fh_param_set *) current_ptr; memcpy(&bss_entry->phy_param_set.fh_param_set, fh_param_set, sizeof(struct ieee_types_fh_param_set)); break; case WLAN_EID_DS_PARAMS: ds_param_set = (struct ieee_types_ds_param_set *) current_ptr; bss_entry->channel = ds_param_set->current_chan; memcpy(&bss_entry->phy_param_set.ds_param_set, ds_param_set, sizeof(struct ieee_types_ds_param_set)); break; case WLAN_EID_CF_PARAMS: cf_param_set = (struct ieee_types_cf_param_set *) current_ptr; memcpy(&bss_entry->ss_param_set.cf_param_set, cf_param_set, sizeof(struct ieee_types_cf_param_set)); break; case WLAN_EID_IBSS_PARAMS: ibss_param_set = (struct ieee_types_ibss_param_set *) current_ptr; memcpy(&bss_entry->ss_param_set.ibss_param_set, ibss_param_set, sizeof(struct ieee_types_ibss_param_set)); break; case WLAN_EID_ERP_INFO: bss_entry->erp_flags = *(current_ptr + 2); break; case WLAN_EID_PWR_CONSTRAINT: bss_entry->local_constraint = *(current_ptr + 2); bss_entry->sensed_11h = true; break; case WLAN_EID_CHANNEL_SWITCH: bss_entry->chan_sw_ie_present = true; case WLAN_EID_PWR_CAPABILITY: case WLAN_EID_TPC_REPORT: case WLAN_EID_QUIET: bss_entry->sensed_11h = true; break; case WLAN_EID_EXT_SUPP_RATES: /* * Only process extended supported rate * if data rate is already found. * Data rate IE should come before * extended supported rate IE */ if (found_data_rate_ie) { if ((element_len + rate_size) > MWIFIEX_SUPPORTED_RATES) bytes_to_copy = (MWIFIEX_SUPPORTED_RATES - rate_size); else bytes_to_copy = element_len; rate = (u8 *) bss_entry->data_rates; rate += rate_size; memcpy(rate, current_ptr + 2, bytes_to_copy); rate = (u8 *) bss_entry->supported_rates; rate += rate_size; memcpy(rate, current_ptr + 2, bytes_to_copy); } break; case WLAN_EID_VENDOR_SPECIFIC: vendor_ie = (struct ieee_types_vendor_specific *) current_ptr; if (!memcmp (vendor_ie->vend_hdr.oui, wpa_oui, sizeof(wpa_oui))) { bss_entry->bcn_wpa_ie = (struct ieee_types_vendor_specific *) current_ptr; bss_entry->wpa_offset = (u16) (current_ptr - bss_entry->beacon_buf); } else if (!memcmp(vendor_ie->vend_hdr.oui, wmm_oui, sizeof(wmm_oui))) { if (total_ie_len == sizeof(struct ieee_types_wmm_parameter) || total_ie_len == sizeof(struct ieee_types_wmm_info)) /* * Only accept and copy the WMM IE if * it matches the size expected for the * WMM Info IE or the WMM Parameter IE. */ memcpy((u8 *) &bss_entry->wmm_ie, current_ptr, total_ie_len); } break; case WLAN_EID_RSN: bss_entry->bcn_rsn_ie = (struct ieee_types_generic *) current_ptr; bss_entry->rsn_offset = (u16) (current_ptr - bss_entry->beacon_buf); break; case WLAN_EID_BSS_AC_ACCESS_DELAY: bss_entry->bcn_wapi_ie = (struct ieee_types_generic *) current_ptr; bss_entry->wapi_offset = (u16) (current_ptr - bss_entry->beacon_buf); break; case WLAN_EID_HT_CAPABILITY: bss_entry->bcn_ht_cap = (struct ieee80211_ht_cap *) (current_ptr + sizeof(struct ieee_types_header)); bss_entry->ht_cap_offset = (u16) (current_ptr + sizeof(struct ieee_types_header) - bss_entry->beacon_buf); break; case WLAN_EID_HT_OPERATION: bss_entry->bcn_ht_oper = (struct ieee80211_ht_operation *)(current_ptr + sizeof(struct ieee_types_header)); bss_entry->ht_info_offset = (u16) (current_ptr + sizeof(struct ieee_types_header) - bss_entry->beacon_buf); break; case WLAN_EID_VHT_CAPABILITY: bss_entry->disable_11ac = false; bss_entry->bcn_vht_cap = (void *)(current_ptr + sizeof(struct ieee_types_header)); bss_entry->vht_cap_offset = (u16)((u8 *)bss_entry->bcn_vht_cap - bss_entry->beacon_buf); break; case WLAN_EID_VHT_OPERATION: bss_entry->bcn_vht_oper = (void *)(current_ptr + sizeof(struct ieee_types_header)); bss_entry->vht_info_offset = (u16)((u8 *)bss_entry->bcn_vht_oper - bss_entry->beacon_buf); break; case WLAN_EID_BSS_COEX_2040: bss_entry->bcn_bss_co_2040 = current_ptr; bss_entry->bss_co_2040_offset = (u16) (current_ptr - bss_entry->beacon_buf); break; case WLAN_EID_EXT_CAPABILITY: bss_entry->bcn_ext_cap = current_ptr; bss_entry->ext_cap_offset = (u16) (current_ptr - bss_entry->beacon_buf); break; case WLAN_EID_OPMODE_NOTIF: bss_entry->oper_mode = (void *)current_ptr; bss_entry->oper_mode_offset = (u16)((u8 *)bss_entry->oper_mode - bss_entry->beacon_buf); break; default: break; } current_ptr += element_len + 2; /* Need to account for IE ID and IE Len */ bytes_left -= (element_len + 2); } /* while (bytes_left > 2) */ return ret; } /* * This function converts radio type scan parameter to a band configuration * to be used in join command. */ static u8 mwifiex_radio_type_to_band(u8 radio_type) { switch (radio_type) { case HostCmd_SCAN_RADIO_TYPE_A: return BAND_A; case HostCmd_SCAN_RADIO_TYPE_BG: default: return BAND_G; } } /* * This is an internal function used to start a scan based on an input * configuration. * * This uses the input user scan configuration information when provided in * order to send the appropriate scan commands to firmware to populate or * update the internal driver scan table. */ int mwifiex_scan_networks(struct mwifiex_private *priv, const struct mwifiex_user_scan_cfg *user_scan_in) { int ret; struct mwifiex_adapter *adapter = priv->adapter; struct cmd_ctrl_node *cmd_node; union mwifiex_scan_cmd_config_tlv *scan_cfg_out; struct mwifiex_ie_types_chan_list_param_set *chan_list_out; struct mwifiex_chan_scan_param_set *scan_chan_list; u8 filtered_scan; u8 scan_current_chan_only; u8 max_chan_per_scan; unsigned long flags; if (adapter->scan_processing) { dev_err(adapter->dev, "cmd: Scan already in process...\n"); return -EBUSY; } if (priv->scan_block) { dev_err(adapter->dev, "cmd: Scan is blocked during association...\n"); return -EBUSY; } spin_lock_irqsave(&adapter->mwifiex_cmd_lock, flags); adapter->scan_processing = true; spin_unlock_irqrestore(&adapter->mwifiex_cmd_lock, flags); scan_cfg_out = kzalloc(sizeof(union mwifiex_scan_cmd_config_tlv), GFP_KERNEL); if (!scan_cfg_out) { ret = -ENOMEM; goto done; } scan_chan_list = kcalloc(MWIFIEX_USER_SCAN_CHAN_MAX, sizeof(struct mwifiex_chan_scan_param_set), GFP_KERNEL); if (!scan_chan_list) { kfree(scan_cfg_out); ret = -ENOMEM; goto done; } mwifiex_config_scan(priv, user_scan_in, &scan_cfg_out->config, &chan_list_out, scan_chan_list, &max_chan_per_scan, &filtered_scan, &scan_current_chan_only); ret = mwifiex_scan_channel_list(priv, max_chan_per_scan, filtered_scan, &scan_cfg_out->config, chan_list_out, scan_chan_list); /* Get scan command from scan_pending_q and put to cmd_pending_q */ if (!ret) { spin_lock_irqsave(&adapter->scan_pending_q_lock, flags); if (!list_empty(&adapter->scan_pending_q)) { cmd_node = list_first_entry(&adapter->scan_pending_q, struct cmd_ctrl_node, list); list_del(&cmd_node->list); spin_unlock_irqrestore(&adapter->scan_pending_q_lock, flags); mwifiex_insert_cmd_to_pending_q(adapter, cmd_node, true); queue_work(adapter->workqueue, &adapter->main_work); /* Perform internal scan synchronously */ if (!priv->scan_request) { dev_dbg(adapter->dev, "wait internal scan\n"); mwifiex_wait_queue_complete(adapter, cmd_node); } } else { spin_unlock_irqrestore(&adapter->scan_pending_q_lock, flags); } } kfree(scan_cfg_out); kfree(scan_chan_list); done: if (ret) { spin_lock_irqsave(&adapter->mwifiex_cmd_lock, flags); adapter->scan_processing = false; spin_unlock_irqrestore(&adapter->mwifiex_cmd_lock, flags); } return ret; } /* * This function prepares a scan command to be sent to the firmware. * * This uses the scan command configuration sent to the command processing * module in command preparation stage to configure a scan command structure * to send to firmware. * * The fixed fields specifying the BSS type and BSSID filters as well as a * variable number/length of TLVs are sent in the command to firmware. * * Preparation also includes - * - Setting command ID, and proper size * - Ensuring correct endian-ness */ int mwifiex_cmd_802_11_scan(struct host_cmd_ds_command *cmd, struct mwifiex_scan_cmd_config *scan_cfg) { struct host_cmd_ds_802_11_scan *scan_cmd = &cmd->params.scan; /* Set fixed field variables in scan command */ scan_cmd->bss_mode = scan_cfg->bss_mode; memcpy(scan_cmd->bssid, scan_cfg->specific_bssid, sizeof(scan_cmd->bssid)); memcpy(scan_cmd->tlv_buffer, scan_cfg->tlv_buf, scan_cfg->tlv_buf_len); cmd->command = cpu_to_le16(HostCmd_CMD_802_11_SCAN); /* Size is equal to the sizeof(fixed portions) + the TLV len + header */ cmd->size = cpu_to_le16((u16) (sizeof(scan_cmd->bss_mode) + sizeof(scan_cmd->bssid) + scan_cfg->tlv_buf_len + S_DS_GEN)); return 0; } /* * This function checks compatibility of requested network with current * driver settings. */ int mwifiex_check_network_compatibility(struct mwifiex_private *priv, struct mwifiex_bssdescriptor *bss_desc) { int ret = -1; if (!bss_desc) return -1; if ((mwifiex_get_cfp(priv, (u8) bss_desc->bss_band, (u16) bss_desc->channel, 0))) { switch (priv->bss_mode) { case NL80211_IFTYPE_STATION: case NL80211_IFTYPE_ADHOC: ret = mwifiex_is_network_compatible(priv, bss_desc, priv->bss_mode); if (ret) dev_err(priv->adapter->dev, "Incompatible network settings\n"); break; default: ret = 0; } } return ret; } static int mwifiex_update_curr_bss_params(struct mwifiex_private *priv, struct cfg80211_bss *bss) { struct mwifiex_bssdescriptor *bss_desc; int ret; unsigned long flags; /* Allocate and fill new bss descriptor */ bss_desc = kzalloc(sizeof(struct mwifiex_bssdescriptor), GFP_KERNEL); if (!bss_desc) return -ENOMEM; ret = mwifiex_fill_new_bss_desc(priv, bss, bss_desc); if (ret) goto done; ret = mwifiex_check_network_compatibility(priv, bss_desc); if (ret) goto done; spin_lock_irqsave(&priv->curr_bcn_buf_lock, flags); /* Make a copy of current BSSID descriptor */ memcpy(&priv->curr_bss_params.bss_descriptor, bss_desc, sizeof(priv->curr_bss_params.bss_descriptor)); /* The contents of beacon_ie will be copied to its own buffer * in mwifiex_save_curr_bcn() */ mwifiex_save_curr_bcn(priv); spin_unlock_irqrestore(&priv->curr_bcn_buf_lock, flags); done: /* beacon_ie buffer was allocated in function * mwifiex_fill_new_bss_desc(). Free it now. */ kfree(bss_desc->beacon_buf); kfree(bss_desc); return 0; } static int mwifiex_parse_single_response_buf(struct mwifiex_private *priv, u8 **bss_info, u32 *bytes_left, u64 fw_tsf, u8 *radio_type, bool ext_scan, s32 rssi_val) { struct mwifiex_adapter *adapter = priv->adapter; struct mwifiex_chan_freq_power *cfp; struct cfg80211_bss *bss; u8 bssid[ETH_ALEN]; s32 rssi; const u8 *ie_buf; size_t ie_len; u16 channel = 0; u16 beacon_size = 0; u32 curr_bcn_bytes; u32 freq; u16 beacon_period; u16 cap_info_bitmap; u8 *current_ptr; u64 timestamp; struct mwifiex_fixed_bcn_param *bcn_param; struct mwifiex_bss_priv *bss_priv; if (*bytes_left >= sizeof(beacon_size)) { /* Extract & convert beacon size from command buffer */ memcpy(&beacon_size, *bss_info, sizeof(beacon_size)); *bytes_left -= sizeof(beacon_size); *bss_info += sizeof(beacon_size); } if (!beacon_size || beacon_size > *bytes_left) { *bss_info += *bytes_left; *bytes_left = 0; return -EFAULT; } /* Initialize the current working beacon pointer for this BSS * iteration */ current_ptr = *bss_info; /* Advance the return beacon pointer past the current beacon */ *bss_info += beacon_size; *bytes_left -= beacon_size; curr_bcn_bytes = beacon_size; /* First 5 fields are bssid, RSSI(for legacy scan only), * time stamp, beacon interval, and capability information */ if (curr_bcn_bytes < ETH_ALEN + sizeof(u8) + sizeof(struct mwifiex_fixed_bcn_param)) { dev_err(adapter->dev, "InterpretIE: not enough bytes left\n"); return -EFAULT; } memcpy(bssid, current_ptr, ETH_ALEN); current_ptr += ETH_ALEN; curr_bcn_bytes -= ETH_ALEN; if (!ext_scan) { rssi = (s32) *current_ptr; rssi = (-rssi) * 100; /* Convert dBm to mBm */ current_ptr += sizeof(u8); curr_bcn_bytes -= sizeof(u8); dev_dbg(adapter->dev, "info: InterpretIE: RSSI=%d\n", rssi); } else { rssi = rssi_val; } bcn_param = (struct mwifiex_fixed_bcn_param *)current_ptr; current_ptr += sizeof(*bcn_param); curr_bcn_bytes -= sizeof(*bcn_param); timestamp = le64_to_cpu(bcn_param->timestamp); beacon_period = le16_to_cpu(bcn_param->beacon_period); cap_info_bitmap = le16_to_cpu(bcn_param->cap_info_bitmap); dev_dbg(adapter->dev, "info: InterpretIE: capabilities=0x%X\n", cap_info_bitmap); /* Rest of the current buffer are IE's */ ie_buf = current_ptr; ie_len = curr_bcn_bytes; dev_dbg(adapter->dev, "info: InterpretIE: IELength for this AP = %d\n", curr_bcn_bytes); while (curr_bcn_bytes >= sizeof(struct ieee_types_header)) { u8 element_id, element_len; element_id = *current_ptr; element_len = *(current_ptr + 1); if (curr_bcn_bytes < element_len + sizeof(struct ieee_types_header)) { dev_err(adapter->dev, "%s: bytes left < IE length\n", __func__); return -EFAULT; } if (element_id == WLAN_EID_DS_PARAMS) { channel = *(current_ptr + sizeof(struct ieee_types_header)); break; } current_ptr += element_len + sizeof(struct ieee_types_header); curr_bcn_bytes -= element_len + sizeof(struct ieee_types_header); } if (channel) { struct ieee80211_channel *chan; u8 band; /* Skip entry if on csa closed channel */ if (channel == priv->csa_chan) { dev_dbg(adapter->dev, "Dropping entry on csa closed channel\n"); return 0; } band = BAND_G; if (radio_type) band = mwifiex_radio_type_to_band(*radio_type & (BIT(0) | BIT(1))); cfp = mwifiex_get_cfp(priv, band, channel, 0); freq = cfp ? cfp->freq : 0; chan = ieee80211_get_channel(priv->wdev->wiphy, freq); if (chan && !(chan->flags & IEEE80211_CHAN_DISABLED)) { bss = cfg80211_inform_bss(priv->wdev->wiphy, chan, bssid, timestamp, cap_info_bitmap, beacon_period, ie_buf, ie_len, rssi, GFP_KERNEL); bss_priv = (struct mwifiex_bss_priv *)bss->priv; bss_priv->band = band; bss_priv->fw_tsf = fw_tsf; if (priv->media_connected && !memcmp(bssid, priv->curr_bss_params.bss_descriptor .mac_address, ETH_ALEN)) mwifiex_update_curr_bss_params(priv, bss); cfg80211_put_bss(priv->wdev->wiphy, bss); } } else { dev_dbg(adapter->dev, "missing BSS channel IE\n"); } return 0; } static void mwifiex_complete_scan(struct mwifiex_private *priv) { struct mwifiex_adapter *adapter = priv->adapter; if (adapter->curr_cmd->wait_q_enabled) { adapter->cmd_wait_q.status = 0; if (!priv->scan_request) { dev_dbg(adapter->dev, "complete internal scan\n"); mwifiex_complete_cmd(adapter, adapter->curr_cmd); } } } static void mwifiex_check_next_scan_command(struct mwifiex_private *priv) { struct mwifiex_adapter *adapter = priv->adapter; struct cmd_ctrl_node *cmd_node; unsigned long flags; spin_lock_irqsave(&adapter->scan_pending_q_lock, flags); if (list_empty(&adapter->scan_pending_q)) { spin_unlock_irqrestore(&adapter->scan_pending_q_lock, flags); spin_lock_irqsave(&adapter->mwifiex_cmd_lock, flags); adapter->scan_processing = false; spin_unlock_irqrestore(&adapter->mwifiex_cmd_lock, flags); if (!adapter->ext_scan) mwifiex_complete_scan(priv); if (priv->report_scan_result) priv->report_scan_result = false; if (priv->scan_request) { dev_dbg(adapter->dev, "info: notifying scan done\n"); cfg80211_scan_done(priv->scan_request, 0); priv->scan_request = NULL; } else { priv->scan_aborting = false; dev_dbg(adapter->dev, "info: scan already aborted\n"); } } else { if ((priv->scan_aborting && !priv->scan_request) || priv->scan_block) { spin_unlock_irqrestore(&adapter->scan_pending_q_lock, flags); adapter->scan_delay_cnt = MWIFIEX_MAX_SCAN_DELAY_CNT; mod_timer(&priv->scan_delay_timer, jiffies); dev_dbg(priv->adapter->dev, "info: %s: triggerring scan abort\n", __func__); } else if (!mwifiex_wmm_lists_empty(adapter) && (priv->scan_request && (priv->scan_request->flags & NL80211_SCAN_FLAG_LOW_PRIORITY))) { spin_unlock_irqrestore(&adapter->scan_pending_q_lock, flags); adapter->scan_delay_cnt = 1; mod_timer(&priv->scan_delay_timer, jiffies + msecs_to_jiffies(MWIFIEX_SCAN_DELAY_MSEC)); dev_dbg(priv->adapter->dev, "info: %s: deferring scan\n", __func__); } else { /* Get scan command from scan_pending_q and put to * cmd_pending_q */ cmd_node = list_first_entry(&adapter->scan_pending_q, struct cmd_ctrl_node, list); list_del(&cmd_node->list); spin_unlock_irqrestore(&adapter->scan_pending_q_lock, flags); mwifiex_insert_cmd_to_pending_q(adapter, cmd_node, true); } } return; } /* * This function handles the command response of scan. * * The response buffer for the scan command has the following * memory layout: * * .-------------------------------------------------------------. * | Header (4 * sizeof(t_u16)): Standard command response hdr | * .-------------------------------------------------------------. * | BufSize (t_u16) : sizeof the BSS Description data | * .-------------------------------------------------------------. * | NumOfSet (t_u8) : Number of BSS Descs returned | * .-------------------------------------------------------------. * | BSSDescription data (variable, size given in BufSize) | * .-------------------------------------------------------------. * | TLV data (variable, size calculated using Header->Size, | * | BufSize and sizeof the fixed fields above) | * .-------------------------------------------------------------. */ int mwifiex_ret_802_11_scan(struct mwifiex_private *priv, struct host_cmd_ds_command *resp) { int ret = 0; struct mwifiex_adapter *adapter = priv->adapter; struct host_cmd_ds_802_11_scan_rsp *scan_rsp; struct mwifiex_ie_types_data *tlv_data; struct mwifiex_ie_types_tsf_timestamp *tsf_tlv; u8 *bss_info; u32 scan_resp_size; u32 bytes_left; u32 idx; u32 tlv_buf_size; struct mwifiex_ie_types_chan_band_list_param_set *chan_band_tlv; struct chan_band_param_set *chan_band; u8 is_bgscan_resp; __le64 fw_tsf = 0; u8 *radio_type; is_bgscan_resp = (le16_to_cpu(resp->command) == HostCmd_CMD_802_11_BG_SCAN_QUERY); if (is_bgscan_resp) scan_rsp = &resp->params.bg_scan_query_resp.scan_resp; else scan_rsp = &resp->params.scan_resp; if (scan_rsp->number_of_sets > MWIFIEX_MAX_AP) { dev_err(adapter->dev, "SCAN_RESP: too many AP returned (%d)\n", scan_rsp->number_of_sets); ret = -1; goto check_next_scan; } /* Check csa channel expiry before parsing scan response */ mwifiex_11h_get_csa_closed_channel(priv); bytes_left = le16_to_cpu(scan_rsp->bss_descript_size); dev_dbg(adapter->dev, "info: SCAN_RESP: bss_descript_size %d\n", bytes_left); scan_resp_size = le16_to_cpu(resp->size); dev_dbg(adapter->dev, "info: SCAN_RESP: returned %d APs before parsing\n", scan_rsp->number_of_sets); bss_info = scan_rsp->bss_desc_and_tlv_buffer; /* * The size of the TLV buffer is equal to the entire command response * size (scan_resp_size) minus the fixed fields (sizeof()'s), the * BSS Descriptions (bss_descript_size as bytesLef) and the command * response header (S_DS_GEN) */ tlv_buf_size = scan_resp_size - (bytes_left + sizeof(scan_rsp->bss_descript_size) + sizeof(scan_rsp->number_of_sets) + S_DS_GEN); tlv_data = (struct mwifiex_ie_types_data *) (scan_rsp-> bss_desc_and_tlv_buffer + bytes_left); /* Search the TLV buffer space in the scan response for any valid TLVs */ mwifiex_ret_802_11_scan_get_tlv_ptrs(adapter, tlv_data, tlv_buf_size, TLV_TYPE_TSFTIMESTAMP, (struct mwifiex_ie_types_data **) &tsf_tlv); /* Search the TLV buffer space in the scan response for any valid TLVs */ mwifiex_ret_802_11_scan_get_tlv_ptrs(adapter, tlv_data, tlv_buf_size, TLV_TYPE_CHANNELBANDLIST, (struct mwifiex_ie_types_data **) &chan_band_tlv); for (idx = 0; idx < scan_rsp->number_of_sets && bytes_left; idx++) { /* * If the TSF TLV was appended to the scan results, save this * entry's TSF value in the fw_tsf field. It is the firmware's * TSF value at the time the beacon or probe response was * received. */ if (tsf_tlv) memcpy(&fw_tsf, &tsf_tlv->tsf_data[idx * TSF_DATA_SIZE], sizeof(fw_tsf)); if (chan_band_tlv) { chan_band = &chan_band_tlv->chan_band_param[idx]; radio_type = &chan_band->radio_type; } else { radio_type = NULL; } ret = mwifiex_parse_single_response_buf(priv, &bss_info, &bytes_left, le64_to_cpu(fw_tsf), radio_type, false, 0); if (ret) goto check_next_scan; } check_next_scan: mwifiex_check_next_scan_command(priv); return ret; } /* * This function prepares an extended scan command to be sent to the firmware * * This uses the scan command configuration sent to the command processing * module in command preparation stage to configure a extended scan command * structure to send to firmware. */ int mwifiex_cmd_802_11_scan_ext(struct mwifiex_private *priv, struct host_cmd_ds_command *cmd, void *data_buf) { struct host_cmd_ds_802_11_scan_ext *ext_scan = &cmd->params.ext_scan; struct mwifiex_scan_cmd_config *scan_cfg = data_buf; memcpy(ext_scan->tlv_buffer, scan_cfg->tlv_buf, scan_cfg->tlv_buf_len); cmd->command = cpu_to_le16(HostCmd_CMD_802_11_SCAN_EXT); /* Size is equal to the sizeof(fixed portions) + the TLV len + header */ cmd->size = cpu_to_le16((u16)(sizeof(ext_scan->reserved) + scan_cfg->tlv_buf_len + S_DS_GEN)); return 0; } /* This function handles the command response of extended scan */ int mwifiex_ret_802_11_scan_ext(struct mwifiex_private *priv) { dev_dbg(priv->adapter->dev, "info: EXT scan returns successfully\n"); mwifiex_complete_scan(priv); return 0; } /* This function This function handles the event extended scan report. It * parses extended scan results and informs to cfg80211 stack. */ int mwifiex_handle_event_ext_scan_report(struct mwifiex_private *priv, void *buf) { int ret = 0; struct mwifiex_adapter *adapter = priv->adapter; u8 *bss_info; u32 bytes_left, bytes_left_for_tlv, idx; u16 type, len; struct mwifiex_ie_types_data *tlv; struct mwifiex_ie_types_bss_scan_rsp *scan_rsp_tlv; struct mwifiex_ie_types_bss_scan_info *scan_info_tlv; u8 *radio_type; u64 fw_tsf = 0; s32 rssi = 0; struct mwifiex_event_scan_result *event_scan = buf; u8 num_of_set = event_scan->num_of_set; u8 *scan_resp = buf + sizeof(struct mwifiex_event_scan_result); u16 scan_resp_size = le16_to_cpu(event_scan->buf_size); if (num_of_set > MWIFIEX_MAX_AP) { dev_err(adapter->dev, "EXT_SCAN: Invalid number of AP returned (%d)!!\n", num_of_set); ret = -1; goto check_next_scan; } bytes_left = scan_resp_size; dev_dbg(adapter->dev, "EXT_SCAN: size %d, returned %d APs...", scan_resp_size, num_of_set); tlv = (struct mwifiex_ie_types_data *)scan_resp; for (idx = 0; idx < num_of_set && bytes_left; idx++) { type = le16_to_cpu(tlv->header.type); len = le16_to_cpu(tlv->header.len); if (bytes_left < sizeof(struct mwifiex_ie_types_header) + len) { dev_err(adapter->dev, "EXT_SCAN: Error bytes left < TLV length\n"); break; } scan_rsp_tlv = NULL; scan_info_tlv = NULL; bytes_left_for_tlv = bytes_left; /* BSS response TLV with beacon or probe response buffer * at the initial position of each descriptor */ if (type != TLV_TYPE_BSS_SCAN_RSP) break; bss_info = (u8 *)tlv; scan_rsp_tlv = (struct mwifiex_ie_types_bss_scan_rsp *)tlv; tlv = (struct mwifiex_ie_types_data *)(tlv->data + len); bytes_left_for_tlv -= (len + sizeof(struct mwifiex_ie_types_header)); while (bytes_left_for_tlv >= sizeof(struct mwifiex_ie_types_header) && le16_to_cpu(tlv->header.type) != TLV_TYPE_BSS_SCAN_RSP) { type = le16_to_cpu(tlv->header.type); len = le16_to_cpu(tlv->header.len); if (bytes_left_for_tlv < sizeof(struct mwifiex_ie_types_header) + len) { dev_err(adapter->dev, "EXT_SCAN: Error in processing TLV, bytes left < TLV length\n"); scan_rsp_tlv = NULL; bytes_left_for_tlv = 0; continue; } switch (type) { case TLV_TYPE_BSS_SCAN_INFO: scan_info_tlv = (struct mwifiex_ie_types_bss_scan_info *)tlv; if (len != sizeof(struct mwifiex_ie_types_bss_scan_info) - sizeof(struct mwifiex_ie_types_header)) { bytes_left_for_tlv = 0; continue; } break; default: break; } tlv = (struct mwifiex_ie_types_data *)(tlv->data + len); bytes_left -= (len + sizeof(struct mwifiex_ie_types_header)); bytes_left_for_tlv -= (len + sizeof(struct mwifiex_ie_types_header)); } if (!scan_rsp_tlv) break; /* Advance pointer to the beacon buffer length and * update the bytes count so that the function * wlan_interpret_bss_desc_with_ie() can handle the * scan buffer withut any change */ bss_info += sizeof(u16); bytes_left -= sizeof(u16); if (scan_info_tlv) { rssi = (s32)(s16)(le16_to_cpu(scan_info_tlv->rssi)); rssi *= 100; /* Convert dBm to mBm */ dev_dbg(adapter->dev, "info: InterpretIE: RSSI=%d\n", rssi); fw_tsf = le64_to_cpu(scan_info_tlv->tsf); radio_type = &scan_info_tlv->radio_type; } else { radio_type = NULL; } ret = mwifiex_parse_single_response_buf(priv, &bss_info, &bytes_left, fw_tsf, radio_type, true, rssi); if (ret) goto check_next_scan; } check_next_scan: if (!event_scan->more_event) mwifiex_check_next_scan_command(priv); return ret; } /* * This function prepares command for background scan query. * * Preparation includes - * - Setting command ID and proper size * - Setting background scan flush parameter * - Ensuring correct endian-ness */ int mwifiex_cmd_802_11_bg_scan_query(struct host_cmd_ds_command *cmd) { struct host_cmd_ds_802_11_bg_scan_query *bg_query = &cmd->params.bg_scan_query; cmd->command = cpu_to_le16(HostCmd_CMD_802_11_BG_SCAN_QUERY); cmd->size = cpu_to_le16(sizeof(struct host_cmd_ds_802_11_bg_scan_query) + S_DS_GEN); bg_query->flush = 1; return 0; } /* * This function inserts scan command node to the scan pending queue. */ void mwifiex_queue_scan_cmd(struct mwifiex_private *priv, struct cmd_ctrl_node *cmd_node) { struct mwifiex_adapter *adapter = priv->adapter; unsigned long flags; cmd_node->wait_q_enabled = true; cmd_node->condition = &adapter->scan_wait_q_woken; spin_lock_irqsave(&adapter->scan_pending_q_lock, flags); list_add_tail(&cmd_node->list, &adapter->scan_pending_q); spin_unlock_irqrestore(&adapter->scan_pending_q_lock, flags); } /* * This function sends a scan command for all available channels to the * firmware, filtered on a specific SSID. */ static int mwifiex_scan_specific_ssid(struct mwifiex_private *priv, struct cfg80211_ssid *req_ssid) { struct mwifiex_adapter *adapter = priv->adapter; int ret; struct mwifiex_user_scan_cfg *scan_cfg; if (adapter->scan_processing) { dev_err(adapter->dev, "cmd: Scan already in process...\n"); return -EBUSY; } if (priv->scan_block) { dev_err(adapter->dev, "cmd: Scan is blocked during association...\n"); return -EBUSY; } scan_cfg = kzalloc(sizeof(struct mwifiex_user_scan_cfg), GFP_KERNEL); if (!scan_cfg) return -ENOMEM; scan_cfg->ssid_list = req_ssid; scan_cfg->num_ssids = 1; ret = mwifiex_scan_networks(priv, scan_cfg); kfree(scan_cfg); return ret; } /* * Sends IOCTL request to start a scan. * * This function allocates the IOCTL request buffer, fills it * with requisite parameters and calls the IOCTL handler. * * Scan command can be issued for both normal scan and specific SSID * scan, depending upon whether an SSID is provided or not. */ int mwifiex_request_scan(struct mwifiex_private *priv, struct cfg80211_ssid *req_ssid) { int ret; if (down_interruptible(&priv->async_sem)) { dev_err(priv->adapter->dev, "%s: acquire semaphore\n", __func__); return -1; } priv->adapter->scan_wait_q_woken = false; if (req_ssid && req_ssid->ssid_len != 0) /* Specific SSID scan */ ret = mwifiex_scan_specific_ssid(priv, req_ssid); else /* Normal scan */ ret = mwifiex_scan_networks(priv, NULL); up(&priv->async_sem); return ret; } /* * This function appends the vendor specific IE TLV to a buffer. */ int mwifiex_cmd_append_vsie_tlv(struct mwifiex_private *priv, u16 vsie_mask, u8 **buffer) { int id, ret_len = 0; struct mwifiex_ie_types_vendor_param_set *vs_param_set; if (!buffer) return 0; if (!(*buffer)) return 0; /* * Traverse through the saved vendor specific IE array and append * the selected(scan/assoc/adhoc) IE as TLV to the command */ for (id = 0; id < MWIFIEX_MAX_VSIE_NUM; id++) { if (priv->vs_ie[id].mask & vsie_mask) { vs_param_set = (struct mwifiex_ie_types_vendor_param_set *) *buffer; vs_param_set->header.type = cpu_to_le16(TLV_TYPE_PASSTHROUGH); vs_param_set->header.len = cpu_to_le16((((u16) priv->vs_ie[id].ie[1]) & 0x00FF) + 2); memcpy(vs_param_set->ie, priv->vs_ie[id].ie, le16_to_cpu(vs_param_set->header.len)); *buffer += le16_to_cpu(vs_param_set->header.len) + sizeof(struct mwifiex_ie_types_header); ret_len += le16_to_cpu(vs_param_set->header.len) + sizeof(struct mwifiex_ie_types_header); } } return ret_len; } /* * This function saves a beacon buffer of the current BSS descriptor. * * The current beacon buffer is saved so that it can be restored in the * following cases that makes the beacon buffer not to contain the current * ssid's beacon buffer. * - The current ssid was not found somehow in the last scan. * - The current ssid was the last entry of the scan table and overloaded. */ void mwifiex_save_curr_bcn(struct mwifiex_private *priv) { struct mwifiex_bssdescriptor *curr_bss = &priv->curr_bss_params.bss_descriptor; if (!curr_bss->beacon_buf_size) return; /* allocate beacon buffer at 1st time; or if it's size has changed */ if (!priv->curr_bcn_buf || priv->curr_bcn_size != curr_bss->beacon_buf_size) { priv->curr_bcn_size = curr_bss->beacon_buf_size; kfree(priv->curr_bcn_buf); priv->curr_bcn_buf = kmalloc(curr_bss->beacon_buf_size, GFP_ATOMIC); if (!priv->curr_bcn_buf) return; } memcpy(priv->curr_bcn_buf, curr_bss->beacon_buf, curr_bss->beacon_buf_size); dev_dbg(priv->adapter->dev, "info: current beacon saved %d\n", priv->curr_bcn_size); curr_bss->beacon_buf = priv->curr_bcn_buf; /* adjust the pointers in the current BSS descriptor */ if (curr_bss->bcn_wpa_ie) curr_bss->bcn_wpa_ie = (struct ieee_types_vendor_specific *) (curr_bss->beacon_buf + curr_bss->wpa_offset); if (curr_bss->bcn_rsn_ie) curr_bss->bcn_rsn_ie = (struct ieee_types_generic *) (curr_bss->beacon_buf + curr_bss->rsn_offset); if (curr_bss->bcn_ht_cap) curr_bss->bcn_ht_cap = (struct ieee80211_ht_cap *) (curr_bss->beacon_buf + curr_bss->ht_cap_offset); if (curr_bss->bcn_ht_oper) curr_bss->bcn_ht_oper = (struct ieee80211_ht_operation *) (curr_bss->beacon_buf + curr_bss->ht_info_offset); if (curr_bss->bcn_vht_cap) curr_bss->bcn_vht_cap = (void *)(curr_bss->beacon_buf + curr_bss->vht_cap_offset); if (curr_bss->bcn_vht_oper) curr_bss->bcn_vht_oper = (void *)(curr_bss->beacon_buf + curr_bss->vht_info_offset); if (curr_bss->bcn_bss_co_2040) curr_bss->bcn_bss_co_2040 = (curr_bss->beacon_buf + curr_bss->bss_co_2040_offset); if (curr_bss->bcn_ext_cap) curr_bss->bcn_ext_cap = curr_bss->beacon_buf + curr_bss->ext_cap_offset; if (curr_bss->oper_mode) curr_bss->oper_mode = (void *)(curr_bss->beacon_buf + curr_bss->oper_mode_offset); } /* * This function frees the current BSS descriptor beacon buffer. */ void mwifiex_free_curr_bcn(struct mwifiex_private *priv) { kfree(priv->curr_bcn_buf); priv->curr_bcn_buf = NULL; }
rj011/Hacktoberfest2021-4
c++ problems asked in interview/Rotate Array(GFG).cpp
<filename>c++ problems asked in interview/Rotate Array(GFG).cpp Given an unsorted array arr[] of size N, rotate it by D elements (clockwise). Input: The first line of the input contains T denoting the number of testcases. First line of each test case contains two space separated elements, N denoting the size of the array and an integer D denoting the number size of the rotation. Subsequent line will be the N space separated array elements. Output: For each testcase, in a new line, output the rotated array. Example: Input: 2 5 2 1 2 3 4 5 10 3 2 4 6 8 10 12 14 16 18 20 Output: 3 4 5 1 2 8 10 12 14 16 18 20 2 4 6 Explanation : Testcase 1: 1 2 3 4 5 when rotated by 2 elements, it becomes 3 4 5 1 2. #include<bits/stdc++.h> using namespace std; int main() { int t; cin>>t; while(t--) { int n,d; cin>>n>>d; int a[n]; for(int i=0;i<n;i++) { cin>>a[(i+n-d)%n]; } for(int i=0;i<n;i++) { cout<<a[i]<<" "; } cout<<endl; } return 0; } Time Complexity - O(n) , because we are traversing the whole array once.
HaoyeTianCoder/coming
src/main/java/fr/inria/coming/core/entities/interfaces/IRevisionPair.java
package fr.inria.coming.core.entities.interfaces; /** * * @author <NAME> * * @param <T> */ public interface IRevisionPair<T> { public T getPreviousVersion(); public T getNextVersion(); public String getNextName(); public String getPreviousName(); public void setPreviousVersion(T previousContent); public void setNextVersion(T content); public void setNextName(String name); public void setPreviousName(String previousName); }
linmingdao/v-bonjure
build/bin/build.js
<reponame>linmingdao/v-bonjure<filename>build/bin/build.js #!/usr/bin/env node const executor = require('../task/executor'); executor.execute('build');
FavyTeam/Elderscape_server
source/network/sql/SQLConstants.java
<filename>source/network/sql/SQLConstants.java<gh_stars>1-10 package network.sql; /** * All table names added here for easy renaming. * @author <NAME>, created on 13-07-2018. */ public enum SQLConstants { OSRS_BOT, STATS_CONSOLE_PRINT_CRASH, STATS_CONSOLE_PRINT_GAME, STATS_PAYMENT_DAILY_TOTAL, STATS_PAYMENT_LATEST, STATS_PLAYER_ONLINE, STATS_TIME, STATS_TOPLIST, STATS_TOPLIST_ANTICAPTCHA_BALANCE, STATS_UNIQUE_IDENTIFIER_ANALYSIS, STATS_UNIQUE_IDENTIFIER_ANALYSIS_ALL, STATS_DOUBLE_ITEMS_NPC, STATS_DOUBLE_ITEMS_NPC_DAILY, STATS_DOUBLE_ITEMS_NPC_PLAYER, STATS_GIVEAWAY, STATS_PAID_YOUTUBER, STATS_OSRS_HISTORY, LOGS_LONG_STRING, OUTPUT_LOG; public static String getServerSchemaTable(SQLConstants entry) { return SCHEMA + entry.toTableName(); } public String toTableName() { return name().toLowerCase(); } public static String SCHEMA = "server."; }
whiterm/gravity
lib/vacuum/prune/registry/registry.go
/* Copyright 2018 Gravitational, 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 registry import ( "context" "strings" apps "github.com/gravitational/gravity/lib/app" appservice "github.com/gravitational/gravity/lib/app/service" "github.com/gravitational/gravity/lib/defaults" "github.com/gravitational/gravity/lib/docker" "github.com/gravitational/gravity/lib/loc" "github.com/gravitational/gravity/lib/pack" "github.com/gravitational/gravity/lib/state" "github.com/gravitational/gravity/lib/systemservice" "github.com/gravitational/gravity/lib/utils" "github.com/gravitational/gravity/lib/vacuum/prune" "github.com/gravitational/trace" log "github.com/sirupsen/logrus" ) // New creates a new registry cleaner func New(config Config) (*Cleanup, error) { if err := config.checkAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } return &Cleanup{ config: config, }, nil } func (r *Config) checkAndSetDefaults() error { if r.App == nil { return trace.BadParameter("application package is required") } if r.ImageService == nil { return trace.BadParameter("docker image service is required") } if r.Packages == nil { return trace.BadParameter("cluster package service is required") } if r.Apps == nil { return trace.BadParameter("cluster application service is required") } if r.FieldLogger == nil { r.FieldLogger = log.WithField(trace.Component, "gc:registry") } return nil } // Config describes configuration for the registry cleaner type Config struct { // Config specifies the common pruner configuration prune.Config // App specifies the cluster application App *loc.Locator // Packages specifies the cluster package service Packages pack.PackageService // Apps specifies the cluster application service Apps apps.Applications // ImageService specifies the docker image service ImageService docker.ImageService } // Prune removes unused docker images. // The registry state is reset by deleting the state from the filesystem // and re-running the docker image export for the cluster application. func (r *Cleanup) Prune(ctx context.Context) (err error) { r.config.PrintStepf("Stop registry service") if !r.config.DryRun { err = r.registryStop(ctx) defer func() { if err == nil { return } if errStart := r.registryStart(ctx); errStart != nil { r.config.Warn(errStart) } }() if err != nil { return trace.Wrap(err) } } stateDir, err := state.GetStateDir() if err != nil { return trace.Wrap(err) } dir := state.RegistryDir(stateDir) r.config.PrintStepf("Delete registry state directory %v", dir) if !r.config.DryRun { err = utils.RemoveContents(dir) if err != nil { return trace.Wrap(trace.ConvertSystemError(err), "failed to remove old registry state from %v.", dir) } } r.config.PrintStepf("Start registry service") if !r.config.DryRun { err = r.registryStart(ctx) if err != nil { return trace.Wrap(err) } } r.config.PrintStepf("Sync application state with registry") if r.config.DryRun { return nil } err = appservice.SyncApp(ctx, appservice.SyncRequest{ PackService: r.config.Packages, AppService: r.config.Apps, ImageService: r.config.ImageService, Package: *r.config.App, }) if err != nil { return trace.Wrap(err) } return nil } func (r *Cleanup) registryStart(ctx context.Context) error { out, err := r.serviceStart(ctx) if err != nil { return trace.Wrap(err, "failed to start the registry service: %s.", out) } err = r.waitForService(ctx, systemservice.ServiceStatusActive) if err != nil { return trace.Wrap(err, "failed to wait for the registry service to start") } return nil } func (r *Cleanup) registryStop(ctx context.Context) error { out, err := r.serviceStop(ctx) if err != nil { return trace.Wrap(err, "failed to stop the registry service: %s.", out) } err = r.waitForService(ctx, systemservice.ServiceStatusInactive) if err != nil { return trace.Wrap(err, "failed to wait for the registry service to stop") } return nil } func (r *Cleanup) waitForService(ctx context.Context, status string) error { localCtx, cancel := defaults.WithTimeout(ctx) defer cancel() b := utils.NewUnlimitedExponentialBackOff() err := utils.RetryWithInterval(localCtx, b, func() error { out, err := r.serviceStatus(localCtx) actualStatus := strings.TrimSpace(string(out)) if strings.HasPrefix(actualStatus, status) { return nil } return trace.Retry(err, "unexpected service status: %s", actualStatus) }) return trace.Wrap(err) } func (r *Cleanup) serviceStop(ctx context.Context) (output []byte, err error) { return serviceCtl(ctx, r.config.FieldLogger, "stop") } func (r *Cleanup) serviceStart(ctx context.Context) (output []byte, err error) { return serviceCtl(ctx, r.config.FieldLogger, "start") } func (r *Cleanup) serviceStatus(ctx context.Context) (output []byte, err error) { return serviceCtl(ctx, r.config.FieldLogger, "is-active") } // Cleanup implements garbage collection for docker registry type Cleanup struct { // config specifies the configuration for the cleanup config Config } func serviceCtl(ctx context.Context, log log.FieldLogger, args ...string) (output []byte, err error) { args = append([]string{"/bin/systemctl"}, append(args, "registry.service")...) output, err = utils.RunCommand(ctx, log, utils.PlanetCommandArgs(args...)...) return output, trace.Wrap(err) }
wu-hanqing/incubator-brpc
test/barrier_closure_unittest.cc
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "butil/barrier_closure.h" #include "butil/bind.h" #include <gtest/gtest.h> namespace { void Increment(int* count) { (*count)++; } TEST(BarrierClosureTest, RunImmediatelyForZeroClosures) { int count = 0; butil::Closure doneClosure(butil::Bind(&Increment, butil::Unretained(&count))); butil::Closure barrierClosure = butil::BarrierClosure(0, doneClosure); EXPECT_EQ(1, count); } TEST(BarrierClosureTest, RunAfterNumClosures) { int count = 0; butil::Closure doneClosure(butil::Bind(&Increment, butil::Unretained(&count))); butil::Closure barrierClosure = butil::BarrierClosure(2, doneClosure); EXPECT_EQ(0, count); barrierClosure.Run(); EXPECT_EQ(0, count); barrierClosure.Run(); EXPECT_EQ(1, count); } } // namespace
nakedible/vpnease-l2tp
openswan/openswan-2.4.0rc4.quilt/linux/include/openswan/ipsec_ipcomp.h
/* * IP compression header declations * * Copyright (C) 2003 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * RCSID $Id: ipsec_ipcomp.h,v 1.4 2004/07/10 19:08:41 mcr Exp $ */ #ifndef IPSEC_IPCOMP_H #define IPSEC_IPCOMP_H #include "openswan/ipsec_auth.h" /* Prefix all global deflate symbols with "ipcomp_" to avoid collisions with ppp_deflate & ext2comp */ #ifndef IPCOMP_PREFIX #define IPCOMP_PREFIX #endif /* IPCOMP_PREFIX */ #ifndef IPPROTO_COMP #define IPPROTO_COMP 108 #endif /* IPPROTO_COMP */ #ifdef CONFIG_KLIPS_DEBUG extern int sysctl_ipsec_debug_ipcomp; #endif /* CONFIG_KLIPS_DEBUG */ struct ipcomphdr { /* IPCOMP header */ __u8 ipcomp_nh; /* Next header (protocol) */ __u8 ipcomp_flags; /* Reserved, must be 0 */ __u16 ipcomp_cpi; /* Compression Parameter Index */ }; extern struct inet_protocol comp_protocol; extern int sysctl_ipsec_debug_ipcomp; #define IPCOMP_UNCOMPRESSABLE 0x000000001 #define IPCOMP_COMPRESSIONERROR 0x000000002 #define IPCOMP_PARMERROR 0x000000004 #define IPCOMP_DECOMPRESSIONERROR 0x000000008 #define IPCOMP_ADAPT_INITIAL_TRIES 8 #define IPCOMP_ADAPT_INITIAL_SKIP 4 #define IPCOMP_ADAPT_SUBSEQ_TRIES 2 #define IPCOMP_ADAPT_SUBSEQ_SKIP 8 /* Function prototypes */ struct sk_buff *skb_compress(struct sk_buff *skb, struct ipsec_sa *ips, unsigned int *flags); struct sk_buff *skb_decompress(struct sk_buff *skb, struct ipsec_sa *ips, unsigned int *flags); extern struct xform_functions ipcomp_xform_funcs[]; #endif /* IPSEC_IPCOMP_H */ /* * $Log: ipsec_ipcomp.h,v $ * Revision 1.4 2004/07/10 19:08:41 mcr * CONFIG_IPSEC -> CONFIG_KLIPS. * * Revision 1.3 2004/04/06 02:49:08 mcr * pullup of algo code from alg-branch. * * Revision 1.2 2004/04/05 19:55:05 mcr * Moved from linux/include/freeswan/ipsec_ipcomp.h,v * * Revision 1.1 2003/12/13 19:10:16 mcr * refactored rcv and xmit code - same as FS 2.05. * * Revision 1.2 2003/12/11 20:14:58 mcr * refactored the xmit code, to move all encapsulation * code into protocol functions. Note that all functions * are essentially done by a single function, which is probably * wrong. * the rcv_functions structures are renamed xform_functions. * * Revision 1.1 2003/12/06 21:21:19 mcr * split up receive path into per-transform files, for * easier later removal. * * * */
Luv8436/Leetcode
src/main/java/com/fishercoder/solutions/_56.java
package com.fishercoder.solutions; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class _56 { public static class Solution1 { public int[][] merge(int[][] intervals) { if (intervals.length <= 1) { return intervals; } Arrays.sort(intervals, (o1, o2) -> o1[0] - o2[0]); List<int[]> result = new ArrayList(); for (int i = 0; i < intervals.length; i++) { int start = intervals[i][0]; int end = intervals[i][1]; while (i < intervals.length && end >= intervals[i][0]) { end = Math.max(end, intervals[i][1]); i++; } result.add(new int[]{start, end}); i--; } int[][] finalResult = new int[result.size()][2]; for (int i = 0; i < result.size(); i++) { finalResult[i][0] = result.get(i)[0]; finalResult[i][1] = result.get(i)[1]; } return finalResult; } } }
AnilKumarBejjanki/drools
drools-compiler/src/main/java/org/drools/compiler/compiler/ProjectJavaCompiler.java
<reponame>AnilKumarBejjanki/drools<filename>drools-compiler/src/main/java/org/drools/compiler/compiler/ProjectJavaCompiler.java /* * Copyright 2015 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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.drools.compiler.compiler; import org.drools.compiler.builder.impl.KnowledgeBuilderConfigurationImpl; import org.drools.compiler.builder.impl.errors.ErrorHandler; import org.drools.compiler.builder.impl.errors.SrcErrorHandler; import org.drools.compiler.commons.jci.compilers.CompilationResult; import org.drools.compiler.commons.jci.compilers.JavaCompiler; import org.drools.compiler.commons.jci.compilers.JavaCompilerFactory; import org.drools.compiler.commons.jci.readers.MemoryResourceReader; import org.drools.compiler.commons.jci.stores.ResourceStore; import org.drools.compiler.rule.builder.dialect.java.JavaDialectConfiguration; import org.drools.core.common.ProjectClassLoader; import org.kie.internal.builder.KnowledgeBuilderResult; import org.kie.internal.jci.CompilationProblem; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.drools.core.util.ClassUtils.convertResourceToClassName; public class ProjectJavaCompiler { private final JavaCompiler compiler; public ProjectJavaCompiler(KnowledgeBuilderConfigurationImpl pkgConf) { this((JavaDialectConfiguration) pkgConf.getDialectConfiguration("java")); } public ProjectJavaCompiler(JavaDialectConfiguration configuration) { compiler = JavaCompilerFactory.getInstance().loadCompiler(configuration); } public List<KnowledgeBuilderResult> compileAll(ProjectClassLoader projectClassLoader, List<String> classList, MemoryResourceReader src) { List<KnowledgeBuilderResult> results = new ArrayList<KnowledgeBuilderResult>(); if ( classList.isEmpty() ) { return results; } final String[] classes = new String[classList.size()]; classList.toArray( classes ); CompilationResult result = compiler.compile( classes, src, new ProjectResourceStore(projectClassLoader), projectClassLoader ); if ( result.getErrors().length > 0 ) { Map<String, ErrorHandler> errorHandlerMap = new HashMap<String, ErrorHandler>(); for ( int i = 0; i < result.getErrors().length; i++ ) { final CompilationProblem err = result.getErrors()[i]; ErrorHandler handler = errorHandlerMap.get( err.getFileName() ); if (handler == null) { handler = new SrcErrorHandler("Src compile error"); errorHandlerMap.put(err.getFileName(), handler); } handler.addError( err ); } for (ErrorHandler handler : errorHandlerMap.values()) { if (handler.isInError()) { results.add(handler.getError()); } } } return results; } private static class ProjectResourceStore implements ResourceStore { private final ProjectClassLoader projectClassLoader; private ProjectResourceStore(ProjectClassLoader projectClassLoader) { this.projectClassLoader = projectClassLoader; } @Override public void write(String pResourceName, byte[] pResourceData) { projectClassLoader.defineClass(convertResourceToClassName(pResourceName), pResourceName, pResourceData); } @Override public void write(final String resourceName, final byte[] clazzData, boolean createFolder) { write(resourceName, clazzData); } @Override public byte[] read(String pResourceName) { return projectClassLoader.getBytecode(pResourceName); } @Override public void remove(String pResourceName) { throw new UnsupportedOperationException("org.drools.compiler.compiler.ProjectJavaCompiler.ProjectResourceStore.remove -> TODO"); } } }
ystk/debian-openmpi
ompi/mca/io/romio/romio/mpi-io/get_size.c
/* -*- Mode: C; c-basic-offset:4 ; -*- */ /* * * Copyright (C) 1997 University of Chicago. * See COPYRIGHT notice in top-level directory. */ #include "mpioimpl.h" #ifdef HAVE_WEAK_SYMBOLS #if defined(HAVE_PRAGMA_WEAK) #pragma weak MPI_File_get_size = PMPI_File_get_size #elif defined(HAVE_PRAGMA_HP_SEC_DEF) #pragma _HP_SECONDARY_DEF PMPI_File_get_size MPI_File_get_size #elif defined(HAVE_PRAGMA_CRI_DUP) #pragma _CRI duplicate MPI_File_get_size as PMPI_File_get_size /* end of weak pragmas */ #endif /* Include mapping from MPI->PMPI */ #define MPIO_BUILD_PROFILING #include "mpioprof.h" #endif /*@ MPI_File_get_size - Returns the file size Input Parameters: . fh - file handle (handle) Output Parameters: . size - size of the file in bytes (nonnegative integer) .N fortran @*/ int MPI_File_get_size(MPI_File mpi_fh, MPI_Offset *size) { int error_code; ADIO_File fh; ADIO_Fcntl_t *fcntl_struct; static char myname[] = "MPI_FILE_GET_SIZE"; #ifdef MPI_hpux int fl_xmpi; HPMP_IO_START(fl_xmpi, BLKMPIFILEGETSIZE, TRDTBLOCK, fh, MPI_DATATYPE_NULL, -1); #endif /* MPI_hpux */ MPIR_Nest_incr(); fh = MPIO_File_resolve(mpi_fh); /* --BEGIN ERROR HANDLING-- */ MPIO_CHECK_FILE_HANDLE(fh, myname, error_code); /* --END ERROR HANDLING-- */ ADIOI_TEST_DEFERRED(fh, myname, &error_code); fcntl_struct = (ADIO_Fcntl_t *) ADIOI_Malloc(sizeof(ADIO_Fcntl_t)); ADIO_Fcntl(fh, ADIO_FCNTL_GET_FSIZE, fcntl_struct, &error_code); /* --BEGIN ERROR HANDLING-- */ if (error_code != MPI_SUCCESS) error_code = MPIO_Err_return_file(fh, error_code); /* --END ERROR HANDLING-- */ *size = fcntl_struct->fsize; ADIOI_Free(fcntl_struct); #ifdef MPI_hpux HPMP_IO_END(fl_xmpi, fh, MPI_DATATYPE_NULL, -1); #endif /* MPI_hpux */ fn_exit: MPIR_Nest_decr(); return error_code; }
MelanieFJNR/Blitz-API
blitz_api/tests/tests_view_MailChimp.py
from rest_framework import status from rest_framework.test import APIClient, APITestCase from django.urls import reverse class MailChimpTests(APITestCase): def setUp(self): self.client = APIClient() def test_create(self): data = { 'email': '<EMAIL>', 'first_name': 'Chuck', 'last_name': 'Norris', } response = self.client.post( reverse('mail_chimp'), data, format='json', ) self.assertEqual( response.status_code, status.HTTP_201_CREATED, response.content )
JohnMai1994/CS246-2018_Fall_Term
1189/lectures/c++/multiple/virtual.cc
<filename>1189/lectures/c++/multiple/virtual.cc #include <iostream> using namespace std; class A { public: int a; }; class B: virtual public A { public: int b; }; class C: virtual public A { public: int c; }; class D: public B, public C { public: int d; }; int main () { D d; cout << d.a << endl; // Note: no longer ambiguous }
VoltzModpack/MFFS-Classic
src/main/java/ic2/api/reactor/IReactor.java
<gh_stars>0 package ic2.api.reactor; import net.minecraft.item.ItemStack; import net.minecraft.util.ChunkCoordinates; import net.minecraft.world.World; public interface IReactor { ChunkCoordinates getPosition(); World getWorld(); int getHeat(); void setHeat(int var1); int addHeat(int var1); int getMaxHeat(); void setMaxHeat(int var1); float getHeatEffectModifier(); void setHeatEffectModifier(float var1); int getOutput(); float addOutput(float var1); /** * @deprecated */ @Deprecated int addOutput(int var1); /** * @deprecated */ @Deprecated int getPulsePower(); ItemStack getItemAt(int var1, int var2); void setItemAt(int var1, int var2, ItemStack var3); void explode(); int getTickRate(); boolean produceEnergy(); }
chenj133/FATE
arch/eggroll/storage-service/src/main/java/com/webank/ai/fate/eggroll/storage/service/manager/LMDBStoreManager.java
<filename>arch/eggroll/storage-service/src/main/java/com/webank/ai/fate/eggroll/storage/service/manager/LMDBStoreManager.java /* * Copyright 2019 The FATE Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.webank.ai.fate.eggroll.storage.service.manager; import com.google.common.cache.*; import com.webank.ai.fate.core.io.KeyValueStore; import com.webank.ai.fate.core.io.StoreInfo; import com.webank.ai.fate.core.io.StoreManager; import com.webank.ai.fate.core.model.Bytes; import com.webank.ai.fate.eggroll.storage.service.model.LMDBStore; import com.webank.ai.fate.eggroll.storage.service.model.enums.Stores; import org.apache.commons.io.FileUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.FileTime; import java.util.Properties; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.TimeUnit; public class LMDBStoreManager implements StoreManager<Bytes, byte[]> { public static final String LMDB_TEMPORARY = "lmdb_temporary"; public static final String LMDB = "lmdb"; public static final long INMEMORY_RENTENTION_TIME = TimeUnit.DAYS.toMillis(2); private static Logger LOGGER = LogManager.getLogger(LMDBStoreManager.class); private static final RemovalListener<StoreInfo, LMDBStore> REMOVAL_LISTENER = new RemovalListener<StoreInfo, LMDBStore>() { @Override public void onRemoval(RemovalNotification<StoreInfo, LMDBStore> removalNotification) { LMDBStore store = removalNotification.getValue(); LOGGER.info("Evicting " + store.toString()); if (store.persistent()) { removalNotification.getValue().close(); } else { LOGGER.info("Destroying on removal " + store.toString()); store.destroy(); } } }; private final Timer timer; private final String parentDir; private LoadingCache<StoreInfo, LMDBStore> storeCache = CacheBuilder.newBuilder() .expireAfterAccess(360, TimeUnit.MINUTES) .removalListener(REMOVAL_LISTENER) .build(new CacheLoader<StoreInfo, LMDBStore>() { @Override public LMDBStore load(StoreInfo storeInfo) throws Exception { LMDBStore store = (LMDBStore) Stores.LMDB.create(storeInfo); LOGGER.info("Loading " + store.toString()); if (!store.isOpen()) { Properties properties = new Properties(); if (storeInfo.getType().equalsIgnoreCase(Stores.IN_MEMORY.name())) { // should config the same as python processor properties.put(LMDBStore.DATA_DIR, Paths.get(parentDir, LMDB_TEMPORARY).toString()); } else { properties.put(LMDBStore.DATA_DIR, Paths.get(parentDir, LMDB).toString()); } store.init(properties); LOGGER.info("Initiated " + store.toString()); } return store; } }); public LMDBStoreManager(String parentDir) { this.parentDir = parentDir; timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { cleanRoutine(); } }, 0, TimeUnit.HOURS.toMillis(1)); } @Override public KeyValueStore<Bytes, byte[]> getStore(StoreInfo info) { return storeCache.getIfPresent(info); } @Override public KeyValueStore<Bytes, byte[]> createIfMissing(StoreInfo info) { return storeCache.getUnchecked(info); } @Override public void destroy(StoreInfo info) { KeyValueStore<Bytes, byte[]> store = storeCache.getUnchecked(info); store.destroy(); storeCache.invalidate(info); LOGGER.info("Destroyed explicitly " + store.toString()); } public void destroy() { for (KeyValueStore<Bytes, byte[]> store : storeCache.asMap().values()) { store.destroy(); LOGGER.info("Destroyed in iter" + store.toString()); } storeCache.cleanUp(); } private void cleanRoutine() { File tempDirectory = Paths.get(parentDir, LMDB_TEMPORARY).toFile(); if (tempDirectory == null || !tempDirectory.isDirectory()) { return; } File[] inMemories = tempDirectory.listFiles(); if (inMemories == null) { return; } for (File dbFile : inMemories) { checkRetentionAndRemove(dbFile); } } private void checkRetentionAndRemove(File file) { boolean deleted = false; try { BasicFileAttributes attrs = Files.readAttributes(file.toPath(), BasicFileAttributes.class); FileTime fileTime = attrs.lastModifiedTime(); long current = System.currentTimeMillis(); long elapsed = current - fileTime.toMillis(); if (elapsed >= INMEMORY_RENTENTION_TIME) { deleted = FileUtils.deleteQuietly(file); LOGGER.info("Remove " + file.toPath().toString() + " " + deleted); } } catch (IOException e) { LOGGER.error("Get namespace meta error", e); } if (!deleted && file.isDirectory()) { File[] subFiles = file.listFiles(); if (null == subFiles) { return; } for (File subFile : subFiles) { checkRetentionAndRemove(subFile); } } } }
ShiftLeftSecurity/llvm2cpg
tests/fixtures/basic_c_support/APinlining.c
int nest_alias(int **x, int **y) { int res = x[2][3]; y[17] = x[1]; return res; // we can inline either tmp=x[2]; y[17]=x[1]; return tmp[3] or leave the code as is. // We cannot inline all of it. } int nest_noalias(int **restrict x, int **restrict y) { int res = x[2][3]; y[17] = x[1]; return res; // this can be fully inlined }
commitd/jonah-server
ketos-test/src/test/java/io/committed/ketos/test/common/providers/baleen/AbstractRelationProviderTest.java
<reponame>commitd/jonah-server package io.committed.ketos.test.common.providers.baleen; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.util.Collections; import java.util.List; import java.util.Optional; import org.junit.Test; import io.committed.invest.core.dto.analytic.TermBin; import io.committed.ketos.common.data.BaleenDocument; import io.committed.ketos.common.data.BaleenMention; import io.committed.ketos.common.data.BaleenRelation; import io.committed.ketos.common.graphql.input.RelationFilter; import io.committed.ketos.common.graphql.output.RelationSearch; import io.committed.ketos.common.providers.baleen.RelationProvider; public abstract class AbstractRelationProviderTest { public abstract RelationProvider getRelationProvider(); @Test public void testGetAll() { List<BaleenRelation> all = getRelationProvider().getAll(0, 1000).collectList().block(); assertEquals(1, all.size()); } @Test public void testGetByDocument() { BaleenDocument doc = new BaleenDocument("a19f6ed4-87bb-4dc6-919e-596761127082", null, "", null); List<BaleenRelation> relations = getRelationProvider().getByDocument(doc).collectList().block(); assertEquals(1, relations.size()); } @Test public void testGetSourceRelations() { BaleenMention mention = new BaleenMention(); mention.setId("b857d949-3ae6-4942-bcf5-e1e727eda58d"); List<BaleenRelation> sourceRelations = getRelationProvider().getSourceRelations(mention).collectList().block(); assertEquals(1, sourceRelations.size()); } @Test public void testGetTargetRelations() { BaleenMention mention = new BaleenMention(); mention.setId("a8672e25-0f23-43cf-b735-fba8f2d48f3b"); List<BaleenRelation> targetRelations = getRelationProvider().getTargetRelations(mention).collectList().block(); assertEquals(1, targetRelations.size()); } @Test public void testGetById() { BaleenRelation relation = getRelationProvider().getById("9dec8723-5ba5-4fb1-8718-6c12586aaa89").block(); assertNotNull(relation); assertEquals("9dec8723-5ba5-4fb1-8718-6c12586aaa89", relation.getId()); } @Test public void testCount() { long count = getRelationProvider().count().block(); assertEquals(1, count); } @Test public void testCountByField() { List<TermBin> results = getRelationProvider() .countByField(Optional.empty(), Collections.singletonList("type"), 1000) .collectList() .block(); assertEquals(1, results.size()); assertEquals(1, results.get(0).getCount()); } @Test public void testSearch() { RelationFilter filter = new RelationFilter(); filter.setType("associated"); RelationSearch search = new RelationSearch(null, filter); List<BaleenRelation> results = getRelationProvider().search(search, 0, 1000).getResults().collectList().block(); assertEquals(1, results.size()); } }
Mrxiaowu/J1120Client
J1120Client/jni/include/ime/IMEContext.h
/* * IMEContext.h * * Created on: Oct 30, 2017 * Author: guoxs */ #ifndef _IME_IMECONTEXT_H_ #define _IME_IMECONTEXT_H_ #include <string> class IMEContext { public: IMEContext(); virtual ~IMEContext(); typedef enum { E_IME_TEXT_TYPE_ALL, E_IME_TEXT_TYPE_NUMBER } EIMETextType; typedef struct { bool isPassword; char passwordChar; EIMETextType imeTextType; std::string text; } SIMETextInfo; class IIMETextUpdateListener { public: virtual ~IIMETextUpdateListener() { } virtual void onIMETextUpdate(const std::string &text) = 0; }; void setIMETextUpdateListener(IIMETextUpdateListener *pListener) { mIMETextUpdateListenerPtr = pListener; } void initIME(const SIMETextInfo &info, IIMETextUpdateListener *pListener); protected: virtual void onInitIME(const SIMETextInfo &info) { } void doneIMETextUpdate(const std::string &text); void cancelIMETextUpdate(); protected: IIMETextUpdateListener *mIMETextUpdateListenerPtr; SIMETextInfo mIMETextInfo; }; #endif /* _IME_IMECONTEXT_H_ */
suggestio/suggestio
src1/shared/common/shared/src/main/scala/io/suggest/app/ios/MIosManifest.scala
package io.suggest.app.ios import japgolly.univeq.UnivEq import play.api.libs.json._ import play.api.libs.functional.syntax._ /** * Suggest.io * User: <NAME> <<EMAIL>> * Created: 18.02.2020 15:50 * @see [[https://stackoverflow.com/a/56378044]] - Пример выхлопа для установочного манифеста. */ object MIosManifest { implicit def iosManifestJson: OFormat[MIosManifest] = { (__ \ "items").format[Seq[MIosItem]] .inmap[MIosManifest]( apply, _.items ) } @inline implicit def univEq: UnivEq[MIosManifest] = UnivEq.derive } case class MIosManifest( items: Seq[MIosItem] )
TheAngryByrd/fantasy
lib/fable-repl/Fable.Compiler/State.js
<gh_stars>1-10 import { filter, map as map_1, tryFind, create, tryGetValue } from "../fable-core/Map"; import _Map from "../fable-core/Map"; import { setType } from "../fable-core/Symbol"; import _Symbol from "../fable-core/Symbol"; import { comparePrimitives, makeGeneric, compareRecords, equalsRecords, Array as _Array, compareUnions, equals } from "../fable-core/Util"; import { FSharpErrorInfo } from "../symbols/SymbolHelpers"; import { FSharpImplementationFileContents } from "../symbols/Exprs"; import { FSharpProjectOptions } from "../service/service"; import { now } from "../fable-core/Date"; import { Path } from "../Fable.Core/Util"; import { choose, exists, filter as filter_1, map } from "../fable-core/Seq"; import { getValue } from "../fable-core/Option"; import Comparer from "../fable-core/Comparer"; import { getRootModuleFullName } from "./FSharp2Fable"; import { toText, printf, toFail, endsWith } from "../fable-core/String"; import { map as map_2 } from "../fable-core/Array"; import { union, create as create_1 } from "../fable-core/Set"; import { PluginInfo, CompilerOptions } from "../Fable.Core/Compiler"; import { ofArray, reverse } from "../fable-core/List"; import List from "../fable-core/List"; function Dictionary_2_GetOrAdd(key, valueFactory) { const matchValue = tryGetValue(this, key, null); if (matchValue[0]) { return matchValue[1]; } else { const v = valueFactory(key); this.set(key, v); return v; } } export { Dictionary_2_GetOrAdd as Dictionary$60$2$2E$GetOrAdd }; function Dictionary_2_AddOrUpdate(key, valueFactory, updateFactory) { if (this.has(key)) { const v = updateFactory(key, this.get(key)); this.set(key, v); return v; } else { const v_1 = valueFactory(key); this.set(key, v_1); return v_1; } } export { Dictionary_2_AddOrUpdate as Dictionary$60$2$2E$AddOrUpdate }; export class PathRef { constructor(tag, data) { this.tag = tag | 0; this.data = data; } [_Symbol.reflection]() { return { type: "Fable.State.PathRef", interfaces: ["FSharpUnion", "System.IEquatable", "System.IComparable"], cases: [["FilePath", "string"], ["NonFilePath", "string"]] }; } Equals(other) { return this === other || this.tag === other.tag && equals(this.data, other.data); } CompareTo(other) { return compareUnions(this, other) | 0; } } setType("Fable.State.PathRef", PathRef); export class FileInfo { constructor(sentToClient, dependencies) { this.SentToClient = sentToClient; this.Dependencies = dependencies; } [_Symbol.reflection]() { return { type: "Fable.State.FileInfo", interfaces: ["FSharpRecord", "System.IEquatable", "System.IComparable"], properties: { SentToClient: "boolean", Dependencies: _Array("string") } }; } Equals(other) { return equalsRecords(this, other); } CompareTo(other) { return compareRecords(this, other) | 0; } } setType("Fable.State.FileInfo", FileInfo); export class Project { [_Symbol.reflection]() { return { type: "Fable.State.Project", interfaces: ["Fable.ICompilerState"], properties: { Errors: _Array(FSharpErrorInfo), FableCore: PathRef, ImplementationFiles: makeGeneric(_Map, { Key: "string", Value: FSharpImplementationFileContents }), IsWatchCompile: "boolean", ProjectFile: "string", ProjectOptions: FSharpProjectOptions, TimeStamp: Date } }; } constructor(projectOptions, implFiles, errors, dependencies, fableCore, isWatchCompile) { this.projectOptions = projectOptions; this.implFiles = implFiles; this.errors = errors; this.fableCore = fableCore; this.isWatchCompile = isWatchCompile; this.timestamp = now(); this.projectFile = Path.normalizePath(this.projectOptions.ProjectFileName); this.entities = new Map(); this.inlineExprs = new Map(); this.normalizedFiles = create(map(f => { const path = Path.normalizeFullPath(f); const matchValue = tryFind(path, dependencies); if (matchValue == null) { return [path, new FileInfo(false, [])]; } else { return [path, new FileInfo(false, getValue(matchValue))]; } }, this.projectOptions.SourceFiles), new Comparer(comparePrimitives)); this.rootModules = map_1((_arg2, file) => getRootModuleFullName(file), filter((file_1, _arg1) => !endsWith(file_1, "fsi"), this.implFiles)); } get TimeStamp() { return this.timestamp; } get FableCore() { return this.fableCore; } get IsWatchCompile() { return this.isWatchCompile; } get ImplementationFiles() { return this.implFiles; } get Errors() { return this.errors; } get ProjectOptions() { return this.projectOptions; } get ProjectFile_0() { return this.projectFile; } ContainsFile(sourceFile) { return this.normalizedFiles.has(sourceFile); } HasSent(sourceFile) { return this.normalizedFiles.get(sourceFile).SentToClient; } MarkSent(sourceFile) { const matchValue = tryFind(sourceFile, this.normalizedFiles); if (matchValue == null) {} else { getValue(matchValue).SentToClient = true; } } GetDependencies() { return map_1((_arg3, info) => info.Dependencies, this.normalizedFiles); } AddDependencies(sourceFile, dependencies) { const matchValue = tryFind(sourceFile, this.normalizedFiles); if (matchValue == null) {} else { getValue(matchValue).Dependencies = map_2(path => Path.normalizePath(path), dependencies, Array); } } GetFilesAndDependent(files) { const files_1 = create_1(files, new Comparer(comparePrimitives)); const dependentFiles = create_1(map(kv => kv[0], filter_1(kv_1 => exists(arg00 => files_1.has(arg00), kv_1[1].Dependencies), this.normalizedFiles)), new Comparer(comparePrimitives)); const filesAndDependent = union(files_1, dependentFiles); return Array.from(choose(kv_2 => filesAndDependent.has(kv_2[0]) ? kv_2[0] : null, this.normalizedFiles)); } get ProjectFile() { return this.projectOptions.ProjectFileName; } GetRootModule(fileName) { const matchValue = tryFind(fileName, this.rootModules); if (matchValue == null) { return toFail(printf("Cannot find root module for %s"))(fileName); } else { return getValue(matchValue); } } GetOrAddEntity(fullName, generate) { return Dictionary_2_GetOrAdd.bind(this.entities)(fullName, _arg4 => generate()); } GetOrAddInlineExpr(fullName, generate) { return Dictionary_2_GetOrAdd.bind(this.inlineExprs)(fullName, _arg5 => generate()); } } setType("Fable.State.Project", Project); export function getDefaultFableCore() { return "fable-core"; } export function getDefaultOptions(replacements) { const replacements_1 = replacements == null ? create(null, new Comparer(comparePrimitives)) : create(getValue(replacements), new Comparer(comparePrimitives)); return new CompilerOptions(getDefaultFableCore(), replacements_1, true, false, false); } export class Compiler { [_Symbol.reflection]() { return { type: "Fable.State.Compiler", interfaces: ["Fable.ICompiler"], properties: { Options: CompilerOptions, Plugins: makeGeneric(List, { T: PluginInfo }) } }; } constructor(options, replacements, plugins) { this.id = 0; if (options != null) { this["options@114"] = options; } else { this["options@114"] = getDefaultOptions(replacements); } if (plugins != null) { this["plugins@115"] = plugins; } else { this["plugins@115"] = new List(); } this.logs = new Map(); } ReadAllLogs() { return create(map(kv => [kv[0], reverse(kv[1])], this.logs), new Comparer(comparePrimitives)); } get Options_0() { return this["options@114"]; } get Plugins_0() { return this["plugins@115"]; } get Options() { return this["options@114"]; } get Plugins() { return this["plugins@115"]; } AddLog(msg, severity, range, fileName, tag) { const tag_1 = tag != null ? tag : "FABLE"; const severity_1 = severity.tag === 1 ? "error" : severity.tag === 2 ? "info" : "warning"; const formattedMsg = fileName == null ? msg : range == null ? toText(printf("%s(1,1): %s %s: %s"))(getValue(fileName), severity_1, tag_1, msg) : toText(printf("%s(%i,%i): (%i,%i) %s %s: %s"))(getValue(fileName), getValue(range).start.line, getValue(range).start.column, getValue(range).end.line, getValue(range).end.column, severity_1, tag_1, msg); if (this.logs.has(severity_1)) { this.logs.set(severity_1, new List(formattedMsg, this.logs.get(severity_1))); } else { this.logs.set(severity_1, ofArray([formattedMsg])); } } GetUniqueVar() { this.id = this.id + 1 | 0; return "$var" + this.id.toString(); } } setType("Fable.State.Compiler", Compiler);
whutch/cwmud
cwmud/core/commands/info/look.py
<filename>cwmud/core/commands/info/look.py # -*- coding: utf-8 -*- """Look command.""" # Part of Clockwork MUD Server (https://github.com/whutch/cwmud) # :copyright: (c) 2008 - 2017 <NAME> # :license: MIT (https://github.com/whutch/cwmud/blob/master/LICENSE.txt) from .. import Command, COMMANDS from ...characters import CharacterShell @COMMANDS.register class LookCommand(Command): """A command to allow a character to look at things.""" def _action(self): char = self.session.char if not char: self.session.send("You're not playing a character!") return if not char.room: self.session.send("You're not in a room!") return char.show_room() CharacterShell.add_verbs(LookCommand, "look", "l")
matty234/client
shared/common-adapters/badge.js
<reponame>matty234/client // @flow import * as React from 'react' import Box from './box' import Text from './text' import * as Styles from '../styles' export type Badge2Props = {| badgeNumber: number, className?: string, fontSize: number, height: number, leftRightPadding: number, badgeStyle?: Styles.StylesCrossPlatform, badgeNumberStyle?: Styles.StylesCrossPlatform, |} export type DefaultBadge2Props = {fontSize: number, height: number, leftRightPadding: number} export default class Badge extends React.Component<Badge2Props> { static defaultProps = { fontSize: Styles.isMobile ? 12 : 10, height: Styles.isMobile ? 20 : 16, leftRightPadding: Styles.isMobile ? 3 : 4, } render() { return ( <Box className={this.props.className} style={Styles.collapseStyles([ styles.badge, { borderRadius: this.props.height, height: this.props.height, minWidth: this.props.height, paddingLeft: this.props.leftRightPadding, paddingRight: this.props.leftRightPadding, }, this.props.badgeStyle, ])} > <Text center={true} type="BodyTinyBold" style={Styles.collapseStyles([ styles.text, { fontSize: this.props.fontSize, height: this.props.height, lineHeight: Styles.isMobile ? this.props.height : `${this.props.height}px`, }, this.props.badgeNumberStyle, ])} > {this.props.badgeNumber} </Text> </Box> ) } } const styles = Styles.styleSheetCreate({ badge: { ...Styles.globalStyles.flexBoxRow, ...Styles.globalStyles.flexBoxCenter, backgroundColor: Styles.globalColors.orange, }, text: { color: Styles.globalColors.white, }, })
shanirogers/early-careers-framework
db/seeds/initial_seed.rb
<filename>db/seeds/initial_seed.rb # frozen_string_literal: true cohort_2021 = Cohort.find_or_create_by!(start_year: 2021) ambition_cip = CoreInductionProgramme.find_or_create_by!(name: "Ambition Institute") edt_cip = CoreInductionProgramme.find_or_create_by!(name: "Education Development Trust") teach_first_cip = CoreInductionProgramme.find_or_create_by!(name: "Teach First") ucl_cip = CoreInductionProgramme.find_or_create_by!(name: "UCL Institute of Education") ambition = LeadProvider.find_or_create_by!(name: "Ambition Institute") ambition.update!(cohorts: [cohort_2021]) unless ambition.cohorts.any? LeadProviderCip.find_or_create_by!(lead_provider: ambition, cohort: cohort_2021, core_induction_programme: ambition_cip) bpn = LeadProvider.find_or_create_by!(name: "Best Practice Network") bpn.update!(cohorts: [cohort_2021]) unless bpn.cohorts.any? LeadProviderCip.find_or_create_by!(lead_provider: bpn, cohort: cohort_2021, core_induction_programme: ucl_cip) capita = LeadProvider.find_or_create_by!(name: "Capita") capita.update!(cohorts: [cohort_2021]) unless capita.cohorts.any? LeadProviderCip.find_or_create_by!(lead_provider: capita, cohort: cohort_2021, core_induction_programme: ambition_cip) edt = LeadProvider.find_or_create_by!(name: "Education Development Trust") edt.update!(cohorts: [cohort_2021]) unless edt.cohorts.any? LeadProviderCip.find_or_create_by!(lead_provider: edt, cohort: cohort_2021, core_induction_programme: edt_cip) teach_first = LeadProvider.find_or_create_by!(name: "<NAME>") teach_first.update!(cohorts: [cohort_2021]) unless teach_first.cohorts.any? LeadProviderCip.find_or_create_by!(lead_provider: teach_first, cohort: cohort_2021, core_induction_programme: teach_first_cip) ucl = LeadProvider.find_or_create_by!(name: "UCL Institute of Education") ucl.update!(cohorts: [cohort_2021]) unless ucl.cohorts.any? LeadProviderCip.find_or_create_by!(lead_provider: ucl, cohort: cohort_2021, core_induction_programme: ucl_cip) PrivacyPolicy.find_or_initialize_by(major_version: 1, minor_version: 0) .tap { |pp| pp.html = Rails.root.join("db/seeds/privacy_policy_1.0.html").read } .save!
smartarch/qoscloud
cloud_controller/monitor/ue_monitor.py
import logging import grpc from cloud_controller import CLIENT_CONTROLLER_HOST, CLIENT_CONTROLLER_PORT from cloud_controller.knowledge.knowledge import Knowledge from cloud_controller.knowledge.knowledge_pb2_grpc import ClientControllerInternalStub from cloud_controller.middleware.helpers import connect_to_grpc_server from cloud_controller.monitor.monitor import Monitor class UEMonitor(Monitor): """ Updates User Equipment records on client controller according to the current state of the UserEquipmentContainer in Knowledge """ def __init__(self, knowledge: Knowledge): super().__init__(knowledge) self.client_controller = connect_to_grpc_server(ClientControllerInternalStub, CLIENT_CONTROLLER_HOST, CLIENT_CONTROLLER_PORT) def monitor(self) -> None: try: for ue in self._knowledge.user_equipment.list_new_ue(): self.client_controller.AddNewUE(ue) for ue in self._knowledge.user_equipment.list_removed_ue(): self.client_controller.RemoveUE(ue) except grpc._channel._Rendezvous: logging.info("Could not connect to the client controller. Proceeding without UE updates.")
engfrosh/engfrosh
engfrosh_bot/rabbit_listener.py
import logging import os import asyncio import functools import json import pika CURRENT_DIRECTORY = os.path.dirname(__file__) LOG_LEVEL = logging.DEBUG # region Logging Setup SCRIPT_NAME = os.path.splitext(os.path.basename(__file__))[0] logger = logging.getLogger(SCRIPT_NAME) if __name__ == "__main__": LOG_FILE = CURRENT_DIRECTORY + "/{}.log".format(SCRIPT_NAME) if os.path.exists(LOG_FILE): try: os.remove(LOG_FILE) except PermissionError: pass logging.basicConfig(level=LOG_LEVEL, filename=LOG_FILE) logger.debug("Module started.") logger.debug("Log file set as: %s", LOG_FILE) logger.debug("Set current directory as: %s", CURRENT_DIRECTORY) # endregion def handle_queued_command(ch, method, properties, body, args): discord_loop, discord_queue_callback = args message = json.loads(body) if type(message) != dict: logger.error(f"Message not dict. Ignored: {message}") elif message["type"] != "discord.py": logger.warning(f"Message not discord message. Ignored: {message}") else: message.pop("type") asyncio.run_coroutine_threadsafe( discord_queue_callback(message), discord_loop) return def rabbit_main(discord_loop, discord_queue_callback, host, queue): connection = pika.BlockingConnection(pika.ConnectionParameters(host)) rabbit_channel = connection.channel() rabbit_channel.queue_declare(queue=queue) handle_queued_command_callback = functools.partial( handle_queued_command, args=(discord_loop, discord_queue_callback)) rabbit_channel.basic_consume(queue=queue, auto_ack=True, on_message_callback=handle_queued_command_callback) rabbit_channel.start_consuming()
pjpv/python_django_video
apps/video/migrations/0006_videomodel_add_time.py
# Generated by Django 2.1.3 on 2018-11-24 07:06 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('video', '0005_videomodel_live'), ] operations = [ migrations.AddField( model_name='videomodel', name='add_time', field=models.DateTimeField(auto_now=True, help_text='添加时间', verbose_name='添加时间'), ), ]
shunyama/nuita
test/test_helper.rb
<gh_stars>10-100 require 'simplecov' SimpleCov.start 'rails' if ENV['UPLOAD_COVERAGE'] == 'true' require 'codecov' SimpleCov.formatter = SimpleCov::Formatter::Codecov end ENV['RAILS_ENV'] ||= 'test' require_relative '../config/environment' require 'rails/test_help' module ActiveSupport class TestCase # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. fixtures :all # Add more helper methods to be used by all tests here... end end
Silfryi/BASE
src/main/java/com/teamacronymcoders/base/client/models/sided/ModelSidedBlock.java
package com.teamacronymcoders.base.client.models.sided; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.teamacronymcoders.base.blocks.properties.SideType; import com.teamacronymcoders.base.client.models.ModelUtils; import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.vertex.VertexFormat; import net.minecraft.util.EnumFacing; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.model.IModel; import net.minecraftforge.common.model.IModelState; import javax.annotation.Nonnull; import javax.annotation.ParametersAreNonnullByDefault; import java.util.Collection; import java.util.function.Function; public class ModelSidedBlock implements IModel { private final String name; private final String type; private final ImmutableMap<String, ResourceLocation> textures; public ModelSidedBlock(String name, String type, ImmutableMap<String, ResourceLocation> textures) { this.name = name; this.type = type; this.textures = textures; } @Override @Nonnull public Collection<ResourceLocation> getDependencies() { return ImmutableList.of(); } @Override @Nonnull public Collection<ResourceLocation> getTextures() { return textures.values(); } @Override @Nonnull @ParametersAreNonnullByDefault public IBakedModel bake(IModelState state, VertexFormat format, Function<ResourceLocation, TextureAtlasSprite> bakedTextureGetter) { TextureAtlasSprite[][] tex = new TextureAtlasSprite[6][3]; for (EnumFacing f : EnumFacing.VALUES) { for (SideType cfg : SideType.values()) { ResourceLocation resourceLocation = textures.get(f.getName() + "_" + cfg.getName()); if (resourceLocation != null) { tex[f.ordinal()][cfg.ordinal()] = ModelUtils.getBlockSprite(resourceLocation); } } } return new BakedModelSidedBlock(name, tex); } @Override @Nonnull public IModel retexture(ImmutableMap<String, String> textures) { String newName = this.name; ImmutableMap.Builder<String, ResourceLocation> builder = ImmutableMap.builder(); for (EnumFacing f : EnumFacing.VALUES) { for (SideType cfg : SideType.values()) { String key = f.getName() + "_" + cfg.getName(); ResourceLocation resourceLocation = this.textures.get(key); if (textures.containsKey(key)) { resourceLocation = new ResourceLocation(textures.get(key)); } else if (textures.containsKey(f.getName())) { ITextureNamer namer = SidedTypeRegistry.getTextureNamer(type); resourceLocation = new ResourceLocation(textures.get(f.getName())); if (namer != null) { String c = namer.nameFromCfg(f, cfg); if (c != null) { resourceLocation = new ResourceLocation(textures.get(f.getName()) + "_" + c); } } } else if (textures.containsKey("name")) { ITextureNamer namer = SidedTypeRegistry.getTextureNamer(type); newName = textures.get("name"); if (namer != null) { resourceLocation = new ResourceLocation(newName + "_" + namer.getTextureName(f, cfg)); } } builder.put(key, resourceLocation); } } return new ModelSidedBlock(newName, type, builder.build()); } }
maricaantonacci/alien4cloud
alien4cloud-core/src/main/java/alien4cloud/topology/validation/LocationPolicyValidationService.java
<reponame>maricaantonacci/alien4cloud package alien4cloud.topology.validation; import static alien4cloud.utils.AlienUtils.safe; import java.util.List; import java.util.Objects; import javax.annotation.Resource; import org.alien4cloud.alm.deployment.configuration.model.DeploymentMatchingConfiguration; import org.apache.commons.lang3.StringUtils; import org.springframework.security.access.AccessDeniedException; import org.springframework.stereotype.Component; import com.google.common.collect.Lists; import alien4cloud.model.orchestrators.Orchestrator; import alien4cloud.model.orchestrators.OrchestratorState; import alien4cloud.model.orchestrators.locations.Location; import alien4cloud.orchestrators.locations.services.LocationSecurityService; import alien4cloud.orchestrators.locations.services.LocationService; import alien4cloud.orchestrators.services.OrchestratorService; import alien4cloud.topology.task.LocationPolicyTask; import alien4cloud.topology.task.TaskCode; import alien4cloud.topology.task.UnavailableLocationTask; import alien4cloud.utils.AlienConstants; /** * Performs validation by checking location policies. */ @Component public class LocationPolicyValidationService { @Resource private LocationService locationService; @Resource private OrchestratorService orchestratorService; @Resource private LocationSecurityService locationSecurityService; public List<LocationPolicyTask> validateLocationPolicies(DeploymentMatchingConfiguration matchingConfiguration) { List<LocationPolicyTask> tasks = Lists.newArrayList(); Location location = null; Orchestrator orchestrator = null; // TODO change this later, as now we only support one location policy and only for _A4C_ALL group String locationId = safe(matchingConfiguration.getLocationIds()).get(AlienConstants.GROUP_ALL); if (StringUtils.isBlank(locationId)) { tasks.add(new LocationPolicyTask()); } else { location = locationService.getOrFail(locationId); orchestrator = orchestratorService.getOrFail(location.getOrchestratorId()); try { // if a location already exists, then check the rigths on it locationSecurityService.checkAuthorisation(location, matchingConfiguration.getEnvironmentId()); // check the orchestrator is still enabled if (!Objects.equals(orchestrator.getState(), OrchestratorState.CONNECTED)) { UnavailableLocationTask task = new UnavailableLocationTask(location.getName(), orchestrator.getName()); task.setCode(TaskCode.LOCATION_DISABLED); tasks.add(task); } } catch (AccessDeniedException e) { UnavailableLocationTask task = new UnavailableLocationTask(location.getName(), orchestrator.getName()); task.setCode(TaskCode.LOCATION_UNAUTHORIZED); tasks.add(task); } } return tasks; } }
sadupally/Dev
unisa-tools/unisa-canceluser/src/java/za/ac/unisa/lms/tools/canceluser/dao/CancelUserStudentQueryDAO.java
package za.ac.unisa.lms.tools.canceluser.dao; import java.net.InetAddress; import java.sql.Timestamp; import java.util.Calendar; import java.util.Iterator; import java.util.List; import org.apache.commons.collections.map.ListOrderedMap; import org.springframework.jdbc.core.JdbcTemplate; import za.ac.unisa.lms.db.StudentSystemDAO; public class CancelUserStudentQueryDAO extends StudentSystemDAO { public boolean getvalidStudent(String studentNr) throws Exception{ // Get valid Student number String studentNrTmp = ""; boolean studentExist = false; String sql = " select nr "+ " from stu " + " where nr = "+studentNr; try { studentNrTmp = this.querySingleValue(sql,"NR"); if ((studentNrTmp == null)||(studentNrTmp.length() == 0)) { studentNr = " "; studentExist = false; } else { studentExist = true; } } catch (Exception ex) { throw new Exception("CancelUserStudentQueryDAO : getvalidStudent / "+ ex,ex); } return studentExist ; } public StudentInfo getStudentDetails(String stno){ StudentInfo studentInfo = new StudentInfo(); List studentList = null; String sql = "select NR, INITIALS, SURNAME from stu where NR = "+stno; JdbcTemplate jdt = new JdbcTemplate(getDataSource()); studentList = jdt.queryForList(sql); Iterator i = studentList.iterator(); while(i.hasNext()){ ListOrderedMap data = (ListOrderedMap) i.next(); studentInfo.setStudentNr(data.get("NR").toString()); studentInfo.setStudentName(data.get("INITIALS").toString()); studentInfo.setSurname(data.get("SURNAME").toString()); } return studentInfo; } public void setUserInactiveSOLACT (String studentNr) throws Exception{ String sql = " UPDATE SOLACT" + " SET ACT_STATUS = 'N'"+ " where student_NR = "+studentNr; System.out.println("update: "+sql); try{ JdbcTemplate jdt1 = new JdbcTemplate(getDataSource()); jdt1.update(sql); } catch (Exception ex) { throw new Exception("CancelUserStudentQueryDAO: setUserInactiveSOLACT (Update): Error occurred /"+ ex,ex); } } public void setMyLifeUserInactiveSOLACT (String studentNr) throws Exception{ String sql = " UPDATE JOIN_ACTIVATE SET MYLIFE_ACT_STATUS = 'N'"+ " where USER_ID= "+studentNr; try{ JdbcTemplate jdt1 = new JdbcTemplate(getDataSource()); jdt1.update(sql); } catch (Exception ex) { } } public void setUserInactiveSTUANN (String studentNr) throws Exception{ String sql = "UPDATE STUANN set SOL_USER_FLAG = 'N' where mk_academic_year = (select max(mk_academic_year)from stuann where mk_student_nr = "+ studentNr +")"+ " and mk_student_nr ="+ studentNr; System.out.println("update: "+sql); try{ JdbcTemplate jdt1 = new JdbcTemplate(getDataSource()); // jdt1.update(sql);1` m } catch (Exception ex) { throw new Exception("CancelUserStudentQueryDAO: setUserInactiveSOLACT (Update): Error occurred /"+ ex,ex); } } public void insertAuditLog (String studentNr) throws Exception{ InetAddress thisIp = InetAddress.getLocalHost(); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(new java.util.Date().getTime()); String sql = " INSERT INTO SOLGEN" + " (STUDENT_NR,TIMESTAMP,IPADDRESS, CATEGORY,DESCRIPTION,COURSE,SYSTEM_GC6,SEQUENCE_NR)"+ " VALUES (?,?,?,?,?,?,?,solgen_sequence_nr.nextval)"; System.out.println("update: "+sql); String category = "CSUSR"; String description = "Cancellation of Sol user"; try{ JdbcTemplate jdt1 = new JdbcTemplate(getDataSource()); jdt1.update(sql,new Object[] { studentNr,new Timestamp(cal.getTimeInMillis()),thisIp.getHostAddress(),category,description,"",""}); } catch (Exception ex) { throw new Exception("CancelUserStudentQueryDAO: insertAuditLog (Update): Error occurred /"+ ex,ex); } } /** * method: querySingleValue * This method executes a query and returns a String value as result. * An empty String value is returned if the query returns no results. * * @param query The query to be executed on the database * @param field The field that is queried on the database * method written by: <NAME> */ private String querySingleValue(String query, String field){ JdbcTemplate jdt = new JdbcTemplate(getDataSource()); List queryList; String result = ""; queryList = jdt.queryForList(query); Iterator i = queryList.iterator(); i = queryList.iterator(); if (i.hasNext()) { ListOrderedMap data = (ListOrderedMap) i.next(); if (data.get(field) == null){ } else { result = data.get(field).toString(); } } return result; } public String getBlockedStatus(String studentNr) { String query = "select status_flag from JOIN_ACTIVATE where USER_ID ="+studentNr; return querySingleValue(query,"status_flag"); } }
SVADemoAPP/02_SVA_DEMO_APP_ANDROID
ImageMap/src/com/hck/imagemap/Dao/MessageDao.java
<filename>ImageMap/src/com/hck/imagemap/Dao/MessageDao.java package com.hck.imagemap.Dao; import java.util.ArrayList; import java.util.List; import com.hck.imagemap.db.MessageDB; import com.hck.imagemap.entity.MessageContent; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; public class MessageDao { public MessageDB helper; public MessageDao(Context context) { helper = new MessageDB(context); } /** * 添加一条记录 */ public boolean add(int _num, String _wucha, String _T, String _TOF, String _FOT, String _Ten, String _time) { SQLiteDatabase db = helper.getWritableDatabase(); if (db.isOpen()) { // 执行添加数据的SQL语句 db.execSQL( "insert into _result (_num , _wucha ,_T ,_TOF ,_FOT ,_Ten,_time) values (?,?,?,?,?,?,?)", new Object[] { _num, _wucha, _T, _TOF, _FOT, _Ten, _time }); db.close(); return true; } // 如果代码能够执行到这一步,说明上面的添加操作也执行了。所以查询的返回值必定为true else { return false; } } public void delete(String time) { SQLiteDatabase db = helper.getWritableDatabase(); if (db.isOpen()) { // 执行添加数据的SQL语句 db.execSQL("delete from _result where _time=?", new Object[] { time }); db.close(); } } public List<MessageContent> findAll() { // 定义好要返回的对象 List<MessageContent> numbers = new ArrayList<MessageContent>(); SQLiteDatabase db = helper.getReadableDatabase(); if (db.isOpen()) { // 查询blacknumber表中的所有号码 Cursor cursor = db.rawQuery( "select _num,_wucha,_T,_TOF,_FOT,_Ten,_time from _result", null); // 循环遍历结果集,将每个结果集封装后添加到集合中 while (cursor.moveToNext()) { MessageContent contents = new MessageContent(); contents.set_num(cursor.getInt(0)); contents.set_wucha(cursor.getString(1)); contents.set_T(cursor.getString(2)); contents.set_TOF(cursor.getString(3)); contents.set_FOT(cursor.getString(4)); contents.set_Ten(cursor.getString(5)); contents.set_time(cursor.getString(6)); numbers.add(contents); contents = null; } cursor.close(); db.close(); } return numbers; } }
fluxtah/mechanoid
examples/movies/src-gen/com/robotoworks/example/movies/ops/AbstractMoviesService.java
/* * Generated by Robotoworks Mechanoid */ package com.robotoworks.example.movies.ops; import com.robotoworks.mechanoid.ops.OperationProcessor; import com.robotoworks.mechanoid.ops.OperationService; import com.robotoworks.mechanoid.ops.OperationServiceConfiguration; import com.robotoworks.example.movies.ops.MoviesProcessor; public abstract class AbstractMoviesService extends OperationService { public static final OperationServiceConfiguration CONFIG = new MoviesServiceConfiguration(); @Override protected OperationProcessor createProcessor() { return new MoviesProcessor(this); } public AbstractMoviesService(boolean enableLogging) { super(enableLogging); } }
nitro-neal/mypass-oauth
src/fe.js
import * as React from 'react'; import { render } from 'react-dom'; // import Login from './components/pages/login'; import Settings from './components/pages/settings'; // import Register from './components/pages/register'; // import PalmTest from './components/pages/PalmTest'; // import Login from './components/pages/login'; // import './index.scss'; render( <Settings />, document.getElementById('root') );
factset/enterprise-sdk
code/typescript/StandardDatafeed/v1/src/model/ListFiles400Response.js
/** * SDF_API * The Standard Datafeed (SDF) API provides an alternative method for users to request and retrieve SDF packages (schemas & bundles). This service is not a direct replacement and does not have 100% feature parity with the Loader. This API provides an alternative for users who are unable to utilize the Loader due to: Unable to install 3rd party executables due to Corporate Security policies Unable to utilize the Loader due to limitations or restrictions with the environment used to consume Standard Datafeed Clients who are utilizing existing delivery method like FTP, who may want to use a more secured & modern solution This API allows users to retrieve SDF packages they have subscriptions for, going back to August 31, 2021. Additional parameters are available to filter requests to get the exact files users are looking for. * * The version of the OpenAPI document: 1.0 * Contact: <EMAIL> * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. * */ import ApiClient from '../ApiClient'; /** * The ListFiles400Response model module. * @module model/ListFiles400Response * @version 0.20.0 */ class ListFiles400Response { /** * Constructs a new <code>ListFiles400Response</code>. * @alias module:model/ListFiles400Response */ constructor() { ListFiles400Response.initialize(this); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj) { } /** * Constructs a <code>ListFiles400Response</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/ListFiles400Response} obj Optional instance to populate. * @return {module:model/ListFiles400Response} The populated <code>ListFiles400Response</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new ListFiles400Response(); if (data.hasOwnProperty('data')) { obj['data'] = ApiClient.convertToType(data['data'], 'String'); } if (data.hasOwnProperty('meta')) { obj['meta'] = ApiClient.convertToType(data['meta'], 'String'); } } return obj; } } /** * @member {String} data */ ListFiles400Response.prototype['data'] = undefined; /** * @member {String} meta */ ListFiles400Response.prototype['meta'] = undefined; export default ListFiles400Response;
TehFishey/pixelmon-spawn-editor
src/main/java/com/github/tehfishey/spawnedit/model/FileLoader.java
package com.github.tehfishey.spawnedit.model; import java.io.BufferedReader; import java.io.IOException; import java.lang.reflect.Field; import java.nio.file.Files; import java.nio.file.Path; import java.util.LinkedHashMap; import java.util.Map; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.internal.bind.ReflectiveTypeAdapterFactory; import com.google.gson.reflect.TypeToken; import com.github.tehfishey.spawnedit.pixelmon.SpawnSet; // Component of the FileManager class. Responsible for parsing and validating // loaded .json data files using Gson. Returns SpawnSet objects, which represent // whole data file contents. public class FileLoader { private Gson parser; public FileLoader() { GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapterFactory(new ValidatorAdapterFactory()); parser = builder.create(); } public SpawnSet parse(Path file) throws IOException, JsonParseException { try (BufferedReader reader = Files.newBufferedReader(file)) { try { SpawnSet spawnSet = parser.fromJson(reader, SpawnSet.class); return spawnSet; } catch (JsonParseException e) { System.out.println(e.getMessage() + "\nJsonParseException @ Filepath: " + file.toString()); throw e; } } catch (IOException e) { System.out.println(e.getMessage() + "\nIOException @ Filepath: " + file.toString()); throw e; } } private class ValidatorAdapterFactory implements TypeAdapterFactory { // Gson does not currently support error handling or catching of unknown properties for input validation purposes. // Suggested workaround taken from comments @ https://github.com/google/gson/issues/188. Credit to <NAME> (ikus060) @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { // If the type adapter is a reflective type adapter, we want to modify the implementation using reflection. The // trick is to replace the Map object used to lookup the property name. Instead of returning null if the // property is not found, we throw a Json exception to terminate the deserialization. TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type); // Check if the type adapter is a reflective, cause this solution only work for reflection. if (delegate instanceof ReflectiveTypeAdapterFactory.Adapter) { try { // Get reference to the existing boundFields. Field f = delegate.getClass().getDeclaredField("boundFields"); f.setAccessible(true); Map boundFields = (Map) f.get(delegate); // Then replace it with our implementation throwing exception if the value is null. boundFields = new LinkedHashMap(boundFields) { @Override public Object get(Object key) { Object value = super.get(key); if (value == null) { throw new JsonParseException("invalid property name: " + key); } return value; } }; // Finally, push our custom map back using reflection. f.set(delegate, boundFields); } catch (Exception e) { // Should never happen if the implementation doesn't change. throw new IllegalStateException(e); } } return delegate; } } }
mr-july/generator-nuxeo
test/sync_lib_test.js
<gh_stars>1-10 const chai = require('chai'); const dirtyChai = require('dirty-chai'); chai.use(dirtyChai); const expect = chai.expect; const PathResolver = require('../generators/synchronize/synchronize/path_resolver'); const containsChild = require('../generators/synchronize/synchronize/path_child_finder').containsChild; const tmp = require('tmp'); const path = require('path'); const fs = require('fs-extra'); describe('Synchronization Lib Modules', function () { before(function () { this.realCwd = process.cwd(); }); afterEach(function () { process.chdir(this.realCwd); }); describe('PathResolved class', function () { beforeEach(function () { this.cwdObj = tmp.dirSync(); this.cwd = this.cwdObj.name; process.chdir(this.cwd); }); afterEach(function () { fs.emptyDirSync(this.cwd); this.cwdObj.removeCallback(); }); describe('src getter', function () { it('returns a default value', function () { expect(PathResolver.src().describe).to.be.eq('Source Folder'); expect(PathResolver.src().default).to.contains('/watcher/src'); expect(PathResolver.computeSource()).to.be.eq('/tmp/watcher/src'); }); describe('can find a Studio gitlab clone', function () { beforeEach(function () { this.baseProject = path.join(process.cwd(), 'project'); fs.mkdirpSync(this.baseProject); fs.writeFileSync(path.join(this.baseProject, 'application.xml'), 'dummy-content'); this.warFolder = path.join(this.baseProject, 'studio', 'resources', 'nuxeo.war'); }); it('ensures that a application.xml and studio folder are present', function () { const cwd = path.join(this.warFolder, 'ui', 'document'); fs.mkdirpSync(cwd); process.chdir(cwd); expect(PathResolver.computeSource()).to.eq(this.warFolder); }); it('ensures that a studio folder exists at the same level, containing a nuxeo.war', function () { // with a missing studio folder expect(PathResolver.computeSource()).to.eq('/tmp/watcher/src'); // After creating a studio folder AND a nuxeo.war fs.mkdirpSync(this.warFolder); process.chdir(this.warFolder); expect(PathResolver.computeSource()).to.eq(this.warFolder); // After unlinking nuxeo.war folder process.chdir(path.dirname(this.warFolder)); fs.rmdirSync(this.warFolder); expect(PathResolver.computeSource()).to.eq('/tmp/watcher/src'); }); }); }); describe('dest getter', function () { it('returns a default value', function () { expect(PathResolver.dest().describe).to.be.eq('Destination Folder'); expect(PathResolver.dest().default).to.contains('/watcher/dest'); expect(PathResolver.computeDestination()).to.be.eq('/tmp/watcher/dest'); }); describe('can find ".yo-rc.json"', function () { beforeEach(function () { this.initYoRc = (obj) => { fs.writeJSONSync(path.join(this.cwd, '.yo-rc.json'), { foo: { bar: 0 }, 'generator-nuxeo': obj }); }; }); it('and read configured distribution path', function () { expect(PathResolver.computeDestination()).to.be.eq('/tmp/watcher/dest'); this.initYoRc({ 'distribution:path': '/foo/bar/nxserver' }); expect(PathResolver.computeDestination()).to.match(/^\/foo\/bar\/nxserver\/.+/); }); it('even from a deeper child', function () { const darkness = path.join(this.cwd, 'deep', 'deep', 'sooo', 'deep'); fs.mkdirpSync(darkness); process.chdir(darkness); expect(PathResolver.computeDestination()).to.be.eq('/tmp/watcher/dest'); this.initYoRc({ 'distribution:path': '/foo/bar/distribution' }); expect(PathResolver.computeDestination()).to.eq('/foo/bar/distribution/nxserver/nuxeo.war'); }); it('and return default value if distribution not configured', function () { expect(PathResolver.computeDestination()).to.be.eq('/tmp/watcher/dest'); this.initYoRc({ 'wrong:key': '/foo/bar/nxserver' }); expect(PathResolver.computeDestination()).to.be.eq('/tmp/watcher/dest'); }); }); }); describe('findBaseDistribution', function () { it('returns undefined when nothing is found', function () { const target = path.join(this.cwd, 'foo', 'bar'); fs.mkdirpSync(target); expect(new PathResolver().findBaseDistributionPath(target)).to.undefined(); }); it('find the distribution root', function () { // Target Folder const target = path.join(this.cwd, 'foo', 'bar', 'dymme', 'nuxeo.war', 'ui'); fs.mkdirpSync(target); // Create nuxeo.conf file somewhere beside the target folder const binTarget = path.join(this.cwd, 'foo', 'bar', 'bin'); fs.mkdirpSync(binTarget); fs.writeJsonSync(path.join(binTarget, 'nuxeo.conf'), {}); expect(new PathResolver().findBaseDistributionPath(target)).to.eq(path.resolve(binTarget, '..')); }); }); }); describe('Child Path Finder class', function () { it('should detect child paths', function () { expect(containsChild(['/a/b'])).to.be.false(); expect(containsChild(['/a/b', '/c', '/b'])).to.be.false(); expect(containsChild(['/a/boby', '/a/bob', '/b'])).to.be.false(); expect(containsChild(['/a/b', '/a', '/b', '/c'])).to.be.true(); expect(containsChild(['/a/boby', '/a/../a/boby'])).to.be.true(); expect(containsChild([process.cwd(), '.'])).to.be.true(); expect(containsChild(['/var/folders/<KEY>', <KEY>', <KEY>'])).to.be.true(); }); }); });
mike-north/ember-asset-size-report
fixtures/ember-new-prod/concat-stats-for/2-ember.js/@glimmer/runtime.js
<gh_stars>1-10 define("@glimmer/runtime", ["exports", "ember-babel", "@glimmer/util", "@glimmer/reference", "@glimmer/vm", "@glimmer/low-level"], function (_exports, _emberBabel, _util, _reference2, _vm2, _lowLevel) { "use strict"; Object.defineProperty(_exports, "__esModule", { value: true }); _exports.renderMain = renderMain; _exports.renderComponent = renderComponent; _exports.setDebuggerCallback = setDebuggerCallback; _exports.resetDebuggerCallback = resetDebuggerCallback; _exports.getDynamicVar = getDynamicVar; _exports.isCurriedComponentDefinition = isCurriedComponentDefinition; _exports.curry = curry; _exports.isWhitespace = isWhitespace; _exports.normalizeProperty = normalizeProperty; _exports.clientBuilder = clientBuilder; _exports.rehydrationBuilder = rehydrationBuilder; _exports.isSerializationFirstNode = isSerializationFirstNode; _exports.capabilityFlagsFrom = capabilityFlagsFrom; _exports.hasCapability = hasCapability; _exports.Cursor = _exports.ConcreteBounds = _exports.SERIALIZATION_FIRST_NODE_STRING = _exports.RehydrateBuilder = _exports.NewElementBuilder = _exports.DOMTreeConstruction = _exports.IDOMChanges = _exports.SVG_NAMESPACE = _exports.DOMChanges = _exports.CurriedComponentDefinition = _exports.MINIMAL_CAPABILITIES = _exports.DEFAULT_CAPABILITIES = _exports.DefaultEnvironment = _exports.Environment = _exports.Scope = _exports.EMPTY_ARGS = _exports.DynamicAttribute = _exports.SimpleDynamicAttribute = _exports.RenderResult = _exports.UpdatingVM = _exports.LowLevelVM = _exports.ConditionalReference = _exports.PrimitiveReference = _exports.UNDEFINED_REFERENCE = _exports.NULL_REFERENCE = void 0; // these import bindings will be stripped from build var AppendOpcodes = /*#__PURE__*/ function () { function AppendOpcodes() { this.evaluateOpcode = (0, _util.fillNulls)(98 /* Size */ ).slice(); } var _proto = AppendOpcodes.prototype; _proto.add = function add(name, evaluate, kind) { if (kind === void 0) { kind = 'syscall'; } this.evaluateOpcode[name] = { syscall: kind === 'syscall', evaluate: evaluate }; }; _proto.debugBefore = function debugBefore(vm, opcode, type) { var sp; var state; return { sp: sp, state: state }; }; _proto.debugAfter = function debugAfter(vm, opcode, type, pre) { var expectedChange; var sp = pre.sp, state = pre.state; var metadata = null; if (metadata !== null) { if (typeof metadata.stackChange === 'number') { expectedChange = metadata.stackChange; } else { expectedChange = metadata.stackChange({ opcode: opcode, constants: vm.constants, state: state }); if (isNaN(expectedChange)) throw (0, _util.unreachable)(); } } }; _proto.evaluate = function evaluate(vm, opcode, type) { var operation = this.evaluateOpcode[type]; if (operation.syscall) { operation.evaluate(vm, opcode); } else { operation.evaluate(vm.inner, opcode); } }; return AppendOpcodes; }(); var APPEND_OPCODES = new AppendOpcodes(); var AbstractOpcode = function AbstractOpcode() { (0, _util.initializeGuid)(this); }; var UpdatingOpcode = /*#__PURE__*/ function (_AbstractOpcode) { (0, _emberBabel.inheritsLoose)(UpdatingOpcode, _AbstractOpcode); function UpdatingOpcode() { var _this; _this = _AbstractOpcode.apply(this, arguments) || this; _this.next = null; _this.prev = null; return _this; } return UpdatingOpcode; }(AbstractOpcode); var PrimitiveReference = /*#__PURE__*/ function (_ConstReference) { (0, _emberBabel.inheritsLoose)(PrimitiveReference, _ConstReference); function PrimitiveReference(value$$1) { return _ConstReference.call(this, value$$1) || this; } PrimitiveReference.create = function create(value$$1) { if (value$$1 === undefined) { return UNDEFINED_REFERENCE; } else if (value$$1 === null) { return NULL_REFERENCE; } else if (value$$1 === true) { return TRUE_REFERENCE; } else if (value$$1 === false) { return FALSE_REFERENCE; } else if (typeof value$$1 === 'number') { return new ValueReference(value$$1); } else { return new StringReference(value$$1); } }; var _proto2 = PrimitiveReference.prototype; _proto2.get = function get(_key) { return UNDEFINED_REFERENCE; }; return PrimitiveReference; }(_reference2.ConstReference); _exports.PrimitiveReference = PrimitiveReference; var StringReference = /*#__PURE__*/ function (_PrimitiveReference) { (0, _emberBabel.inheritsLoose)(StringReference, _PrimitiveReference); function StringReference() { var _this2; _this2 = _PrimitiveReference.apply(this, arguments) || this; _this2.lengthReference = null; return _this2; } var _proto3 = StringReference.prototype; _proto3.get = function get(key) { if (key === 'length') { var lengthReference = this.lengthReference; if (lengthReference === null) { lengthReference = this.lengthReference = new ValueReference(this.inner.length); } return lengthReference; } else { return _PrimitiveReference.prototype.get.call(this, key); } }; return StringReference; }(PrimitiveReference); var ValueReference = /*#__PURE__*/ function (_PrimitiveReference2) { (0, _emberBabel.inheritsLoose)(ValueReference, _PrimitiveReference2); function ValueReference(value$$1) { return _PrimitiveReference2.call(this, value$$1) || this; } return ValueReference; }(PrimitiveReference); var UNDEFINED_REFERENCE = new ValueReference(undefined); _exports.UNDEFINED_REFERENCE = UNDEFINED_REFERENCE; var NULL_REFERENCE = new ValueReference(null); _exports.NULL_REFERENCE = NULL_REFERENCE; var TRUE_REFERENCE = new ValueReference(true); var FALSE_REFERENCE = new ValueReference(false); var ConditionalReference = /*#__PURE__*/ function () { function ConditionalReference(inner) { this.inner = inner; this.tag = inner.tag; } var _proto4 = ConditionalReference.prototype; _proto4.value = function value() { return this.toBool(this.inner.value()); }; _proto4.toBool = function toBool(value$$1) { return !!value$$1; }; return ConditionalReference; }(); _exports.ConditionalReference = ConditionalReference; var ConcatReference = /*#__PURE__*/ function (_CachedReference) { (0, _emberBabel.inheritsLoose)(ConcatReference, _CachedReference); function ConcatReference(parts) { var _this3; _this3 = _CachedReference.call(this) || this; _this3.parts = parts; _this3.tag = (0, _reference2.combineTagged)(parts); return _this3; } var _proto5 = ConcatReference.prototype; _proto5.compute = function compute() { var parts = new Array(); for (var i = 0; i < this.parts.length; i++) { var value$$1 = this.parts[i].value(); if (value$$1 !== null && value$$1 !== undefined) { parts[i] = castToString(value$$1); } } if (parts.length > 0) { return parts.join(''); } return null; }; return ConcatReference; }(_reference2.CachedReference); function castToString(value$$1) { if (typeof value$$1.toString !== 'function') { return ''; } return String(value$$1); } APPEND_OPCODES.add(1 /* Helper */ , function (vm, _ref) { var handle = _ref.op1; var stack = vm.stack; var helper = vm.constants.resolveHandle(handle); var args = stack.pop(); var value$$1 = helper(vm, args); vm.loadValue(_vm2.Register.v0, value$$1); }); APPEND_OPCODES.add(6 /* GetVariable */ , function (vm, _ref2) { var symbol = _ref2.op1; var expr = vm.referenceForSymbol(symbol); vm.stack.push(expr); }); APPEND_OPCODES.add(4 /* SetVariable */ , function (vm, _ref3) { var symbol = _ref3.op1; var expr = vm.stack.pop(); vm.scope().bindSymbol(symbol, expr); }); APPEND_OPCODES.add(5 /* SetBlock */ , function (vm, _ref4) { var symbol = _ref4.op1; var handle = vm.stack.pop(); var scope = vm.stack.pop(); // FIXME(mmun): shouldn't need to cast this var table = vm.stack.pop(); var block = table ? [handle, scope, table] : null; vm.scope().bindBlock(symbol, block); }); APPEND_OPCODES.add(96 /* ResolveMaybeLocal */ , function (vm, _ref5) { var _name = _ref5.op1; var name = vm.constants.getString(_name); var locals = vm.scope().getPartialMap(); var ref = locals[name]; if (ref === undefined) { ref = vm.getSelf().get(name); } vm.stack.push(ref); }); APPEND_OPCODES.add(20 /* RootScope */ , function (vm, _ref6) { var symbols = _ref6.op1, bindCallerScope = _ref6.op2; vm.pushRootScope(symbols, !!bindCallerScope); }); APPEND_OPCODES.add(7 /* GetProperty */ , function (vm, _ref7) { var _key = _ref7.op1; var key = vm.constants.getString(_key); var expr = vm.stack.pop(); vm.stack.push(expr.get(key)); }); APPEND_OPCODES.add(8 /* GetBlock */ , function (vm, _ref8) { var _block = _ref8.op1; var stack = vm.stack; var block = vm.scope().getBlock(_block); if (block) { stack.push(block[2]); stack.push(block[1]); stack.push(block[0]); } else { stack.push(null); stack.push(null); stack.push(null); } }); APPEND_OPCODES.add(9 /* HasBlock */ , function (vm, _ref9) { var _block = _ref9.op1; var hasBlock = !!vm.scope().getBlock(_block); vm.stack.push(hasBlock ? TRUE_REFERENCE : FALSE_REFERENCE); }); APPEND_OPCODES.add(10 /* HasBlockParams */ , function (vm) { // FIXME(mmun): should only need to push the symbol table var block = vm.stack.pop(); var scope = vm.stack.pop(); var table = vm.stack.pop(); var hasBlockParams = table && table.parameters.length; vm.stack.push(hasBlockParams ? TRUE_REFERENCE : FALSE_REFERENCE); }); APPEND_OPCODES.add(11 /* Concat */ , function (vm, _ref10) { var count = _ref10.op1; var out = new Array(count); for (var i = count; i > 0; i--) { var offset = i - 1; out[offset] = vm.stack.pop(); } vm.stack.push(new ConcatReference(out)); }); var CURRIED_COMPONENT_DEFINITION_BRAND = 'CURRIED COMPONENT DEFINITION [id=6f00feb9-a0ef-4547-99ea-ac328f80acea]'; function isCurriedComponentDefinition(definition) { return !!(definition && definition[CURRIED_COMPONENT_DEFINITION_BRAND]); } function isComponentDefinition(definition) { return definition && definition[CURRIED_COMPONENT_DEFINITION_BRAND]; } var CurriedComponentDefinition = /*#__PURE__*/ function () { /** @internal */ function CurriedComponentDefinition(inner, args) { this.inner = inner; this.args = args; this[CURRIED_COMPONENT_DEFINITION_BRAND] = true; } var _proto6 = CurriedComponentDefinition.prototype; _proto6.unwrap = function unwrap(args) { args.realloc(this.offset); var definition = this; while (true) { var _definition = definition, curriedArgs = _definition.args, inner = _definition.inner; if (curriedArgs) { args.positional.prepend(curriedArgs.positional); args.named.merge(curriedArgs.named); } if (!isCurriedComponentDefinition(inner)) { return inner; } definition = inner; } } /** @internal */ ; (0, _emberBabel.createClass)(CurriedComponentDefinition, [{ key: "offset", get: function get() { var inner = this.inner, args = this.args; var length = args ? args.positional.length : 0; return isCurriedComponentDefinition(inner) ? length + inner.offset : length; } }]); return CurriedComponentDefinition; }(); _exports.CurriedComponentDefinition = CurriedComponentDefinition; function curry(spec, args) { if (args === void 0) { args = null; } return new CurriedComponentDefinition(spec, args); } function normalizeStringValue(value$$1) { if (isEmpty(value$$1)) { return ''; } return String(value$$1); } function shouldCoerce(value$$1) { return isString(value$$1) || isEmpty(value$$1) || typeof value$$1 === 'boolean' || typeof value$$1 === 'number'; } function isEmpty(value$$1) { return value$$1 === null || value$$1 === undefined || typeof value$$1.toString !== 'function'; } function isSafeString(value$$1) { return typeof value$$1 === 'object' && value$$1 !== null && typeof value$$1.toHTML === 'function'; } function isNode(value$$1) { return typeof value$$1 === 'object' && value$$1 !== null && typeof value$$1.nodeType === 'number'; } function isFragment(value$$1) { return isNode(value$$1) && value$$1.nodeType === 11; } function isString(value$$1) { return typeof value$$1 === 'string'; } var DynamicTextContent = /*#__PURE__*/ function (_UpdatingOpcode) { (0, _emberBabel.inheritsLoose)(DynamicTextContent, _UpdatingOpcode); function DynamicTextContent(node, reference, lastValue) { var _this4; _this4 = _UpdatingOpcode.call(this) || this; _this4.node = node; _this4.reference = reference; _this4.lastValue = lastValue; _this4.type = 'dynamic-text'; _this4.tag = reference.tag; _this4.lastRevision = (0, _reference2.value)(_this4.tag); return _this4; } var _proto7 = DynamicTextContent.prototype; _proto7.evaluate = function evaluate() { var reference = this.reference, tag = this.tag; if (!(0, _reference2.validate)(tag, this.lastRevision)) { this.lastRevision = (0, _reference2.value)(tag); this.update(reference.value()); } }; _proto7.update = function update(value$$1) { var lastValue = this.lastValue; if (value$$1 === lastValue) return; var normalized; if (isEmpty(value$$1)) { normalized = ''; } else if (isString(value$$1)) { normalized = value$$1; } else { normalized = String(value$$1); } if (normalized !== lastValue) { var textNode = this.node; textNode.nodeValue = this.lastValue = normalized; } }; return DynamicTextContent; }(UpdatingOpcode); var IsCurriedComponentDefinitionReference = /*#__PURE__*/ function (_ConditionalReference) { (0, _emberBabel.inheritsLoose)(IsCurriedComponentDefinitionReference, _ConditionalReference); function IsCurriedComponentDefinitionReference() { return _ConditionalReference.apply(this, arguments) || this; } IsCurriedComponentDefinitionReference.create = function create(inner) { return new IsCurriedComponentDefinitionReference(inner); }; var _proto8 = IsCurriedComponentDefinitionReference.prototype; _proto8.toBool = function toBool(value$$1) { return isCurriedComponentDefinition(value$$1); }; return IsCurriedComponentDefinitionReference; }(ConditionalReference); var ContentTypeReference = /*#__PURE__*/ function () { function ContentTypeReference(inner) { this.inner = inner; this.tag = inner.tag; } var _proto9 = ContentTypeReference.prototype; _proto9.value = function value() { var value$$1 = this.inner.value(); if (shouldCoerce(value$$1)) { return 1 /* String */ ; } else if (isComponentDefinition(value$$1)) { return 0 /* Component */ ; } else if (isSafeString(value$$1)) { return 3 /* SafeString */ ; } else if (isFragment(value$$1)) { return 4 /* Fragment */ ; } else if (isNode(value$$1)) { return 5 /* Node */ ; } else { return 1 /* String */ ; } }; return ContentTypeReference; }(); APPEND_OPCODES.add(28 /* AppendHTML */ , function (vm) { var reference = vm.stack.pop(); var rawValue = reference.value(); var value$$1 = isEmpty(rawValue) ? '' : String(rawValue); vm.elements().appendDynamicHTML(value$$1); }); APPEND_OPCODES.add(29 /* AppendSafeHTML */ , function (vm) { var reference = vm.stack.pop(); var rawValue = reference.value().toHTML(); var value$$1 = isEmpty(rawValue) ? '' : rawValue; vm.elements().appendDynamicHTML(value$$1); }); APPEND_OPCODES.add(32 /* AppendText */ , function (vm) { var reference = vm.stack.pop(); var rawValue = reference.value(); var value$$1 = isEmpty(rawValue) ? '' : String(rawValue); var node = vm.elements().appendDynamicText(value$$1); if (!(0, _reference2.isConst)(reference)) { vm.updateWith(new DynamicTextContent(node, reference, value$$1)); } }); APPEND_OPCODES.add(30 /* AppendDocumentFragment */ , function (vm) { var reference = vm.stack.pop(); var value$$1 = reference.value(); vm.elements().appendDynamicFragment(value$$1); }); APPEND_OPCODES.add(31 /* AppendNode */ , function (vm) { var reference = vm.stack.pop(); var value$$1 = reference.value(); vm.elements().appendDynamicNode(value$$1); }); APPEND_OPCODES.add(22 /* ChildScope */ , function (vm) { return vm.pushChildScope(); }); APPEND_OPCODES.add(23 /* PopScope */ , function (vm) { return vm.popScope(); }); APPEND_OPCODES.add(44 /* PushDynamicScope */ , function (vm) { return vm.pushDynamicScope(); }); APPEND_OPCODES.add(45 /* PopDynamicScope */ , function (vm) { return vm.popDynamicScope(); }); APPEND_OPCODES.add(12 /* Constant */ , function (vm, _ref11) { var other = _ref11.op1; vm.stack.push(vm.constants.getOther(other)); }); APPEND_OPCODES.add(13 /* Primitive */ , function (vm, _ref12) { var primitive = _ref12.op1; var stack = vm.stack; var flag = primitive & 7; // 111 var value$$1 = primitive >> 3; switch (flag) { case 0 /* NUMBER */ : stack.push(value$$1); break; case 1 /* FLOAT */ : stack.push(vm.constants.getNumber(value$$1)); break; case 2 /* STRING */ : stack.push(vm.constants.getString(value$$1)); break; case 3 /* BOOLEAN_OR_VOID */ : stack.pushEncodedImmediate(primitive); break; case 4 /* NEGATIVE */ : stack.push(vm.constants.getNumber(value$$1)); break; case 5 /* BIG_NUM */ : stack.push(vm.constants.getNumber(value$$1)); break; } }); APPEND_OPCODES.add(14 /* PrimitiveReference */ , function (vm) { var stack = vm.stack; stack.push(PrimitiveReference.create(stack.pop())); }); APPEND_OPCODES.add(15 /* ReifyU32 */ , function (vm) { var stack = vm.stack; stack.push(stack.peek().value()); }); APPEND_OPCODES.add(16 /* Dup */ , function (vm, _ref13) { var register = _ref13.op1, offset = _ref13.op2; var position = vm.fetchValue(register) - offset; vm.stack.dup(position); }); APPEND_OPCODES.add(17 /* Pop */ , function (vm, _ref14) { var count = _ref14.op1; vm.stack.pop(count); }); APPEND_OPCODES.add(18 /* Load */ , function (vm, _ref15) { var register = _ref15.op1; vm.load(register); }); APPEND_OPCODES.add(19 /* Fetch */ , function (vm, _ref16) { var register = _ref16.op1; vm.fetch(register); }); APPEND_OPCODES.add(43 /* BindDynamicScope */ , function (vm, _ref17) { var _names = _ref17.op1; var names = vm.constants.getArray(_names); vm.bindDynamicScope(names); }); APPEND_OPCODES.add(61 /* Enter */ , function (vm, _ref18) { var args = _ref18.op1; vm.enter(args); }); APPEND_OPCODES.add(62 /* Exit */ , function (vm) { vm.exit(); }); APPEND_OPCODES.add(48 /* PushSymbolTable */ , function (vm, _ref19) { var _table = _ref19.op1; var stack = vm.stack; stack.push(vm.constants.getSerializable(_table)); }); APPEND_OPCODES.add(47 /* PushBlockScope */ , function (vm) { var stack = vm.stack; stack.push(vm.scope()); }); APPEND_OPCODES.add(46 /* CompileBlock */ , function (vm) { var stack = vm.stack; var block = stack.pop(); if (block) { stack.push(block.compile()); } else { stack.pushNull(); } }); APPEND_OPCODES.add(51 /* InvokeYield */ , function (vm) { var stack = vm.stack; var handle = stack.pop(); var scope = stack.pop(); // FIXME(mmun): shouldn't need to cast this var table = stack.pop(); var args = stack.pop(); if (table === null) { // To balance the pop{Frame,Scope} vm.pushFrame(); vm.pushScope(scope); // Could be null but it doesnt matter as it is immediatelly popped. return; } var invokingScope = scope; // If necessary, create a child scope { var locals = table.parameters; var localsCount = locals.length; if (localsCount > 0) { invokingScope = invokingScope.child(); for (var i = 0; i < localsCount; i++) { invokingScope.bindSymbol(locals[i], args.at(i)); } } } vm.pushFrame(); vm.pushScope(invokingScope); vm.call(handle); }); APPEND_OPCODES.add(53 /* JumpIf */ , function (vm, _ref20) { var target = _ref20.op1; var reference = vm.stack.pop(); if ((0, _reference2.isConst)(reference)) { if (reference.value()) { vm.goto(target); } } else { var cache = new _reference2.ReferenceCache(reference); if (cache.peek()) { vm.goto(target); } vm.updateWith(new Assert(cache)); } }); APPEND_OPCODES.add(54 /* JumpUnless */ , function (vm, _ref21) { var target = _ref21.op1; var reference = vm.stack.pop(); if ((0, _reference2.isConst)(reference)) { if (!reference.value()) { vm.goto(target); } } else { var cache = new _reference2.ReferenceCache(reference); if (!cache.peek()) { vm.goto(target); } vm.updateWith(new Assert(cache)); } }); APPEND_OPCODES.add(55 /* JumpEq */ , function (vm, _ref22) { var target = _ref22.op1, comparison = _ref22.op2; var other = vm.stack.peek(); if (other === comparison) { vm.goto(target); } }); APPEND_OPCODES.add(56 /* AssertSame */ , function (vm) { var reference = vm.stack.peek(); if (!(0, _reference2.isConst)(reference)) { vm.updateWith(Assert.initialize(new _reference2.ReferenceCache(reference))); } }); APPEND_OPCODES.add(63 /* ToBoolean */ , function (vm) { var env = vm.env, stack = vm.stack; stack.push(env.toConditionalReference(stack.pop())); }); var Assert = /*#__PURE__*/ function (_UpdatingOpcode2) { (0, _emberBabel.inheritsLoose)(Assert, _UpdatingOpcode2); function Assert(cache) { var _this5; _this5 = _UpdatingOpcode2.call(this) || this; _this5.type = 'assert'; _this5.tag = cache.tag; _this5.cache = cache; return _this5; } Assert.initialize = function initialize(cache) { var assert = new Assert(cache); cache.peek(); return assert; }; var _proto10 = Assert.prototype; _proto10.evaluate = function evaluate(vm) { var cache = this.cache; if ((0, _reference2.isModified)(cache.revalidate())) { vm.throw(); } }; return Assert; }(UpdatingOpcode); var JumpIfNotModifiedOpcode = /*#__PURE__*/ function (_UpdatingOpcode3) { (0, _emberBabel.inheritsLoose)(JumpIfNotModifiedOpcode, _UpdatingOpcode3); function JumpIfNotModifiedOpcode(tag, target) { var _this6; _this6 = _UpdatingOpcode3.call(this) || this; _this6.target = target; _this6.type = 'jump-if-not-modified'; _this6.tag = tag; _this6.lastRevision = (0, _reference2.value)(tag); return _this6; } var _proto11 = JumpIfNotModifiedOpcode.prototype; _proto11.evaluate = function evaluate(vm) { var tag = this.tag, target = this.target, lastRevision = this.lastRevision; if (!vm.alwaysRevalidate && (0, _reference2.validate)(tag, lastRevision)) { vm.goto(target); } }; _proto11.didModify = function didModify() { this.lastRevision = (0, _reference2.value)(this.tag); }; return JumpIfNotModifiedOpcode; }(UpdatingOpcode); var DidModifyOpcode = /*#__PURE__*/ function (_UpdatingOpcode4) { (0, _emberBabel.inheritsLoose)(DidModifyOpcode, _UpdatingOpcode4); function DidModifyOpcode(target) { var _this7; _this7 = _UpdatingOpcode4.call(this) || this; _this7.target = target; _this7.type = 'did-modify'; _this7.tag = _reference2.CONSTANT_TAG; return _this7; } var _proto12 = DidModifyOpcode.prototype; _proto12.evaluate = function evaluate() { this.target.didModify(); }; return DidModifyOpcode; }(UpdatingOpcode); var LabelOpcode = /*#__PURE__*/ function () { function LabelOpcode(label) { this.tag = _reference2.CONSTANT_TAG; this.type = 'label'; this.label = null; this.prev = null; this.next = null; (0, _util.initializeGuid)(this); this.label = label; } var _proto13 = LabelOpcode.prototype; _proto13.evaluate = function evaluate() {}; _proto13.inspect = function inspect() { return this.label + " [" + this._guid + "]"; }; return LabelOpcode; }(); APPEND_OPCODES.add(26 /* Text */ , function (vm, _ref23) { var text = _ref23.op1; vm.elements().appendText(vm.constants.getString(text)); }); APPEND_OPCODES.add(27 /* Comment */ , function (vm, _ref24) { var text = _ref24.op1; vm.elements().appendComment(vm.constants.getString(text)); }); APPEND_OPCODES.add(33 /* OpenElement */ , function (vm, _ref25) { var tag = _ref25.op1; vm.elements().openElement(vm.constants.getString(tag)); }); APPEND_OPCODES.add(34 /* OpenDynamicElement */ , function (vm) { var tagName = vm.stack.pop().value(); vm.elements().openElement(tagName); }); APPEND_OPCODES.add(41 /* PushRemoteElement */ , function (vm) { var elementRef = vm.stack.pop(); var nextSiblingRef = vm.stack.pop(); var guidRef = vm.stack.pop(); var element; var nextSibling; var guid = guidRef.value(); if ((0, _reference2.isConst)(elementRef)) { element = elementRef.value(); } else { var cache = new _reference2.ReferenceCache(elementRef); element = cache.peek(); vm.updateWith(new Assert(cache)); } if ((0, _reference2.isConst)(nextSiblingRef)) { nextSibling = nextSiblingRef.value(); } else { var _cache = new _reference2.ReferenceCache(nextSiblingRef); nextSibling = _cache.peek(); vm.updateWith(new Assert(_cache)); } vm.elements().pushRemoteElement(element, guid, nextSibling); }); APPEND_OPCODES.add(42 /* PopRemoteElement */ , function (vm) { vm.elements().popRemoteElement(); }); APPEND_OPCODES.add(38 /* FlushElement */ , function (vm) { var operations = vm.fetchValue(_vm2.Register.t0); var modifiers = null; if (operations) { modifiers = operations.flush(vm); vm.loadValue(_vm2.Register.t0, null); } vm.elements().flushElement(modifiers); }); APPEND_OPCODES.add(39 /* CloseElement */ , function (vm) { var modifiers = vm.elements().closeElement(); if (modifiers) { modifiers.forEach(function (_ref26) { var manager = _ref26[0], modifier = _ref26[1]; vm.env.scheduleInstallModifier(modifier, manager); var destructor = manager.getDestructor(modifier); if (destructor) { vm.newDestroyable(destructor); } }); } }); APPEND_OPCODES.add(40 /* Modifier */ , function (vm, _ref27) { var handle = _ref27.op1; var _vm$constants$resolve = vm.constants.resolveHandle(handle), manager = _vm$constants$resolve.manager, state = _vm$constants$resolve.state; var stack = vm.stack; var args = stack.pop(); var _vm$elements = vm.elements(), constructing = _vm$elements.constructing, updateOperations = _vm$elements.updateOperations; var dynamicScope = vm.dynamicScope(); var modifier = manager.create(constructing, state, args, dynamicScope, updateOperations); var operations = vm.fetchValue(_vm2.Register.t0); operations.addModifier(manager, modifier); var tag = manager.getTag(modifier); if (!(0, _reference2.isConstTag)(tag)) { vm.updateWith(new UpdateModifierOpcode(tag, manager, modifier)); } }); var UpdateModifierOpcode = /*#__PURE__*/ function (_UpdatingOpcode5) { (0, _emberBabel.inheritsLoose)(UpdateModifierOpcode, _UpdatingOpcode5); function UpdateModifierOpcode(tag, manager, modifier) { var _this8; _this8 = _UpdatingOpcode5.call(this) || this; _this8.tag = tag; _this8.manager = manager; _this8.modifier = modifier; _this8.type = 'update-modifier'; _this8.lastUpdated = (0, _reference2.value)(tag); return _this8; } var _proto14 = UpdateModifierOpcode.prototype; _proto14.evaluate = function evaluate(vm) { var manager = this.manager, modifier = this.modifier, tag = this.tag, lastUpdated = this.lastUpdated; if (!(0, _reference2.validate)(tag, lastUpdated)) { vm.env.scheduleUpdateModifier(modifier, manager); this.lastUpdated = (0, _reference2.value)(tag); } }; return UpdateModifierOpcode; }(UpdatingOpcode); APPEND_OPCODES.add(35 /* StaticAttr */ , function (vm, _ref28) { var _name = _ref28.op1, _value = _ref28.op2, _namespace = _ref28.op3; var name = vm.constants.getString(_name); var value$$1 = vm.constants.getString(_value); var namespace = _namespace ? vm.constants.getString(_namespace) : null; vm.elements().setStaticAttribute(name, value$$1, namespace); }); APPEND_OPCODES.add(36 /* DynamicAttr */ , function (vm, _ref29) { var _name = _ref29.op1, trusting = _ref29.op2, _namespace = _ref29.op3; var name = vm.constants.getString(_name); var reference = vm.stack.pop(); var value$$1 = reference.value(); var namespace = _namespace ? vm.constants.getString(_namespace) : null; var attribute = vm.elements().setDynamicAttribute(name, value$$1, !!trusting, namespace); if (!(0, _reference2.isConst)(reference)) { vm.updateWith(new UpdateDynamicAttributeOpcode(reference, attribute)); } }); var UpdateDynamicAttributeOpcode = /*#__PURE__*/ function (_UpdatingOpcode6) { (0, _emberBabel.inheritsLoose)(UpdateDynamicAttributeOpcode, _UpdatingOpcode6); function UpdateDynamicAttributeOpcode(reference, attribute) { var _this9; _this9 = _UpdatingOpcode6.call(this) || this; _this9.reference = reference; _this9.attribute = attribute; _this9.type = 'patch-element'; var tag = reference.tag; _this9.tag = tag; _this9.lastRevision = (0, _reference2.value)(tag); return _this9; } var _proto15 = UpdateDynamicAttributeOpcode.prototype; _proto15.evaluate = function evaluate(vm) { var attribute = this.attribute, reference = this.reference, tag = this.tag; if (!(0, _reference2.validate)(tag, this.lastRevision)) { this.lastRevision = (0, _reference2.value)(tag); attribute.update(reference.value(), vm.env); } }; return UpdateDynamicAttributeOpcode; }(UpdatingOpcode); function resolveComponent(resolver, name, meta) { var definition = resolver.lookupComponentDefinition(name, meta); return definition; } var CurryComponentReference = /*#__PURE__*/ function () { function CurryComponentReference(inner, resolver, meta, args) { this.inner = inner; this.resolver = resolver; this.meta = meta; this.args = args; this.tag = inner.tag; this.lastValue = null; this.lastDefinition = null; } var _proto16 = CurryComponentReference.prototype; _proto16.value = function value() { var inner = this.inner, lastValue = this.lastValue; var value$$1 = inner.value(); if (value$$1 === lastValue) { return this.lastDefinition; } var definition = null; if (isCurriedComponentDefinition(value$$1)) { definition = value$$1; } else if (typeof value$$1 === 'string' && value$$1) { var resolver = this.resolver, meta = this.meta; definition = resolveComponent(resolver, value$$1, meta); } definition = this.curry(definition); this.lastValue = value$$1; this.lastDefinition = definition; return definition; }; _proto16.get = function get() { return UNDEFINED_REFERENCE; }; _proto16.curry = function curry(definition) { var args = this.args; if (!args && isCurriedComponentDefinition(definition)) { return definition; } else if (!definition) { return null; } else { return new CurriedComponentDefinition(definition, args); } }; return CurryComponentReference; }(); var ClassListReference = /*#__PURE__*/ function () { function ClassListReference(list) { this.list = list; this.tag = (0, _reference2.combineTagged)(list); this.list = list; } var _proto17 = ClassListReference.prototype; _proto17.value = function value() { var ret = []; var list = this.list; for (var i = 0; i < list.length; i++) { var value$$1 = normalizeStringValue(list[i].value()); if (value$$1) ret.push(value$$1); } return ret.length === 0 ? null : ret.join(' '); }; return ClassListReference; }(); /** * Converts a ComponentCapabilities object into a 32-bit integer representation. */ function capabilityFlagsFrom(capabilities) { return 0 | (capabilities.dynamicLayout ? 1 /* DynamicLayout */ : 0) | (capabilities.dynamicTag ? 2 /* DynamicTag */ : 0) | (capabilities.prepareArgs ? 4 /* PrepareArgs */ : 0) | (capabilities.createArgs ? 8 /* CreateArgs */ : 0) | (capabilities.attributeHook ? 16 /* AttributeHook */ : 0) | (capabilities.elementHook ? 32 /* ElementHook */ : 0) | (capabilities.dynamicScope ? 64 /* DynamicScope */ : 0) | (capabilities.createCaller ? 128 /* CreateCaller */ : 0) | (capabilities.updateHook ? 256 /* UpdateHook */ : 0) | (capabilities.createInstance ? 512 /* CreateInstance */ : 0); } function hasCapability(capabilities, capability) { return !!(capabilities & capability); } APPEND_OPCODES.add(69 /* IsComponent */ , function (vm) { var stack = vm.stack; var ref = stack.pop(); stack.push(IsCurriedComponentDefinitionReference.create(ref)); }); APPEND_OPCODES.add(70 /* ContentType */ , function (vm) { var stack = vm.stack; var ref = stack.peek(); stack.push(new ContentTypeReference(ref)); }); APPEND_OPCODES.add(71 /* CurryComponent */ , function (vm, _ref30) { var _meta = _ref30.op1; var stack = vm.stack; var definition = stack.pop(); var capturedArgs = stack.pop(); var meta = vm.constants.getSerializable(_meta); var resolver = vm.constants.resolver; vm.loadValue(_vm2.Register.v0, new CurryComponentReference(definition, resolver, meta, capturedArgs)); // expectStackChange(vm.stack, -args.length - 1, 'CurryComponent'); }); APPEND_OPCODES.add(72 /* PushComponentDefinition */ , function (vm, _ref31) { var handle = _ref31.op1; var definition = vm.constants.resolveHandle(handle); var manager = definition.manager; var capabilities = capabilityFlagsFrom(manager.getCapabilities(definition.state)); var instance = { definition: definition, manager: manager, capabilities: capabilities, state: null, handle: null, table: null, lookup: null }; vm.stack.push(instance); }); APPEND_OPCODES.add(75 /* ResolveDynamicComponent */ , function (vm, _ref32) { var _meta = _ref32.op1; var stack = vm.stack; var component = stack.pop().value(); var meta = vm.constants.getSerializable(_meta); vm.loadValue(_vm2.Register.t1, null); // Clear the temp register var definition; if (typeof component === 'string') { var resolver = vm.constants.resolver; var resolvedDefinition = resolveComponent(resolver, component, meta); definition = resolvedDefinition; } else if (isCurriedComponentDefinition(component)) { definition = component; } else { throw (0, _util.unreachable)(); } stack.push(definition); }); APPEND_OPCODES.add(73 /* PushDynamicComponentInstance */ , function (vm) { var stack = vm.stack; var definition = stack.pop(); var capabilities, manager; if (isCurriedComponentDefinition(definition)) { manager = capabilities = null; } else { manager = definition.manager; capabilities = capabilityFlagsFrom(manager.getCapabilities(definition.state)); } stack.push({ definition: definition, capabilities: capabilities, manager: manager, state: null, handle: null, table: null }); }); APPEND_OPCODES.add(74 /* PushCurriedComponent */ , function (vm, _ref33) { (0, _emberBabel.objectDestructuringEmpty)(_ref33); var stack = vm.stack; var component = stack.pop().value(); var definition; if (isCurriedComponentDefinition(component)) { definition = component; } else { throw (0, _util.unreachable)(); } stack.push(definition); }); APPEND_OPCODES.add(76 /* PushArgs */ , function (vm, _ref34) { var _names = _ref34.op1, flags = _ref34.op2; var stack = vm.stack; var names = vm.constants.getStringArray(_names); var positionalCount = flags >> 4; var synthetic = flags & 8; var blockNames = []; if (flags & 4) blockNames.push('main'); if (flags & 2) blockNames.push('else'); if (flags & 1) blockNames.push('attrs'); vm.args.setup(stack, names, blockNames, positionalCount, !!synthetic); stack.push(vm.args); }); APPEND_OPCODES.add(77 /* PushEmptyArgs */ , function (vm) { var stack = vm.stack; stack.push(vm.args.empty(stack)); }); APPEND_OPCODES.add(80 /* CaptureArgs */ , function (vm) { var stack = vm.stack; var args = stack.pop(); var capturedArgs = args.capture(); stack.push(capturedArgs); }); APPEND_OPCODES.add(79 /* PrepareArgs */ , function (vm, _ref35) { var _state = _ref35.op1; var stack = vm.stack; var instance = vm.fetchValue(_state); var args = stack.pop(); var definition = instance.definition; if (isCurriedComponentDefinition(definition)) { definition = resolveCurriedComponentDefinition(instance, definition, args); } var _definition2 = definition, manager = _definition2.manager, state = _definition2.state; var capabilities = instance.capabilities; if (hasCapability(capabilities, 4 /* PrepareArgs */ ) !== true) { stack.push(args); return; } var blocks = args.blocks.values; var blockNames = args.blocks.names; var preparedArgs = manager.prepareArgs(state, args); if (preparedArgs) { args.clear(); for (var i = 0; i < blocks.length; i++) { stack.push(blocks[i]); } var positional = preparedArgs.positional, named = preparedArgs.named; var positionalCount = positional.length; for (var _i = 0; _i < positionalCount; _i++) { stack.push(positional[_i]); } var names = Object.keys(named); for (var _i2 = 0; _i2 < names.length; _i2++) { stack.push(named[names[_i2]]); } args.setup(stack, names, blockNames, positionalCount, true); } stack.push(args); }); function resolveCurriedComponentDefinition(instance, definition, args) { var unwrappedDefinition = instance.definition = definition.unwrap(args); var manager = unwrappedDefinition.manager, state = unwrappedDefinition.state; instance.manager = manager; instance.capabilities = capabilityFlagsFrom(manager.getCapabilities(state)); return unwrappedDefinition; } APPEND_OPCODES.add(81 /* CreateComponent */ , function (vm, _ref36) { var flags = _ref36.op1, _state = _ref36.op2; var instance = vm.fetchValue(_state); var definition = instance.definition, manager = instance.manager; var capabilities = instance.capabilities = capabilityFlagsFrom(manager.getCapabilities(definition.state)); var dynamicScope = null; if (hasCapability(capabilities, 64 /* DynamicScope */ )) { dynamicScope = vm.dynamicScope(); } var hasDefaultBlock = flags & 1; var args = null; if (hasCapability(capabilities, 8 /* CreateArgs */ )) { args = vm.stack.peek(); } var self = null; if (hasCapability(capabilities, 128 /* CreateCaller */ )) { self = vm.getSelf(); } var state = manager.create(vm.env, definition.state, args, dynamicScope, self, !!hasDefaultBlock); // We want to reuse the `state` POJO here, because we know that the opcodes // only transition at exactly one place. instance.state = state; var tag = manager.getTag(state); if (hasCapability(capabilities, 256 /* UpdateHook */ ) && !(0, _reference2.isConstTag)(tag)) { vm.updateWith(new UpdateComponentOpcode(tag, state, manager, dynamicScope)); } }); APPEND_OPCODES.add(82 /* RegisterComponentDestructor */ , function (vm, _ref37) { var _state = _ref37.op1; var _vm$fetchValue = vm.fetchValue(_state), manager = _vm$fetchValue.manager, state = _vm$fetchValue.state; var destructor = manager.getDestructor(state); if (destructor) vm.newDestroyable(destructor); }); APPEND_OPCODES.add(91 /* BeginComponentTransaction */ , function (vm) { vm.beginCacheGroup(); vm.elements().pushSimpleBlock(); }); APPEND_OPCODES.add(83 /* PutComponentOperations */ , function (vm) { vm.loadValue(_vm2.Register.t0, new ComponentElementOperations()); }); APPEND_OPCODES.add(37 /* ComponentAttr */ , function (vm, _ref38) { var _name = _ref38.op1, trusting = _ref38.op2, _namespace = _ref38.op3; var name = vm.constants.getString(_name); var reference = vm.stack.pop(); var namespace = _namespace ? vm.constants.getString(_namespace) : null; vm.fetchValue(_vm2.Register.t0).setAttribute(name, reference, !!trusting, namespace); }); var ComponentElementOperations = /*#__PURE__*/ function () { function ComponentElementOperations() { this.attributes = (0, _util.dict)(); this.classes = []; this.modifiers = []; } var _proto18 = ComponentElementOperations.prototype; _proto18.setAttribute = function setAttribute(name, value$$1, trusting, namespace) { var deferred = { value: value$$1, namespace: namespace, trusting: trusting }; if (name === 'class') { this.classes.push(value$$1); } this.attributes[name] = deferred; }; _proto18.addModifier = function addModifier(manager, modifier) { this.modifiers.push([manager, modifier]); }; _proto18.flush = function flush(vm) { for (var name in this.attributes) { var attr = this.attributes[name]; var reference = attr.value, namespace = attr.namespace, trusting = attr.trusting; if (name === 'class') { reference = new ClassListReference(this.classes); } if (name === 'type') { continue; } var attribute = vm.elements().setDynamicAttribute(name, reference.value(), trusting, namespace); if (!(0, _reference2.isConst)(reference)) { vm.updateWith(new UpdateDynamicAttributeOpcode(reference, attribute)); } } if ('type' in this.attributes) { var type = this.attributes.type; var _reference = type.value, _namespace2 = type.namespace, _trusting = type.trusting; var _attribute = vm.elements().setDynamicAttribute('type', _reference.value(), _trusting, _namespace2); if (!(0, _reference2.isConst)(_reference)) { vm.updateWith(new UpdateDynamicAttributeOpcode(_reference, _attribute)); } } return this.modifiers; }; return ComponentElementOperations; }(); APPEND_OPCODES.add(93 /* DidCreateElement */ , function (vm, _ref39) { var _state = _ref39.op1; var _vm$fetchValue2 = vm.fetchValue(_state), definition = _vm$fetchValue2.definition, state = _vm$fetchValue2.state; var manager = definition.manager; var operations = vm.fetchValue(_vm2.Register.t0); var action = 'DidCreateElementOpcode#evaluate'; manager.didCreateElement(state, vm.elements().expectConstructing(action), operations); }); APPEND_OPCODES.add(84 /* GetComponentSelf */ , function (vm, _ref40) { var _state = _ref40.op1; var _vm$fetchValue3 = vm.fetchValue(_state), definition = _vm$fetchValue3.definition, state = _vm$fetchValue3.state; var manager = definition.manager; vm.stack.push(manager.getSelf(state)); }); APPEND_OPCODES.add(85 /* GetComponentTagName */ , function (vm, _ref41) { var _state = _ref41.op1; var _vm$fetchValue4 = vm.fetchValue(_state), definition = _vm$fetchValue4.definition, state = _vm$fetchValue4.state; var manager = definition.manager; vm.stack.push(manager.getTagName(state)); }); // Dynamic Invocation Only APPEND_OPCODES.add(86 /* GetComponentLayout */ , function (vm, _ref42) { var _state = _ref42.op1; var instance = vm.fetchValue(_state); var manager = instance.manager, definition = instance.definition; var resolver = vm.constants.resolver, stack = vm.stack; var instanceState = instance.state, capabilities = instance.capabilities; var definitionState = definition.state; var invoke; if (hasStaticLayoutCapability(capabilities, manager)) { invoke = manager.getLayout(definitionState, resolver); } else if (hasDynamicLayoutCapability(capabilities, manager)) { invoke = manager.getDynamicLayout(instanceState, resolver); } else { throw (0, _util.unreachable)(); } stack.push(invoke.symbolTable); stack.push(invoke.handle); }); function hasStaticLayoutCapability(capabilities, _manager) { return hasCapability(capabilities, 1 /* DynamicLayout */ ) === false; } function hasDynamicLayoutCapability(capabilities, _manager) { return hasCapability(capabilities, 1 /* DynamicLayout */ ) === true; } APPEND_OPCODES.add(68 /* Main */ , function (vm, _ref43) { var register = _ref43.op1; var definition = vm.stack.pop(); var invocation = vm.stack.pop(); var manager = definition.manager; var capabilities = capabilityFlagsFrom(manager.getCapabilities(definition.state)); var state = { definition: definition, manager: manager, capabilities: capabilities, state: null, handle: invocation.handle, table: invocation.symbolTable, lookup: null }; vm.loadValue(register, state); }); APPEND_OPCODES.add(89 /* PopulateLayout */ , function (vm, _ref44) { var _state = _ref44.op1; var stack = vm.stack; var handle = stack.pop(); var table = stack.pop(); var state = vm.fetchValue(_state); state.handle = handle; state.table = table; }); APPEND_OPCODES.add(21 /* VirtualRootScope */ , function (vm, _ref45) { var _state = _ref45.op1; var symbols = vm.fetchValue(_state).table.symbols; vm.pushRootScope(symbols.length + 1, true); }); APPEND_OPCODES.add(87 /* SetupForEval */ , function (vm, _ref46) { var _state = _ref46.op1; var state = vm.fetchValue(_state); if (state.table.hasEval) { var lookup = state.lookup = (0, _util.dict)(); vm.scope().bindEvalScope(lookup); } }); APPEND_OPCODES.add(2 /* SetNamedVariables */ , function (vm, _ref47) { var _state = _ref47.op1; var state = vm.fetchValue(_state); var scope = vm.scope(); var args = vm.stack.peek(); var callerNames = args.named.atNames; for (var i = callerNames.length - 1; i >= 0; i--) { var atName = callerNames[i]; var symbol = state.table.symbols.indexOf(callerNames[i]); var value$$1 = args.named.get(atName, false); if (symbol !== -1) scope.bindSymbol(symbol + 1, value$$1); if (state.lookup) state.lookup[atName] = value$$1; } }); function bindBlock(symbolName, blockName, state, blocks, vm) { var symbol = state.table.symbols.indexOf(symbolName); var block = blocks.get(blockName); if (symbol !== -1) { vm.scope().bindBlock(symbol + 1, block); } if (state.lookup) state.lookup[symbolName] = block; } APPEND_OPCODES.add(3 /* SetBlocks */ , function (vm, _ref48) { var _state = _ref48.op1; var state = vm.fetchValue(_state); var _vm$stack$peek = vm.stack.peek(), blocks = _vm$stack$peek.blocks; bindBlock('&attrs', 'attrs', state, blocks, vm); bindBlock('&inverse', 'else', state, blocks, vm); bindBlock('&default', 'main', state, blocks, vm); }); // Dynamic Invocation Only APPEND_OPCODES.add(90 /* InvokeComponentLayout */ , function (vm, _ref49) { var _state = _ref49.op1; var state = vm.fetchValue(_state); vm.call(state.handle); }); APPEND_OPCODES.add(94 /* DidRenderLayout */ , function (vm, _ref50) { var _state = _ref50.op1; var _vm$fetchValue5 = vm.fetchValue(_state), manager = _vm$fetchValue5.manager, state = _vm$fetchValue5.state; var bounds = vm.elements().popBlock(); var mgr = manager; mgr.didRenderLayout(state, bounds); vm.env.didCreate(state, manager); vm.updateWith(new DidUpdateLayoutOpcode(manager, state, bounds)); }); APPEND_OPCODES.add(92 /* CommitComponentTransaction */ , function (vm) { vm.commitCacheGroup(); }); var UpdateComponentOpcode = /*#__PURE__*/ function (_UpdatingOpcode7) { (0, _emberBabel.inheritsLoose)(UpdateComponentOpcode, _UpdatingOpcode7); function UpdateComponentOpcode(tag, component, manager, dynamicScope) { var _this10; _this10 = _UpdatingOpcode7.call(this) || this; _this10.tag = tag; _this10.component = component; _this10.manager = manager; _this10.dynamicScope = dynamicScope; _this10.type = 'update-component'; return _this10; } var _proto19 = UpdateComponentOpcode.prototype; _proto19.evaluate = function evaluate(_vm) { var component = this.component, manager = this.manager, dynamicScope = this.dynamicScope; manager.update(component, dynamicScope); }; return UpdateComponentOpcode; }(UpdatingOpcode); var DidUpdateLayoutOpcode = /*#__PURE__*/ function (_UpdatingOpcode8) { (0, _emberBabel.inheritsLoose)(DidUpdateLayoutOpcode, _UpdatingOpcode8); function DidUpdateLayoutOpcode(manager, component, bounds) { var _this11; _this11 = _UpdatingOpcode8.call(this) || this; _this11.manager = manager; _this11.component = component; _this11.bounds = bounds; _this11.type = 'did-update-layout'; _this11.tag = _reference2.CONSTANT_TAG; return _this11; } var _proto20 = DidUpdateLayoutOpcode.prototype; _proto20.evaluate = function evaluate(vm) { var manager = this.manager, component = this.component, bounds = this.bounds; manager.didUpdateLayout(component, bounds); vm.env.didUpdate(component, manager); }; return DidUpdateLayoutOpcode; }(UpdatingOpcode); /* tslint:disable */ function debugCallback(context, get) { console.info('Use `context`, and `get(<path>)` to debug this template.'); // for example... context === get('this'); debugger; } /* tslint:enable */ var callback = debugCallback; // For testing purposes function setDebuggerCallback(cb) { callback = cb; } function resetDebuggerCallback() { callback = debugCallback; } var ScopeInspector = /*#__PURE__*/ function () { function ScopeInspector(scope, symbols, evalInfo) { this.scope = scope; this.locals = (0, _util.dict)(); for (var i = 0; i < evalInfo.length; i++) { var slot = evalInfo[i]; var name = symbols[slot - 1]; var ref = scope.getSymbol(slot); this.locals[name] = ref; } } var _proto21 = ScopeInspector.prototype; _proto21.get = function get(path) { var scope = this.scope, locals = this.locals; var parts = path.split('.'); var _path$split = path.split('.'), head = _path$split[0], tail = _path$split.slice(1); var evalScope = scope.getEvalScope(); var ref; if (head === 'this') { ref = scope.getSelf(); } else if (locals[head]) { ref = locals[head]; } else if (head.indexOf('@') === 0 && evalScope[head]) { ref = evalScope[head]; } else { ref = this.scope.getSelf(); tail = parts; } return tail.reduce(function (r, part) { return r.get(part); }, ref); }; return ScopeInspector; }(); APPEND_OPCODES.add(97 /* Debugger */ , function (vm, _ref51) { var _symbols = _ref51.op1, _evalInfo = _ref51.op2; var symbols = vm.constants.getStringArray(_symbols); var evalInfo = vm.constants.getArray(_evalInfo); var inspector = new ScopeInspector(vm.scope(), symbols, evalInfo); callback(vm.getSelf().value(), function (path) { return inspector.get(path).value(); }); }); APPEND_OPCODES.add(95 /* InvokePartial */ , function (vm, _ref52) { var _meta = _ref52.op1, _symbols = _ref52.op2, _evalInfo = _ref52.op3; var constants = vm.constants, resolver = vm.constants.resolver, stack = vm.stack; var name = stack.pop().value(); var meta = constants.getSerializable(_meta); var outerSymbols = constants.getStringArray(_symbols); var evalInfo = constants.getArray(_evalInfo); var handle = resolver.lookupPartial(name, meta); var definition = resolver.resolve(handle); var _definition$getPartia = definition.getPartial(), symbolTable = _definition$getPartia.symbolTable, vmHandle = _definition$getPartia.handle; { var partialSymbols = symbolTable.symbols; var outerScope = vm.scope(); var partialScope = vm.pushRootScope(partialSymbols.length, false); var evalScope = outerScope.getEvalScope(); partialScope.bindCallerScope(outerScope.getCallerScope()); partialScope.bindEvalScope(evalScope); partialScope.bindSelf(outerScope.getSelf()); var locals = Object.create(outerScope.getPartialMap()); for (var i = 0; i < evalInfo.length; i++) { var slot = evalInfo[i]; var _name2 = outerSymbols[slot - 1]; var ref = outerScope.getSymbol(slot); locals[_name2] = ref; } if (evalScope) { for (var _i3 = 0; _i3 < partialSymbols.length; _i3++) { var _name3 = partialSymbols[_i3]; var symbol = _i3 + 1; var value$$1 = evalScope[_name3]; if (value$$1 !== undefined) partialScope.bind(symbol, value$$1); } } partialScope.bindPartialMap(locals); vm.pushFrame(); // sp += 2 vm.call(vmHandle); } }); var IterablePresenceReference = /*#__PURE__*/ function () { function IterablePresenceReference(artifacts) { this.tag = artifacts.tag; this.artifacts = artifacts; } var _proto22 = IterablePresenceReference.prototype; _proto22.value = function value() { return !this.artifacts.isEmpty(); }; return IterablePresenceReference; }(); APPEND_OPCODES.add(66 /* PutIterator */ , function (vm) { var stack = vm.stack; var listRef = stack.pop(); var key = stack.pop(); var iterable = vm.env.iterableFor(listRef, key.value()); var iterator = new _reference2.ReferenceIterator(iterable); stack.push(iterator); stack.push(new IterablePresenceReference(iterator.artifacts)); }); APPEND_OPCODES.add(64 /* EnterList */ , function (vm, _ref53) { var relativeStart = _ref53.op1; vm.enterList(relativeStart); }); APPEND_OPCODES.add(65 /* ExitList */ , function (vm) { vm.exitList(); }); APPEND_OPCODES.add(67 /* Iterate */ , function (vm, _ref54) { var breaks = _ref54.op1; var stack = vm.stack; var item = stack.peek().next(); if (item) { var tryOpcode = vm.iterate(item.memo, item.value); vm.enterItem(item.key, tryOpcode); } else { vm.goto(breaks); } }); var Cursor = function Cursor(element, nextSibling) { this.element = element; this.nextSibling = nextSibling; }; _exports.Cursor = Cursor; var ConcreteBounds = /*#__PURE__*/ function () { function ConcreteBounds(parentNode, first, last) { this.parentNode = parentNode; this.first = first; this.last = last; } var _proto23 = ConcreteBounds.prototype; _proto23.parentElement = function parentElement() { return this.parentNode; }; _proto23.firstNode = function firstNode() { return this.first; }; _proto23.lastNode = function lastNode() { return this.last; }; return ConcreteBounds; }(); _exports.ConcreteBounds = ConcreteBounds; var SingleNodeBounds = /*#__PURE__*/ function () { function SingleNodeBounds(parentNode, node) { this.parentNode = parentNode; this.node = node; } var _proto24 = SingleNodeBounds.prototype; _proto24.parentElement = function parentElement() { return this.parentNode; }; _proto24.firstNode = function firstNode() { return this.node; }; _proto24.lastNode = function lastNode() { return this.node; }; return SingleNodeBounds; }(); function _move(bounds, reference) { var parent = bounds.parentElement(); var first = bounds.firstNode(); var last = bounds.lastNode(); var current = first; while (true) { var next = current.nextSibling; parent.insertBefore(current, reference); if (current === last) { return next; } current = next; } } function clear(bounds) { var parent = bounds.parentElement(); var first = bounds.firstNode(); var last = bounds.lastNode(); var current = first; while (true) { var next = current.nextSibling; parent.removeChild(current); if (current === last) { return next; } current = next; } } // Patch: insertAdjacentHTML on SVG Fix // Browsers: Safari, IE, Edge, Firefox ~33-34 // Reason: insertAdjacentHTML does not exist on SVG elements in Safari. It is // present but throws an exception on IE and Edge. Old versions of // Firefox create nodes in the incorrect namespace. // Fix: Since IE and Edge silently fail to create SVG nodes using // innerHTML, and because Firefox may create nodes in the incorrect // namespace using innerHTML on SVG elements, an HTML-string wrapping // approach is used. A pre/post SVG tag is added to the string, then // that whole string is added to a div. The created nodes are plucked // out and applied to the target location on DOM. function applySVGInnerHTMLFix(document, DOMClass, svgNamespace) { if (!document) return DOMClass; if (!shouldApplyFix(document, svgNamespace)) { return DOMClass; } var div = document.createElement('div'); return ( /*#__PURE__*/ function (_DOMClass) { (0, _emberBabel.inheritsLoose)(DOMChangesWithSVGInnerHTMLFix, _DOMClass); function DOMChangesWithSVGInnerHTMLFix() { return _DOMClass.apply(this, arguments) || this; } var _proto25 = DOMChangesWithSVGInnerHTMLFix.prototype; _proto25.insertHTMLBefore = function insertHTMLBefore(parent, nextSibling, html) { if (html === '') { return _DOMClass.prototype.insertHTMLBefore.call(this, parent, nextSibling, html); } if (parent.namespaceURI !== svgNamespace) { return _DOMClass.prototype.insertHTMLBefore.call(this, parent, nextSibling, html); } return fixSVG(parent, div, html, nextSibling); }; return DOMChangesWithSVGInnerHTMLFix; }(DOMClass) ); } function fixSVG(parent, div, html, reference) { var source; // This is important, because decendants of the <foreignObject> integration // point are parsed in the HTML namespace if (parent.tagName.toUpperCase() === 'FOREIGNOBJECT') { // IE, Edge: also do not correctly support using `innerHTML` on SVG // namespaced elements. So here a wrapper is used. var wrappedHtml = '<svg><foreignObject>' + html + '</foreignObject></svg>'; div.innerHTML = wrappedHtml; source = div.firstChild.firstChild; } else { // IE, Edge: also do not correctly support using `innerHTML` on SVG // namespaced elements. So here a wrapper is used. var _wrappedHtml = '<svg>' + html + '</svg>'; div.innerHTML = _wrappedHtml; source = div.firstChild; } return moveNodesBefore(source, parent, reference); } function shouldApplyFix(document, svgNamespace) { var svg = document.createElementNS(svgNamespace, 'svg'); try { svg['insertAdjacentHTML']('beforeend', '<circle></circle>'); } catch (e) {// IE, Edge: Will throw, insertAdjacentHTML is unsupported on SVG // Safari: Will throw, insertAdjacentHTML is not present on SVG } finally { // FF: Old versions will create a node in the wrong namespace if (svg.childNodes.length === 1 && svg.firstChild.namespaceURI === SVG_NAMESPACE) { // The test worked as expected, no fix required return false; } return true; } } // Patch: Adjacent text node merging fix // Browsers: IE, Edge, Firefox w/o inspector open // Reason: These browsers will merge adjacent text nodes. For exmaple given // <div>Hello</div> with div.insertAdjacentHTML(' world') browsers // with proper behavior will populate div.childNodes with two items. // These browsers will populate it with one merged node instead. // Fix: Add these nodes to a wrapper element, then iterate the childNodes // of that wrapper and move the nodes to their target location. Note // that potential SVG bugs will have been handled before this fix. // Note that this fix must only apply to the previous text node, as // the base implementation of `insertHTMLBefore` already handles // following text nodes correctly. function applyTextNodeMergingFix(document, DOMClass) { if (!document) return DOMClass; if (!shouldApplyFix$1(document)) { return DOMClass; } return ( /*#__PURE__*/ function (_DOMClass2) { (0, _emberBabel.inheritsLoose)(DOMChangesWithTextNodeMergingFix, _DOMClass2); function DOMChangesWithTextNodeMergingFix(document) { var _this12; _this12 = _DOMClass2.call(this, document) || this; _this12.uselessComment = document.createComment(''); return _this12; } var _proto26 = DOMChangesWithTextNodeMergingFix.prototype; _proto26.insertHTMLBefore = function insertHTMLBefore(parent, nextSibling, html) { if (html === '') { return _DOMClass2.prototype.insertHTMLBefore.call(this, parent, nextSibling, html); } var didSetUselessComment = false; var nextPrevious = nextSibling ? nextSibling.previousSibling : parent.lastChild; if (nextPrevious && nextPrevious instanceof Text) { didSetUselessComment = true; parent.insertBefore(this.uselessComment, nextSibling); } var bounds = _DOMClass2.prototype.insertHTMLBefore.call(this, parent, nextSibling, html); if (didSetUselessComment) { parent.removeChild(this.uselessComment); } return bounds; }; return DOMChangesWithTextNodeMergingFix; }(DOMClass) ); } function shouldApplyFix$1(document) { var mergingTextDiv = document.createElement('div'); mergingTextDiv.innerHTML = 'first'; mergingTextDiv.insertAdjacentHTML('beforeend', 'second'); if (mergingTextDiv.childNodes.length === 2) { // It worked as expected, no fix required return false; } return true; } var SVG_NAMESPACE = "http://www.w3.org/2000/svg" /* SVG */ ; // http://www.w3.org/TR/html/syntax.html#html-integration-point _exports.SVG_NAMESPACE = SVG_NAMESPACE; var SVG_INTEGRATION_POINTS = { foreignObject: 1, desc: 1, title: 1 }; // http://www.w3.org/TR/html/syntax.html#adjust-svg-attributes // TODO: Adjust SVG attributes // http://www.w3.org/TR/html/syntax.html#parsing-main-inforeign // TODO: Adjust SVG elements // http://www.w3.org/TR/html/syntax.html#parsing-main-inforeign var BLACKLIST_TABLE = Object.create(null); ['b', 'big', 'blockquote', 'body', 'br', 'center', 'code', 'dd', 'div', 'dl', 'dt', 'em', 'embed', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'hr', 'i', 'img', 'li', 'listing', 'main', 'meta', 'nobr', 'ol', 'p', 'pre', 'ruby', 's', 'small', 'span', 'strong', 'strike', 'sub', 'sup', 'table', 'tt', 'u', 'ul', 'var'].forEach(function (tag) { return BLACKLIST_TABLE[tag] = 1; }); var WHITESPACE = /[\t-\r \xA0\u1680\u180E\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF]/; var doc = typeof document === 'undefined' ? null : document; function isWhitespace(string) { return WHITESPACE.test(string); } function moveNodesBefore(source, target, nextSibling) { var first = source.firstChild; var last = first; var current = first; while (current) { var next = current.nextSibling; target.insertBefore(current, nextSibling); last = current; current = next; } return new ConcreteBounds(target, first, last); } var DOMOperations = /*#__PURE__*/ function () { function DOMOperations(document) { this.document = document; this.setupUselessElement(); } // split into seperate method so that NodeDOMTreeConstruction // can override it. var _proto27 = DOMOperations.prototype; _proto27.setupUselessElement = function setupUselessElement() { this.uselessElement = this.document.createElement('div'); }; _proto27.createElement = function createElement(tag, context) { var isElementInSVGNamespace, isHTMLIntegrationPoint; if (context) { isElementInSVGNamespace = context.namespaceURI === SVG_NAMESPACE || tag === 'svg'; isHTMLIntegrationPoint = SVG_INTEGRATION_POINTS[context.tagName]; } else { isElementInSVGNamespace = tag === 'svg'; isHTMLIntegrationPoint = false; } if (isElementInSVGNamespace && !isHTMLIntegrationPoint) { // FIXME: This does not properly handle <font> with color, face, or // size attributes, which is also disallowed by the spec. We should fix // this. if (BLACKLIST_TABLE[tag]) { throw new Error("Cannot create a " + tag + " inside an SVG context"); } return this.document.createElementNS(SVG_NAMESPACE, tag); } else { return this.document.createElement(tag); } }; _proto27.insertBefore = function insertBefore(parent, node, reference) { parent.insertBefore(node, reference); }; _proto27.insertHTMLBefore = function insertHTMLBefore(parent, nextSibling, html) { if (html === '') { var comment = this.createComment(''); parent.insertBefore(comment, nextSibling); return new ConcreteBounds(parent, comment, comment); } var prev = nextSibling ? nextSibling.previousSibling : parent.lastChild; var last; if (nextSibling === null) { parent.insertAdjacentHTML("beforeend" /* beforeend */ , html); last = parent.lastChild; } else if (nextSibling instanceof HTMLElement) { nextSibling.insertAdjacentHTML("beforebegin" /* beforebegin */ , html); last = nextSibling.previousSibling; } else { // Non-element nodes do not support insertAdjacentHTML, so add an // element and call it on that element. Then remove the element. // // This also protects Edge, IE and Firefox w/o the inspector open // from merging adjacent text nodes. See ./compat/text-node-merging-fix.ts var uselessElement = this.uselessElement; parent.insertBefore(uselessElement, nextSibling); uselessElement.insertAdjacentHTML("beforebegin" /* beforebegin */ , html); last = uselessElement.previousSibling; parent.removeChild(uselessElement); } var first = prev ? prev.nextSibling : parent.firstChild; return new ConcreteBounds(parent, first, last); }; _proto27.createTextNode = function createTextNode(text) { return this.document.createTextNode(text); }; _proto27.createComment = function createComment(data) { return this.document.createComment(data); }; return DOMOperations; }(); var DOM; (function (DOM) { var TreeConstruction = /*#__PURE__*/ function (_DOMOperations) { (0, _emberBabel.inheritsLoose)(TreeConstruction, _DOMOperations); function TreeConstruction() { return _DOMOperations.apply(this, arguments) || this; } var _proto28 = TreeConstruction.prototype; _proto28.createElementNS = function createElementNS(namespace, tag) { return this.document.createElementNS(namespace, tag); }; _proto28.setAttribute = function setAttribute(element, name, value$$1, namespace) { if (namespace === void 0) { namespace = null; } if (namespace) { element.setAttributeNS(namespace, name, value$$1); } else { element.setAttribute(name, value$$1); } }; return TreeConstruction; }(DOMOperations); DOM.TreeConstruction = TreeConstruction; var appliedTreeContruction = TreeConstruction; appliedTreeContruction = applyTextNodeMergingFix(doc, appliedTreeContruction); appliedTreeContruction = applySVGInnerHTMLFix(doc, appliedTreeContruction, SVG_NAMESPACE); DOM.DOMTreeConstruction = appliedTreeContruction; })(DOM || (DOM = {})); var DOMChanges = /*#__PURE__*/ function (_DOMOperations2) { (0, _emberBabel.inheritsLoose)(DOMChanges, _DOMOperations2); function DOMChanges(document) { var _this13; _this13 = _DOMOperations2.call(this, document) || this; _this13.document = document; _this13.namespace = null; return _this13; } var _proto29 = DOMChanges.prototype; _proto29.setAttribute = function setAttribute(element, name, value$$1) { element.setAttribute(name, value$$1); }; _proto29.removeAttribute = function removeAttribute(element, name) { element.removeAttribute(name); }; _proto29.insertAfter = function insertAfter(element, node, reference) { this.insertBefore(element, node, reference.nextSibling); }; return DOMChanges; }(DOMOperations); _exports.IDOMChanges = DOMChanges; var helper = DOMChanges; helper = applyTextNodeMergingFix(doc, helper); helper = applySVGInnerHTMLFix(doc, helper, SVG_NAMESPACE); var helper$1 = helper; _exports.DOMChanges = helper$1; var DOMTreeConstruction = DOM.DOMTreeConstruction; _exports.DOMTreeConstruction = DOMTreeConstruction; var badProtocols = ['javascript:', 'vbscript:']; var badTags = ['A', 'BODY', 'LINK', 'IMG', 'IFRAME', 'BASE', 'FORM']; var badTagsForDataURI = ['EMBED']; var badAttributes = ['href', 'src', 'background', 'action']; var badAttributesForDataURI = ['src']; function has(array, item) { return array.indexOf(item) !== -1; } function checkURI(tagName, attribute) { return (tagName === null || has(badTags, tagName)) && has(badAttributes, attribute); } function checkDataURI(tagName, attribute) { if (tagName === null) return false; return has(badTagsForDataURI, tagName) && has(badAttributesForDataURI, attribute); } function requiresSanitization(tagName, attribute) { return checkURI(tagName, attribute) || checkDataURI(tagName, attribute); } function sanitizeAttributeValue(env, element, attribute, value$$1) { var tagName = null; if (value$$1 === null || value$$1 === undefined) { return value$$1; } if (isSafeString(value$$1)) { return value$$1.toHTML(); } if (!element) { tagName = null; } else { tagName = element.tagName.toUpperCase(); } var str = normalizeStringValue(value$$1); if (checkURI(tagName, attribute)) { var protocol = env.protocolForURL(str); if (has(badProtocols, protocol)) { return "unsafe:" + str; } } if (checkDataURI(tagName, attribute)) { return "unsafe:" + str; } return str; } /* * @method normalizeProperty * @param element {HTMLElement} * @param slotName {String} * @returns {Object} { name, type } */ function normalizeProperty(element, slotName) { var type, normalized; if (slotName in element) { normalized = slotName; type = 'prop'; } else { var lower = slotName.toLowerCase(); if (lower in element) { type = 'prop'; normalized = lower; } else { type = 'attr'; normalized = slotName; } } if (type === 'prop' && (normalized.toLowerCase() === 'style' || preferAttr(element.tagName, normalized))) { type = 'attr'; } return { normalized: normalized, type: type }; } // properties that MUST be set as attributes, due to: // * browser bug // * strange spec outlier var ATTR_OVERRIDES = { INPUT: { form: true, // Chrome 46.0.2464.0: 'autocorrect' in document.createElement('input') === false // Safari 8.0.7: 'autocorrect' in document.createElement('input') === false // Mobile Safari (iOS 8.4 simulator): 'autocorrect' in document.createElement('input') === true autocorrect: true, // Chrome 54.0.2840.98: 'list' in document.createElement('input') === true // Safari 9.1.3: 'list' in document.createElement('input') === false list: true }, // element.form is actually a legitimate readOnly property, that is to be // mutated, but must be mutated by setAttribute... SELECT: { form: true }, OPTION: { form: true }, TEXTAREA: { form: true }, LABEL: { form: true }, FIELDSET: { form: true }, LEGEND: { form: true }, OBJECT: { form: true }, BUTTON: { form: true } }; function preferAttr(tagName, propName) { var tag = ATTR_OVERRIDES[tagName.toUpperCase()]; return tag && tag[propName.toLowerCase()] || false; } function dynamicAttribute(element, attr, namespace) { var tagName = element.tagName, namespaceURI = element.namespaceURI; var attribute = { element: element, name: attr, namespace: namespace }; if (namespaceURI === SVG_NAMESPACE) { return buildDynamicAttribute(tagName, attr, attribute); } var _normalizeProperty = normalizeProperty(element, attr), type = _normalizeProperty.type, normalized = _normalizeProperty.normalized; if (type === 'attr') { return buildDynamicAttribute(tagName, normalized, attribute); } else { return buildDynamicProperty(tagName, normalized, attribute); } } function buildDynamicAttribute(tagName, name, attribute) { if (requiresSanitization(tagName, name)) { return new SafeDynamicAttribute(attribute); } else { return new SimpleDynamicAttribute(attribute); } } function buildDynamicProperty(tagName, name, attribute) { if (requiresSanitization(tagName, name)) { return new SafeDynamicProperty(name, attribute); } if (isUserInputValue(tagName, name)) { return new InputValueDynamicAttribute(name, attribute); } if (isOptionSelected(tagName, name)) { return new OptionSelectedDynamicAttribute(name, attribute); } return new DefaultDynamicProperty(name, attribute); } var DynamicAttribute = function DynamicAttribute(attribute) { this.attribute = attribute; }; _exports.DynamicAttribute = DynamicAttribute; var SimpleDynamicAttribute = /*#__PURE__*/ function (_DynamicAttribute) { (0, _emberBabel.inheritsLoose)(SimpleDynamicAttribute, _DynamicAttribute); function SimpleDynamicAttribute() { return _DynamicAttribute.apply(this, arguments) || this; } var _proto30 = SimpleDynamicAttribute.prototype; _proto30.set = function set(dom, value$$1, _env) { var normalizedValue = normalizeValue(value$$1); if (normalizedValue !== null) { var _this$attribute = this.attribute, name = _this$attribute.name, namespace = _this$attribute.namespace; dom.__setAttribute(name, normalizedValue, namespace); } }; _proto30.update = function update(value$$1, _env) { var normalizedValue = normalizeValue(value$$1); var _this$attribute2 = this.attribute, element = _this$attribute2.element, name = _this$attribute2.name; if (normalizedValue === null) { element.removeAttribute(name); } else { element.setAttribute(name, normalizedValue); } }; return SimpleDynamicAttribute; }(DynamicAttribute); _exports.SimpleDynamicAttribute = SimpleDynamicAttribute; var DefaultDynamicProperty = /*#__PURE__*/ function (_DynamicAttribute2) { (0, _emberBabel.inheritsLoose)(DefaultDynamicProperty, _DynamicAttribute2); function DefaultDynamicProperty(normalizedName, attribute) { var _this14; _this14 = _DynamicAttribute2.call(this, attribute) || this; _this14.normalizedName = normalizedName; return _this14; } var _proto31 = DefaultDynamicProperty.prototype; _proto31.set = function set(dom, value$$1, _env) { if (value$$1 !== null && value$$1 !== undefined) { this.value = value$$1; dom.__setProperty(this.normalizedName, value$$1); } }; _proto31.update = function update(value$$1, _env) { var element = this.attribute.element; if (this.value !== value$$1) { element[this.normalizedName] = this.value = value$$1; if (value$$1 === null || value$$1 === undefined) { this.removeAttribute(); } } }; _proto31.removeAttribute = function removeAttribute() { // TODO this sucks but to preserve properties first and to meet current // semantics we must do this. var _this$attribute3 = this.attribute, element = _this$attribute3.element, namespace = _this$attribute3.namespace; if (namespace) { element.removeAttributeNS(namespace, this.normalizedName); } else { element.removeAttribute(this.normalizedName); } }; return DefaultDynamicProperty; }(DynamicAttribute); var SafeDynamicProperty = /*#__PURE__*/ function (_DefaultDynamicProper) { (0, _emberBabel.inheritsLoose)(SafeDynamicProperty, _DefaultDynamicProper); function SafeDynamicProperty() { return _DefaultDynamicProper.apply(this, arguments) || this; } var _proto32 = SafeDynamicProperty.prototype; _proto32.set = function set(dom, value$$1, env) { var _this$attribute4 = this.attribute, element = _this$attribute4.element, name = _this$attribute4.name; var sanitized = sanitizeAttributeValue(env, element, name, value$$1); _DefaultDynamicProper.prototype.set.call(this, dom, sanitized, env); }; _proto32.update = function update(value$$1, env) { var _this$attribute5 = this.attribute, element = _this$attribute5.element, name = _this$attribute5.name; var sanitized = sanitizeAttributeValue(env, element, name, value$$1); _DefaultDynamicProper.prototype.update.call(this, sanitized, env); }; return SafeDynamicProperty; }(DefaultDynamicProperty); var SafeDynamicAttribute = /*#__PURE__*/ function (_SimpleDynamicAttribu) { (0, _emberBabel.inheritsLoose)(SafeDynamicAttribute, _SimpleDynamicAttribu); function SafeDynamicAttribute() { return _SimpleDynamicAttribu.apply(this, arguments) || this; } var _proto33 = SafeDynamicAttribute.prototype; _proto33.set = function set(dom, value$$1, env) { var _this$attribute6 = this.attribute, element = _this$attribute6.element, name = _this$attribute6.name; var sanitized = sanitizeAttributeValue(env, element, name, value$$1); _SimpleDynamicAttribu.prototype.set.call(this, dom, sanitized, env); }; _proto33.update = function update(value$$1, env) { var _this$attribute7 = this.attribute, element = _this$attribute7.element, name = _this$attribute7.name; var sanitized = sanitizeAttributeValue(env, element, name, value$$1); _SimpleDynamicAttribu.prototype.update.call(this, sanitized, env); }; return SafeDynamicAttribute; }(SimpleDynamicAttribute); var InputValueDynamicAttribute = /*#__PURE__*/ function (_DefaultDynamicProper2) { (0, _emberBabel.inheritsLoose)(InputValueDynamicAttribute, _DefaultDynamicProper2); function InputValueDynamicAttribute() { return _DefaultDynamicProper2.apply(this, arguments) || this; } var _proto34 = InputValueDynamicAttribute.prototype; _proto34.set = function set(dom, value$$1) { dom.__setProperty('value', normalizeStringValue(value$$1)); }; _proto34.update = function update(value$$1) { var input = this.attribute.element; var currentValue = input.value; var normalizedValue = normalizeStringValue(value$$1); if (currentValue !== normalizedValue) { input.value = normalizedValue; } }; return InputValueDynamicAttribute; }(DefaultDynamicProperty); var OptionSelectedDynamicAttribute = /*#__PURE__*/ function (_DefaultDynamicProper3) { (0, _emberBabel.inheritsLoose)(OptionSelectedDynamicAttribute, _DefaultDynamicProper3); function OptionSelectedDynamicAttribute() { return _DefaultDynamicProper3.apply(this, arguments) || this; } var _proto35 = OptionSelectedDynamicAttribute.prototype; _proto35.set = function set(dom, value$$1) { if (value$$1 !== null && value$$1 !== undefined && value$$1 !== false) { dom.__setProperty('selected', true); } }; _proto35.update = function update(value$$1) { var option = this.attribute.element; if (value$$1) { option.selected = true; } else { option.selected = false; } }; return OptionSelectedDynamicAttribute; }(DefaultDynamicProperty); function isOptionSelected(tagName, attribute) { return tagName === 'OPTION' && attribute === 'selected'; } function isUserInputValue(tagName, attribute) { return (tagName === 'INPUT' || tagName === 'TEXTAREA') && attribute === 'value'; } function normalizeValue(value$$1) { if (value$$1 === false || value$$1 === undefined || value$$1 === null || typeof value$$1.toString === 'undefined') { return null; } if (value$$1 === true) { return ''; } // onclick function etc in SSR if (typeof value$$1 === 'function') { return null; } return String(value$$1); } var Scope = /*#__PURE__*/ function () { function Scope( // the 0th slot is `self` slots, callerScope, // named arguments and blocks passed to a layout that uses eval evalScope, // locals in scope when the partial was invoked partialMap) { this.slots = slots; this.callerScope = callerScope; this.evalScope = evalScope; this.partialMap = partialMap; } Scope.root = function root(self, size) { if (size === void 0) { size = 0; } var refs = new Array(size + 1); for (var i = 0; i <= size; i++) { refs[i] = UNDEFINED_REFERENCE; } return new Scope(refs, null, null, null).init({ self: self }); }; Scope.sized = function sized(size) { if (size === void 0) { size = 0; } var refs = new Array(size + 1); for (var i = 0; i <= size; i++) { refs[i] = UNDEFINED_REFERENCE; } return new Scope(refs, null, null, null); }; var _proto36 = Scope.prototype; _proto36.init = function init(_ref55) { var self = _ref55.self; this.slots[0] = self; return this; }; _proto36.getSelf = function getSelf() { return this.get(0); }; _proto36.getSymbol = function getSymbol(symbol) { return this.get(symbol); }; _proto36.getBlock = function getBlock(symbol) { var block = this.get(symbol); return block === UNDEFINED_REFERENCE ? null : block; }; _proto36.getEvalScope = function getEvalScope() { return this.evalScope; }; _proto36.getPartialMap = function getPartialMap() { return this.partialMap; }; _proto36.bind = function bind(symbol, value$$1) { this.set(symbol, value$$1); }; _proto36.bindSelf = function bindSelf(self) { this.set(0, self); }; _proto36.bindSymbol = function bindSymbol(symbol, value$$1) { this.set(symbol, value$$1); }; _proto36.bindBlock = function bindBlock(symbol, value$$1) { this.set(symbol, value$$1); }; _proto36.bindEvalScope = function bindEvalScope(map) { this.evalScope = map; }; _proto36.bindPartialMap = function bindPartialMap(map) { this.partialMap = map; }; _proto36.bindCallerScope = function bindCallerScope(scope) { this.callerScope = scope; }; _proto36.getCallerScope = function getCallerScope() { return this.callerScope; }; _proto36.child = function child() { return new Scope(this.slots.slice(), this.callerScope, this.evalScope, this.partialMap); }; _proto36.get = function get(index) { if (index >= this.slots.length) { throw new RangeError("BUG: cannot get $" + index + " from scope; length=" + this.slots.length); } return this.slots[index]; }; _proto36.set = function set(index, value$$1) { if (index >= this.slots.length) { throw new RangeError("BUG: cannot get $" + index + " from scope; length=" + this.slots.length); } this.slots[index] = value$$1; }; return Scope; }(); _exports.Scope = Scope; var Transaction = /*#__PURE__*/ function () { function Transaction() { this.scheduledInstallManagers = []; this.scheduledInstallModifiers = []; this.scheduledUpdateModifierManagers = []; this.scheduledUpdateModifiers = []; this.createdComponents = []; this.createdManagers = []; this.updatedComponents = []; this.updatedManagers = []; this.destructors = []; } var _proto37 = Transaction.prototype; _proto37.didCreate = function didCreate(component, manager) { this.createdComponents.push(component); this.createdManagers.push(manager); }; _proto37.didUpdate = function didUpdate(component, manager) { this.updatedComponents.push(component); this.updatedManagers.push(manager); }; _proto37.scheduleInstallModifier = function scheduleInstallModifier(modifier, manager) { this.scheduledInstallModifiers.push(modifier); this.scheduledInstallManagers.push(manager); }; _proto37.scheduleUpdateModifier = function scheduleUpdateModifier(modifier, manager) { this.scheduledUpdateModifiers.push(modifier); this.scheduledUpdateModifierManagers.push(manager); }; _proto37.didDestroy = function didDestroy(d) { this.destructors.push(d); }; _proto37.commit = function commit() { var createdComponents = this.createdComponents, createdManagers = this.createdManagers; for (var i = 0; i < createdComponents.length; i++) { var component = createdComponents[i]; var manager = createdManagers[i]; manager.didCreate(component); } var updatedComponents = this.updatedComponents, updatedManagers = this.updatedManagers; for (var _i4 = 0; _i4 < updatedComponents.length; _i4++) { var _component = updatedComponents[_i4]; var _manager2 = updatedManagers[_i4]; _manager2.didUpdate(_component); } var destructors = this.destructors; for (var _i5 = 0; _i5 < destructors.length; _i5++) { destructors[_i5].destroy(); } var scheduledInstallManagers = this.scheduledInstallManagers, scheduledInstallModifiers = this.scheduledInstallModifiers; for (var _i6 = 0; _i6 < scheduledInstallManagers.length; _i6++) { var modifier = scheduledInstallModifiers[_i6]; var _manager3 = scheduledInstallManagers[_i6]; _manager3.install(modifier); } var scheduledUpdateModifierManagers = this.scheduledUpdateModifierManagers, scheduledUpdateModifiers = this.scheduledUpdateModifiers; for (var _i7 = 0; _i7 < scheduledUpdateModifierManagers.length; _i7++) { var _modifier = scheduledUpdateModifiers[_i7]; var _manager4 = scheduledUpdateModifierManagers[_i7]; _manager4.update(_modifier); } }; return Transaction; }(); var Environment = /*#__PURE__*/ function () { function Environment(_ref56) { var appendOperations = _ref56.appendOperations, updateOperations = _ref56.updateOperations; this._transaction = null; this.appendOperations = appendOperations; this.updateOperations = updateOperations; } var _proto38 = Environment.prototype; _proto38.toConditionalReference = function toConditionalReference(reference) { return new ConditionalReference(reference); }; _proto38.getAppendOperations = function getAppendOperations() { return this.appendOperations; }; _proto38.getDOM = function getDOM() { return this.updateOperations; }; _proto38.begin = function begin() { this._transaction = new Transaction(); }; _proto38.didCreate = function didCreate(component, manager) { this.transaction.didCreate(component, manager); }; _proto38.didUpdate = function didUpdate(component, manager) { this.transaction.didUpdate(component, manager); }; _proto38.scheduleInstallModifier = function scheduleInstallModifier(modifier, manager) { this.transaction.scheduleInstallModifier(modifier, manager); }; _proto38.scheduleUpdateModifier = function scheduleUpdateModifier(modifier, manager) { this.transaction.scheduleUpdateModifier(modifier, manager); }; _proto38.didDestroy = function didDestroy(d) { this.transaction.didDestroy(d); }; _proto38.commit = function commit() { var transaction = this.transaction; this._transaction = null; transaction.commit(); }; _proto38.attributeFor = function attributeFor(element, attr, _isTrusting, namespace) { if (namespace === void 0) { namespace = null; } return dynamicAttribute(element, attr, namespace); }; (0, _emberBabel.createClass)(Environment, [{ key: "transaction", get: function get() { return this._transaction; } }]); return Environment; }(); _exports.Environment = Environment; var DefaultEnvironment = /*#__PURE__*/ function (_Environment) { (0, _emberBabel.inheritsLoose)(DefaultEnvironment, _Environment); function DefaultEnvironment(options) { if (!options) { var _document = window.document; var appendOperations = new DOMTreeConstruction(_document); var updateOperations = new DOMChanges(_document); options = { appendOperations: appendOperations, updateOperations: updateOperations }; } return _Environment.call(this, options) || this; } return DefaultEnvironment; }(Environment); _exports.DefaultEnvironment = DefaultEnvironment; var LowLevelVM = /*#__PURE__*/ function () { function LowLevelVM(stack, heap, program, externs, pc, ra) { if (pc === void 0) { pc = -1; } if (ra === void 0) { ra = -1; } this.stack = stack; this.heap = heap; this.program = program; this.externs = externs; this.pc = pc; this.ra = ra; this.currentOpSize = 0; } // Start a new frame and save $ra and $fp on the stack var _proto39 = LowLevelVM.prototype; _proto39.pushFrame = function pushFrame() { this.stack.push(this.ra); this.stack.push(this.stack.fp); this.stack.fp = this.stack.sp - 1; } // Restore $ra, $sp and $fp ; _proto39.popFrame = function popFrame() { this.stack.sp = this.stack.fp - 1; this.ra = this.stack.get(0); this.stack.fp = this.stack.get(1); }; _proto39.pushSmallFrame = function pushSmallFrame() { this.stack.push(this.ra); }; _proto39.popSmallFrame = function popSmallFrame() { this.ra = this.stack.popSmi(); } // Jump to an address in `program` ; _proto39.goto = function goto(offset) { var addr = this.pc + offset - this.currentOpSize; this.pc = addr; } // Save $pc into $ra, then jump to a new address in `program` (jal in MIPS) ; _proto39.call = function call(handle) { this.ra = this.pc; this.pc = this.heap.getaddr(handle); } // Put a specific `program` address in $ra ; _proto39.returnTo = function returnTo(offset) { var addr = this.pc + offset - this.currentOpSize; this.ra = addr; } // Return to the `program` address stored in $ra ; _proto39.return = function _return() { this.pc = this.ra; }; _proto39.nextStatement = function nextStatement() { var pc = this.pc, program = this.program; if (pc === -1) { return null; } // We have to save off the current operations size so that // when we do a jump we can calculate the correct offset // to where we are going. We can't simply ask for the size // in a jump because we have have already incremented the // program counter to the next instruction prior to executing. var _this$program$opcode = this.program.opcode(pc), size = _this$program$opcode.size; var operationSize = this.currentOpSize = size; this.pc += operationSize; return program.opcode(pc); }; _proto39.evaluateOuter = function evaluateOuter(opcode, vm) { { this.evaluateInner(opcode, vm); } }; _proto39.evaluateInner = function evaluateInner(opcode, vm) { if (opcode.isMachine) { this.evaluateMachine(opcode); } else { this.evaluateSyscall(opcode, vm); } }; _proto39.evaluateMachine = function evaluateMachine(opcode) { switch (opcode.type) { case 57 /* PushFrame */ : return this.pushFrame(); case 58 /* PopFrame */ : return this.popFrame(); case 59 /* PushSmallFrame */ : return this.pushSmallFrame(); case 60 /* PopSmallFrame */ : return this.popSmallFrame(); case 50 /* InvokeStatic */ : return this.call(opcode.op1); case 49 /* InvokeVirtual */ : return this.call(this.stack.popSmi()); case 52 /* Jump */ : return this.goto(opcode.op1); case 24 /* Return */ : return this.return(); case 25 /* ReturnTo */ : return this.returnTo(opcode.op1); } }; _proto39.evaluateSyscall = function evaluateSyscall(opcode, vm) { APPEND_OPCODES.evaluate(vm, opcode, opcode.type); }; return LowLevelVM; }(); var First = /*#__PURE__*/ function () { function First(node) { this.node = node; } var _proto40 = First.prototype; _proto40.firstNode = function firstNode() { return this.node; }; return First; }(); var Last = /*#__PURE__*/ function () { function Last(node) { this.node = node; } var _proto41 = Last.prototype; _proto41.lastNode = function lastNode() { return this.node; }; return Last; }(); var NewElementBuilder = /*#__PURE__*/ function () { function NewElementBuilder(env, parentNode, nextSibling) { this.constructing = null; this.operations = null; this.cursorStack = new _util.Stack(); this.modifierStack = new _util.Stack(); this.blockStack = new _util.Stack(); this.pushElement(parentNode, nextSibling); this.env = env; this.dom = env.getAppendOperations(); this.updateOperations = env.getDOM(); } NewElementBuilder.forInitialRender = function forInitialRender(env, cursor) { var builder = new this(env, cursor.element, cursor.nextSibling); builder.pushSimpleBlock(); return builder; }; NewElementBuilder.resume = function resume(env, tracker, nextSibling) { var parentNode = tracker.parentElement(); var stack = new this(env, parentNode, nextSibling); stack.pushSimpleBlock(); stack.pushBlockTracker(tracker); return stack; }; var _proto42 = NewElementBuilder.prototype; _proto42.expectConstructing = function expectConstructing(method) { return this.constructing; }; _proto42.block = function block() { return this.blockStack.current; }; _proto42.popElement = function popElement() { this.cursorStack.pop(); this.cursorStack.current; }; _proto42.pushSimpleBlock = function pushSimpleBlock() { return this.pushBlockTracker(new SimpleBlockTracker(this.element)); }; _proto42.pushUpdatableBlock = function pushUpdatableBlock() { return this.pushBlockTracker(new UpdatableBlockTracker(this.element)); }; _proto42.pushBlockList = function pushBlockList(list) { return this.pushBlockTracker(new BlockListTracker(this.element, list)); }; _proto42.pushBlockTracker = function pushBlockTracker(tracker, isRemote) { if (isRemote === void 0) { isRemote = false; } var current = this.blockStack.current; if (current !== null) { current.newDestroyable(tracker); if (!isRemote) { current.didAppendBounds(tracker); } } this.__openBlock(); this.blockStack.push(tracker); return tracker; }; _proto42.popBlock = function popBlock() { this.block().finalize(this); this.__closeBlock(); return this.blockStack.pop(); }; _proto42.__openBlock = function __openBlock() {}; _proto42.__closeBlock = function __closeBlock() {} // todo return seems unused ; _proto42.openElement = function openElement(tag) { var element = this.__openElement(tag); this.constructing = element; return element; }; _proto42.__openElement = function __openElement(tag) { return this.dom.createElement(tag, this.element); }; _proto42.flushElement = function flushElement(modifiers) { var parent = this.element; var element = this.constructing; this.__flushElement(parent, element); this.constructing = null; this.operations = null; this.pushModifiers(modifiers); this.pushElement(element, null); this.didOpenElement(element); }; _proto42.__flushElement = function __flushElement(parent, constructing) { this.dom.insertBefore(parent, constructing, this.nextSibling); }; _proto42.closeElement = function closeElement() { this.willCloseElement(); this.popElement(); return this.popModifiers(); }; _proto42.pushRemoteElement = function pushRemoteElement(element, guid, nextSibling) { if (nextSibling === void 0) { nextSibling = null; } this.__pushRemoteElement(element, guid, nextSibling); }; _proto42.__pushRemoteElement = function __pushRemoteElement(element, _guid, nextSibling) { this.pushElement(element, nextSibling); var tracker = new RemoteBlockTracker(element); this.pushBlockTracker(tracker, true); }; _proto42.popRemoteElement = function popRemoteElement() { this.popBlock(); this.popElement(); }; _proto42.pushElement = function pushElement(element, nextSibling) { this.cursorStack.push(new Cursor(element, nextSibling)); }; _proto42.pushModifiers = function pushModifiers(modifiers) { this.modifierStack.push(modifiers); }; _proto42.popModifiers = function popModifiers() { return this.modifierStack.pop(); }; _proto42.didAddDestroyable = function didAddDestroyable(d) { this.block().newDestroyable(d); }; _proto42.didAppendBounds = function didAppendBounds(bounds) { this.block().didAppendBounds(bounds); return bounds; }; _proto42.didAppendNode = function didAppendNode(node) { this.block().didAppendNode(node); return node; }; _proto42.didOpenElement = function didOpenElement(element) { this.block().openElement(element); return element; }; _proto42.willCloseElement = function willCloseElement() { this.block().closeElement(); }; _proto42.appendText = function appendText(string) { return this.didAppendNode(this.__appendText(string)); }; _proto42.__appendText = function __appendText(text) { var dom = this.dom, element = this.element, nextSibling = this.nextSibling; var node = dom.createTextNode(text); dom.insertBefore(element, node, nextSibling); return node; }; _proto42.__appendNode = function __appendNode(node) { this.dom.insertBefore(this.element, node, this.nextSibling); return node; }; _proto42.__appendFragment = function __appendFragment(fragment) { var first = fragment.firstChild; if (first) { var ret = new ConcreteBounds(this.element, first, fragment.lastChild); this.dom.insertBefore(this.element, fragment, this.nextSibling); return ret; } else { return new SingleNodeBounds(this.element, this.__appendComment('')); } }; _proto42.__appendHTML = function __appendHTML(html) { return this.dom.insertHTMLBefore(this.element, this.nextSibling, html); }; _proto42.appendDynamicHTML = function appendDynamicHTML(value$$1) { var bounds = this.trustedContent(value$$1); this.didAppendBounds(bounds); }; _proto42.appendDynamicText = function appendDynamicText(value$$1) { var node = this.untrustedContent(value$$1); this.didAppendNode(node); return node; }; _proto42.appendDynamicFragment = function appendDynamicFragment(value$$1) { var bounds = this.__appendFragment(value$$1); this.didAppendBounds(bounds); }; _proto42.appendDynamicNode = function appendDynamicNode(value$$1) { var node = this.__appendNode(value$$1); var bounds = new SingleNodeBounds(this.element, node); this.didAppendBounds(bounds); }; _proto42.trustedContent = function trustedContent(value$$1) { return this.__appendHTML(value$$1); }; _proto42.untrustedContent = function untrustedContent(value$$1) { return this.__appendText(value$$1); }; _proto42.appendComment = function appendComment(string) { return this.didAppendNode(this.__appendComment(string)); }; _proto42.__appendComment = function __appendComment(string) { var dom = this.dom, element = this.element, nextSibling = this.nextSibling; var node = dom.createComment(string); dom.insertBefore(element, node, nextSibling); return node; }; _proto42.__setAttribute = function __setAttribute(name, value$$1, namespace) { this.dom.setAttribute(this.constructing, name, value$$1, namespace); }; _proto42.__setProperty = function __setProperty(name, value$$1) { this.constructing[name] = value$$1; }; _proto42.setStaticAttribute = function setStaticAttribute(name, value$$1, namespace) { this.__setAttribute(name, value$$1, namespace); }; _proto42.setDynamicAttribute = function setDynamicAttribute(name, value$$1, trusting, namespace) { var element = this.constructing; var attribute = this.env.attributeFor(element, name, trusting, namespace); attribute.set(this, value$$1, this.env); return attribute; }; (0, _emberBabel.createClass)(NewElementBuilder, [{ key: "element", get: function get() { return this.cursorStack.current.element; } }, { key: "nextSibling", get: function get() { return this.cursorStack.current.nextSibling; } }]); return NewElementBuilder; }(); _exports.NewElementBuilder = NewElementBuilder; var SimpleBlockTracker = /*#__PURE__*/ function () { function SimpleBlockTracker(parent) { this.parent = parent; this.first = null; this.last = null; this.destroyables = null; this.nesting = 0; } var _proto43 = SimpleBlockTracker.prototype; _proto43.destroy = function destroy() { var destroyables = this.destroyables; if (destroyables && destroyables.length) { for (var i = 0; i < destroyables.length; i++) { destroyables[i].destroy(); } } }; _proto43.parentElement = function parentElement() { return this.parent; }; _proto43.firstNode = function firstNode() { var first = this.first; return first.firstNode(); }; _proto43.lastNode = function lastNode() { var last = this.last; return last.lastNode(); }; _proto43.openElement = function openElement(element) { this.didAppendNode(element); this.nesting++; }; _proto43.closeElement = function closeElement() { this.nesting--; }; _proto43.didAppendNode = function didAppendNode(node) { if (this.nesting !== 0) return; if (!this.first) { this.first = new First(node); } this.last = new Last(node); }; _proto43.didAppendBounds = function didAppendBounds(bounds) { if (this.nesting !== 0) return; if (!this.first) { this.first = bounds; } this.last = bounds; }; _proto43.newDestroyable = function newDestroyable(d) { this.destroyables = this.destroyables || []; this.destroyables.push(d); }; _proto43.finalize = function finalize(stack) { if (this.first === null) { stack.appendComment(''); } }; return SimpleBlockTracker; }(); var RemoteBlockTracker = /*#__PURE__*/ function (_SimpleBlockTracker) { (0, _emberBabel.inheritsLoose)(RemoteBlockTracker, _SimpleBlockTracker); function RemoteBlockTracker() { return _SimpleBlockTracker.apply(this, arguments) || this; } var _proto44 = RemoteBlockTracker.prototype; _proto44.destroy = function destroy() { _SimpleBlockTracker.prototype.destroy.call(this); clear(this); }; return RemoteBlockTracker; }(SimpleBlockTracker); var UpdatableBlockTracker = /*#__PURE__*/ function (_SimpleBlockTracker2) { (0, _emberBabel.inheritsLoose)(UpdatableBlockTracker, _SimpleBlockTracker2); function UpdatableBlockTracker() { return _SimpleBlockTracker2.apply(this, arguments) || this; } var _proto45 = UpdatableBlockTracker.prototype; _proto45.reset = function reset(env) { var destroyables = this.destroyables; if (destroyables && destroyables.length) { for (var i = 0; i < destroyables.length; i++) { env.didDestroy(destroyables[i]); } } var nextSibling = clear(this); this.first = null; this.last = null; this.destroyables = null; this.nesting = 0; return nextSibling; }; return UpdatableBlockTracker; }(SimpleBlockTracker); var BlockListTracker = /*#__PURE__*/ function () { function BlockListTracker(parent, boundList) { this.parent = parent; this.boundList = boundList; this.parent = parent; this.boundList = boundList; } var _proto46 = BlockListTracker.prototype; _proto46.destroy = function destroy() { this.boundList.forEachNode(function (node) { return node.destroy(); }); }; _proto46.parentElement = function parentElement() { return this.parent; }; _proto46.firstNode = function firstNode() { var head = this.boundList.head(); return head.firstNode(); }; _proto46.lastNode = function lastNode() { var tail = this.boundList.tail(); return tail.lastNode(); }; _proto46.openElement = function openElement(_element) {}; _proto46.closeElement = function closeElement() {}; _proto46.didAppendNode = function didAppendNode(_node) {}; _proto46.didAppendBounds = function didAppendBounds(_bounds) {}; _proto46.newDestroyable = function newDestroyable(_d) {}; _proto46.finalize = function finalize(_stack) {}; return BlockListTracker; }(); function clientBuilder(env, cursor) { return NewElementBuilder.forInitialRender(env, cursor); } var MAX_SMI = 0xfffffff; var InnerStack = /*#__PURE__*/ function () { function InnerStack(inner, js) { if (inner === void 0) { inner = new _lowLevel.Stack(); } if (js === void 0) { js = []; } this.inner = inner; this.js = js; } var _proto47 = InnerStack.prototype; _proto47.slice = function slice(start, end) { var inner; if (typeof start === 'number' && typeof end === 'number') { inner = this.inner.slice(start, end); } else if (typeof start === 'number' && end === undefined) { inner = this.inner.sliceFrom(start); } else { inner = this.inner.clone(); } return new InnerStack(inner, this.js.slice(start, end)); }; _proto47.sliceInner = function sliceInner(start, end) { var out = []; for (var i = start; i < end; i++) { out.push(this.get(i)); } return out; }; _proto47.copy = function copy(from, to) { this.inner.copy(from, to); }; _proto47.write = function write(pos, value$$1) { if (isImmediate(value$$1)) { this.inner.writeRaw(pos, encodeImmediate(value$$1)); } else { var idx = this.js.length; this.js.push(value$$1); this.inner.writeRaw(pos, ~idx); } }; _proto47.writeRaw = function writeRaw(pos, value$$1) { this.inner.writeRaw(pos, value$$1); }; _proto47.get = function get(pos) { var value$$1 = this.inner.getRaw(pos); if (value$$1 < 0) { return this.js[~value$$1]; } else { return decodeImmediate(value$$1); } }; _proto47.reset = function reset() { this.inner.reset(); this.js.length = 0; }; (0, _emberBabel.createClass)(InnerStack, [{ key: "length", get: function get() { return this.inner.len(); } }]); return InnerStack; }(); var EvaluationStack = /*#__PURE__*/ function () { function EvaluationStack(stack, fp, sp) { this.stack = stack; this.fp = fp; this.sp = sp; } EvaluationStack.empty = function empty() { return new this(new InnerStack(), 0, -1); }; EvaluationStack.restore = function restore(snapshot) { var stack = new InnerStack(); for (var i = 0; i < snapshot.length; i++) { stack.write(i, snapshot[i]); } return new this(stack, 0, snapshot.length - 1); }; var _proto48 = EvaluationStack.prototype; _proto48.push = function push(value$$1) { this.stack.write(++this.sp, value$$1); }; _proto48.pushEncodedImmediate = function pushEncodedImmediate(value$$1) { this.stack.writeRaw(++this.sp, value$$1); }; _proto48.pushNull = function pushNull() { this.stack.write(++this.sp, null); }; _proto48.dup = function dup(position) { if (position === void 0) { position = this.sp; } this.stack.copy(position, ++this.sp); }; _proto48.copy = function copy(from, to) { this.stack.copy(from, to); }; _proto48.pop = function pop(n) { if (n === void 0) { n = 1; } var top = this.stack.get(this.sp); this.sp -= n; return top; }; _proto48.popSmi = function popSmi() { return this.stack.get(this.sp--); }; _proto48.peek = function peek(offset) { if (offset === void 0) { offset = 0; } return this.stack.get(this.sp - offset); }; _proto48.get = function get(offset, base) { if (base === void 0) { base = this.fp; } return this.stack.get(base + offset); }; _proto48.set = function set(value$$1, offset, base) { if (base === void 0) { base = this.fp; } this.stack.write(base + offset, value$$1); }; _proto48.slice = function slice(start, end) { return this.stack.slice(start, end); }; _proto48.sliceArray = function sliceArray(start, end) { return this.stack.sliceInner(start, end); }; _proto48.capture = function capture(items) { var end = this.sp + 1; var start = end - items; return this.stack.sliceInner(start, end); }; _proto48.reset = function reset() { this.stack.reset(); }; _proto48.toArray = function toArray() { return this.stack.sliceInner(this.fp, this.sp + 1); }; return EvaluationStack; }(); function isImmediate(value$$1) { var type = typeof value$$1; if (value$$1 === null || value$$1 === undefined) return true; switch (type) { case 'boolean': case 'undefined': return true; case 'number': // not an integer if (value$$1 % 1 !== 0) return false; var abs = Math.abs(value$$1); if (abs > MAX_SMI) return false; return true; default: return false; } } function encodeSmi(primitive) { if (primitive < 0) { var abs = Math.abs(primitive); if (abs > MAX_SMI) throw new Error('not smi'); return Math.abs(primitive) << 3 | 4 /* NEGATIVE */ ; } else { if (primitive > MAX_SMI) throw new Error('not smi'); return primitive << 3 | 0 /* NUMBER */ ; } } function encodeImmediate(primitive) { switch (typeof primitive) { case 'number': return encodeSmi(primitive); case 'boolean': return primitive ? 11 /* True */ : 3 /* False */ ; case 'object': // assume null return 19 /* Null */ ; case 'undefined': return 27 /* Undef */ ; default: throw (0, _util.unreachable)(); } } function decodeSmi(smi) { switch (smi & 7) { case 0 /* NUMBER */ : return smi >> 3; case 4 /* NEGATIVE */ : return -(smi >> 3); default: throw (0, _util.unreachable)(); } } function decodeImmediate(immediate) { switch (immediate) { case 3 /* False */ : return false; case 11 /* True */ : return true; case 19 /* Null */ : return null; case 27 /* Undef */ : return undefined; default: return decodeSmi(immediate); } } var UpdatingVM = /*#__PURE__*/ function () { function UpdatingVM(env, program, _ref57) { var _ref57$alwaysRevalida = _ref57.alwaysRevalidate, alwaysRevalidate = _ref57$alwaysRevalida === void 0 ? false : _ref57$alwaysRevalida; this.frameStack = new _util.Stack(); this.env = env; this.constants = program.constants; this.dom = env.getDOM(); this.alwaysRevalidate = alwaysRevalidate; } var _proto49 = UpdatingVM.prototype; _proto49.execute = function execute(opcodes, handler) { var frameStack = this.frameStack; this.try(opcodes, handler); while (true) { if (frameStack.isEmpty()) break; var opcode = this.frame.nextStatement(); if (opcode === null) { this.frameStack.pop(); continue; } opcode.evaluate(this); } }; _proto49.goto = function goto(op) { this.frame.goto(op); }; _proto49.try = function _try(ops, handler) { this.frameStack.push(new UpdatingVMFrame(ops, handler)); }; _proto49.throw = function _throw() { this.frame.handleException(); this.frameStack.pop(); }; (0, _emberBabel.createClass)(UpdatingVM, [{ key: "frame", get: function get() { return this.frameStack.current; } }]); return UpdatingVM; }(); _exports.UpdatingVM = UpdatingVM; var BlockOpcode = /*#__PURE__*/ function (_UpdatingOpcode9) { (0, _emberBabel.inheritsLoose)(BlockOpcode, _UpdatingOpcode9); function BlockOpcode(start, state, runtime, bounds, children) { var _this15; _this15 = _UpdatingOpcode9.call(this) || this; _this15.start = start; _this15.state = state; _this15.runtime = runtime; _this15.type = 'block'; _this15.next = null; _this15.prev = null; _this15.children = children; _this15.bounds = bounds; return _this15; } var _proto50 = BlockOpcode.prototype; _proto50.parentElement = function parentElement() { return this.bounds.parentElement(); }; _proto50.firstNode = function firstNode() { return this.bounds.firstNode(); }; _proto50.lastNode = function lastNode() { return this.bounds.lastNode(); }; _proto50.evaluate = function evaluate(vm) { vm.try(this.children, null); }; _proto50.destroy = function destroy() { this.bounds.destroy(); }; _proto50.didDestroy = function didDestroy() { this.runtime.env.didDestroy(this.bounds); }; return BlockOpcode; }(UpdatingOpcode); var TryOpcode = /*#__PURE__*/ function (_BlockOpcode) { (0, _emberBabel.inheritsLoose)(TryOpcode, _BlockOpcode); function TryOpcode(start, state, runtime, bounds, children) { var _this16; _this16 = _BlockOpcode.call(this, start, state, runtime, bounds, children) || this; _this16.type = 'try'; _this16.tag = _this16._tag = (0, _reference2.createUpdatableTag)(); return _this16; } var _proto51 = TryOpcode.prototype; _proto51.didInitializeChildren = function didInitializeChildren() { (0, _reference2.update)(this._tag, (0, _reference2.combineSlice)(this.children)); }; _proto51.evaluate = function evaluate(vm) { vm.try(this.children, this); }; _proto51.handleException = function handleException() { var _this17 = this; var state = this.state, bounds = this.bounds, children = this.children, start = this.start, prev = this.prev, next = this.next, runtime = this.runtime; children.clear(); var elementStack = NewElementBuilder.resume(runtime.env, bounds, bounds.reset(runtime.env)); var vm = VM.resume(state, runtime, elementStack); var updating = new _util.LinkedList(); vm.execute(start, function (vm) { vm.stack = EvaluationStack.restore(state.stack); vm.updatingOpcodeStack.push(updating); vm.updateWith(_this17); vm.updatingOpcodeStack.push(children); }); this.prev = prev; this.next = next; }; return TryOpcode; }(BlockOpcode); var ListRevalidationDelegate = /*#__PURE__*/ function () { function ListRevalidationDelegate(opcode, marker) { this.opcode = opcode; this.marker = marker; this.didInsert = false; this.didDelete = false; this.map = opcode.map; this.updating = opcode['children']; } var _proto52 = ListRevalidationDelegate.prototype; _proto52.insert = function insert(key, item, memo, before) { var map = this.map, opcode = this.opcode, updating = this.updating; var nextSibling = null; var reference = null; if (typeof before === 'string') { reference = map[before]; nextSibling = reference['bounds'].firstNode(); } else { nextSibling = this.marker; } var vm = opcode.vmForInsertion(nextSibling); var tryOpcode = null; var start = opcode.start; vm.execute(start, function (vm) { map[key] = tryOpcode = vm.iterate(memo, item); vm.updatingOpcodeStack.push(new _util.LinkedList()); vm.updateWith(tryOpcode); vm.updatingOpcodeStack.push(tryOpcode.children); }); updating.insertBefore(tryOpcode, reference); this.didInsert = true; }; _proto52.retain = function retain(_key, _item, _memo) {}; _proto52.move = function move(key, _item, _memo, before) { var map = this.map, updating = this.updating; var entry = map[key]; var reference = map[before] || null; if (typeof before === 'string') { _move(entry, reference.firstNode()); } else { _move(entry, this.marker); } updating.remove(entry); updating.insertBefore(entry, reference); }; _proto52.delete = function _delete(key) { var map = this.map; var opcode = map[key]; opcode.didDestroy(); clear(opcode); this.updating.remove(opcode); delete map[key]; this.didDelete = true; }; _proto52.done = function done() { this.opcode.didInitializeChildren(this.didInsert || this.didDelete); }; return ListRevalidationDelegate; }(); var ListBlockOpcode = /*#__PURE__*/ function (_BlockOpcode2) { (0, _emberBabel.inheritsLoose)(ListBlockOpcode, _BlockOpcode2); function ListBlockOpcode(start, state, runtime, bounds, children, artifacts) { var _this18; _this18 = _BlockOpcode2.call(this, start, state, runtime, bounds, children) || this; _this18.type = 'list-block'; _this18.map = (0, _util.dict)(); _this18.lastIterated = _reference2.INITIAL; _this18.artifacts = artifacts; var _tag = _this18._tag = (0, _reference2.createUpdatableTag)(); _this18.tag = (0, _reference2.combine)([artifacts.tag, _tag]); return _this18; } var _proto53 = ListBlockOpcode.prototype; _proto53.didInitializeChildren = function didInitializeChildren(listDidChange) { if (listDidChange === void 0) { listDidChange = true; } this.lastIterated = (0, _reference2.value)(this.artifacts.tag); if (listDidChange) { (0, _reference2.update)(this._tag, (0, _reference2.combineSlice)(this.children)); } }; _proto53.evaluate = function evaluate(vm) { var artifacts = this.artifacts, lastIterated = this.lastIterated; if (!(0, _reference2.validate)(artifacts.tag, lastIterated)) { var bounds = this.bounds; var dom = vm.dom; var marker = dom.createComment(''); dom.insertAfter(bounds.parentElement(), marker, bounds.lastNode()); var target = new ListRevalidationDelegate(this, marker); var synchronizer = new _reference2.IteratorSynchronizer({ target: target, artifacts: artifacts }); synchronizer.sync(); this.parentElement().removeChild(marker); } // Run now-updated updating opcodes _BlockOpcode2.prototype.evaluate.call(this, vm); }; _proto53.vmForInsertion = function vmForInsertion(nextSibling) { var bounds = this.bounds, state = this.state, runtime = this.runtime; var elementStack = NewElementBuilder.forInitialRender(runtime.env, { element: bounds.parentElement(), nextSibling: nextSibling }); return VM.resume(state, runtime, elementStack); }; return ListBlockOpcode; }(BlockOpcode); var UpdatingVMFrame = /*#__PURE__*/ function () { function UpdatingVMFrame(ops, exceptionHandler) { this.ops = ops; this.exceptionHandler = exceptionHandler; this.current = ops.head(); } var _proto54 = UpdatingVMFrame.prototype; _proto54.goto = function goto(op) { this.current = op; }; _proto54.nextStatement = function nextStatement() { var current = this.current, ops = this.ops; if (current) this.current = ops.nextNode(current); return current; }; _proto54.handleException = function handleException() { if (this.exceptionHandler) { this.exceptionHandler.handleException(); } }; return UpdatingVMFrame; }(); var RenderResult = /*#__PURE__*/ function () { function RenderResult(env, program, updating, bounds) { this.env = env; this.program = program; this.updating = updating; this.bounds = bounds; } var _proto55 = RenderResult.prototype; _proto55.rerender = function rerender(_temp) { var _ref58 = _temp === void 0 ? { alwaysRevalidate: false } : _temp, _ref58$alwaysRevalida = _ref58.alwaysRevalidate, alwaysRevalidate = _ref58$alwaysRevalida === void 0 ? false : _ref58$alwaysRevalida; var env = this.env, program = this.program, updating = this.updating; var vm = new UpdatingVM(env, program, { alwaysRevalidate: alwaysRevalidate }); vm.execute(updating, this); }; _proto55.parentElement = function parentElement() { return this.bounds.parentElement(); }; _proto55.firstNode = function firstNode() { return this.bounds.firstNode(); }; _proto55.lastNode = function lastNode() { return this.bounds.lastNode(); }; _proto55.handleException = function handleException() { throw 'this should never happen'; }; _proto55.destroy = function destroy() { this.bounds.destroy(); clear(this.bounds); }; return RenderResult; }(); _exports.RenderResult = RenderResult; var Arguments = /*#__PURE__*/ function () { function Arguments() { this.stack = null; this.positional = new PositionalArguments(); this.named = new NamedArguments(); this.blocks = new BlockArguments(); } var _proto56 = Arguments.prototype; _proto56.empty = function empty(stack) { var base = stack.sp + 1; this.named.empty(stack, base); this.positional.empty(stack, base); this.blocks.empty(stack, base); return this; }; _proto56.setup = function setup(stack, names, blockNames, positionalCount, synthetic) { this.stack = stack; /* | ... | blocks | positional | named | | ... | b0 b1 | p0 p1 p2 p3 | n0 n1 | index | ... | 4/5/6 7/8/9 | 10 11 12 13 | 14 15 | ^ ^ ^ ^ bbase pbase nbase sp */ var named = this.named; var namedCount = names.length; var namedBase = stack.sp - namedCount + 1; named.setup(stack, namedBase, namedCount, names, synthetic); var positional = this.positional; var positionalBase = namedBase - positionalCount; positional.setup(stack, positionalBase, positionalCount); var blocks = this.blocks; var blocksCount = blockNames.length; var blocksBase = positionalBase - blocksCount * 3; blocks.setup(stack, blocksBase, blocksCount, blockNames); }; _proto56.at = function at(pos) { return this.positional.at(pos); }; _proto56.realloc = function realloc(offset) { var stack = this.stack; if (offset > 0 && stack !== null) { var positional = this.positional, named = this.named; var newBase = positional.base + offset; var length = positional.length + named.length; for (var i = length - 1; i >= 0; i--) { stack.copy(i + positional.base, i + newBase); } positional.base += offset; named.base += offset; stack.sp += offset; } }; _proto56.capture = function capture() { var positional = this.positional.length === 0 ? EMPTY_POSITIONAL : this.positional.capture(); var named = this.named.length === 0 ? EMPTY_NAMED : this.named.capture(); return new CapturedArguments(this.tag, positional, named, this.length); }; _proto56.clear = function clear() { var stack = this.stack, length = this.length; if (length > 0 && stack !== null) stack.pop(length); }; (0, _emberBabel.createClass)(Arguments, [{ key: "tag", get: function get() { return (0, _reference2.combineTagged)([this.positional, this.named]); } }, { key: "base", get: function get() { return this.blocks.base; } }, { key: "length", get: function get() { return this.positional.length + this.named.length + this.blocks.length * 3; } }]); return Arguments; }(); var CapturedArguments = /*#__PURE__*/ function () { function CapturedArguments(tag, positional, named, length) { this.tag = tag; this.positional = positional; this.named = named; this.length = length; } var _proto57 = CapturedArguments.prototype; _proto57.value = function value() { return { named: this.named.value(), positional: this.positional.value() }; }; return CapturedArguments; }(); var PositionalArguments = /*#__PURE__*/ function () { function PositionalArguments() { this.base = 0; this.length = 0; this.stack = null; this._tag = null; this._references = null; } var _proto58 = PositionalArguments.prototype; _proto58.empty = function empty(stack, base) { this.stack = stack; this.base = base; this.length = 0; this._tag = _reference2.CONSTANT_TAG; this._references = _util.EMPTY_ARRAY; }; _proto58.setup = function setup(stack, base, length) { this.stack = stack; this.base = base; this.length = length; if (length === 0) { this._tag = _reference2.CONSTANT_TAG; this._references = _util.EMPTY_ARRAY; } else { this._tag = null; this._references = null; } }; _proto58.at = function at(position) { var base = this.base, length = this.length, stack = this.stack; if (position < 0 || position >= length) { return UNDEFINED_REFERENCE; } return stack.get(position, base); }; _proto58.capture = function capture() { return new CapturedPositionalArguments(this.tag, this.references); }; _proto58.prepend = function prepend(other) { var additions = other.length; if (additions > 0) { var base = this.base, length = this.length, stack = this.stack; this.base = base = base - additions; this.length = length + additions; for (var i = 0; i < additions; i++) { stack.set(other.at(i), i, base); } this._tag = null; this._references = null; } }; (0, _emberBabel.createClass)(PositionalArguments, [{ key: "tag", get: function get() { var tag = this._tag; if (!tag) { tag = this._tag = (0, _reference2.combineTagged)(this.references); } return tag; } }, { key: "references", get: function get() { var references = this._references; if (!references) { var stack = this.stack, base = this.base, length = this.length; references = this._references = stack.sliceArray(base, base + length); } return references; } }]); return PositionalArguments; }(); var CapturedPositionalArguments = /*#__PURE__*/ function () { function CapturedPositionalArguments(tag, references, length) { if (length === void 0) { length = references.length; } this.tag = tag; this.references = references; this.length = length; } CapturedPositionalArguments.empty = function empty() { return new CapturedPositionalArguments(_reference2.CONSTANT_TAG, _util.EMPTY_ARRAY, 0); }; var _proto59 = CapturedPositionalArguments.prototype; _proto59.at = function at(position) { return this.references[position]; }; _proto59.value = function value() { return this.references.map(this.valueOf); }; _proto59.get = function get(name) { var references = this.references, length = this.length; if (name === 'length') { return PrimitiveReference.create(length); } else { var idx = parseInt(name, 10); if (idx < 0 || idx >= length) { return UNDEFINED_REFERENCE; } else { return references[idx]; } } }; _proto59.valueOf = function valueOf(reference) { return reference.value(); }; return CapturedPositionalArguments; }(); var NamedArguments = /*#__PURE__*/ function () { function NamedArguments() { this.base = 0; this.length = 0; this._references = null; this._names = _util.EMPTY_ARRAY; this._atNames = _util.EMPTY_ARRAY; } var _proto60 = NamedArguments.prototype; _proto60.empty = function empty(stack, base) { this.stack = stack; this.base = base; this.length = 0; this._references = _util.EMPTY_ARRAY; this._names = _util.EMPTY_ARRAY; this._atNames = _util.EMPTY_ARRAY; }; _proto60.setup = function setup(stack, base, length, names, synthetic) { this.stack = stack; this.base = base; this.length = length; if (length === 0) { this._references = _util.EMPTY_ARRAY; this._names = _util.EMPTY_ARRAY; this._atNames = _util.EMPTY_ARRAY; } else { this._references = null; if (synthetic) { this._names = names; this._atNames = null; } else { this._names = null; this._atNames = names; } } }; _proto60.has = function has(name) { return this.names.indexOf(name) !== -1; }; _proto60.get = function get(name, synthetic) { if (synthetic === void 0) { synthetic = true; } var base = this.base, stack = this.stack; var names = synthetic ? this.names : this.atNames; var idx = names.indexOf(name); if (idx === -1) { return UNDEFINED_REFERENCE; } return stack.get(idx, base); }; _proto60.capture = function capture() { return new CapturedNamedArguments(this.tag, this.names, this.references); }; _proto60.merge = function merge(other) { var extras = other.length; if (extras > 0) { var names = this.names, length = this.length, stack = this.stack; var extraNames = other.names; if (Object.isFrozen(names) && names.length === 0) { names = []; } for (var i = 0; i < extras; i++) { var name = extraNames[i]; var idx = names.indexOf(name); if (idx === -1) { length = names.push(name); stack.push(other.references[i]); } } this.length = length; this._references = null; this._names = names; this._atNames = null; } }; _proto60.toSyntheticName = function toSyntheticName(name) { return name.slice(1); }; _proto60.toAtName = function toAtName(name) { return "@" + name; }; (0, _emberBabel.createClass)(NamedArguments, [{ key: "tag", get: function get() { return (0, _reference2.combineTagged)(this.references); } }, { key: "names", get: function get() { var names = this._names; if (!names) { names = this._names = this._atNames.map(this.toSyntheticName); } return names; } }, { key: "atNames", get: function get() { var atNames = this._atNames; if (!atNames) { atNames = this._atNames = this._names.map(this.toAtName); } return atNames; } }, { key: "references", get: function get() { var references = this._references; if (!references) { var base = this.base, length = this.length, stack = this.stack; references = this._references = stack.sliceArray(base, base + length); } return references; } }]); return NamedArguments; }(); var CapturedNamedArguments = /*#__PURE__*/ function () { function CapturedNamedArguments(tag, names, references) { this.tag = tag; this.names = names; this.references = references; this.length = names.length; this._map = null; } var _proto61 = CapturedNamedArguments.prototype; _proto61.has = function has(name) { return this.names.indexOf(name) !== -1; }; _proto61.get = function get(name) { var names = this.names, references = this.references; var idx = names.indexOf(name); if (idx === -1) { return UNDEFINED_REFERENCE; } else { return references[idx]; } }; _proto61.value = function value() { var names = this.names, references = this.references; var out = (0, _util.dict)(); for (var i = 0; i < names.length; i++) { var name = names[i]; out[name] = references[i].value(); } return out; }; (0, _emberBabel.createClass)(CapturedNamedArguments, [{ key: "map", get: function get() { var map = this._map; if (!map) { var names = this.names, references = this.references; map = this._map = (0, _util.dict)(); for (var i = 0; i < names.length; i++) { var name = names[i]; map[name] = references[i]; } } return map; } }]); return CapturedNamedArguments; }(); var BlockArguments = /*#__PURE__*/ function () { function BlockArguments() { this.internalValues = null; this.internalTag = null; this.names = _util.EMPTY_ARRAY; this.length = 0; this.base = 0; } var _proto62 = BlockArguments.prototype; _proto62.empty = function empty(stack, base) { this.stack = stack; this.names = _util.EMPTY_ARRAY; this.base = base; this.length = 0; this.internalTag = _reference2.CONSTANT_TAG; this.internalValues = _util.EMPTY_ARRAY; }; _proto62.setup = function setup(stack, base, length, names) { this.stack = stack; this.names = names; this.base = base; this.length = length; if (length === 0) { this.internalTag = _reference2.CONSTANT_TAG; this.internalValues = _util.EMPTY_ARRAY; } else { this.internalTag = null; this.internalValues = null; } }; _proto62.has = function has(name) { return this.names.indexOf(name) !== -1; }; _proto62.get = function get(name) { var base = this.base, stack = this.stack, names = this.names; var idx = names.indexOf(name); if (names.indexOf(name) === -1) { return null; } var table = stack.get(idx * 3, base); var scope = stack.get(idx * 3 + 1, base); // FIXME(mmun): shouldn't need to cast this var handle = stack.get(idx * 3 + 2, base); return handle === null ? null : [handle, scope, table]; }; _proto62.capture = function capture() { return new CapturedBlockArguments(this.names, this.values); }; (0, _emberBabel.createClass)(BlockArguments, [{ key: "values", get: function get() { var values = this.internalValues; if (!values) { var base = this.base, length = this.length, stack = this.stack; values = this.internalValues = stack.sliceArray(base, base + length * 3); } return values; } }]); return BlockArguments; }(); var CapturedBlockArguments = /*#__PURE__*/ function () { function CapturedBlockArguments(names, values) { this.names = names; this.values = values; this.length = names.length; } var _proto63 = CapturedBlockArguments.prototype; _proto63.has = function has(name) { return this.names.indexOf(name) !== -1; }; _proto63.get = function get(name) { var idx = this.names.indexOf(name); if (idx === -1) return null; return [this.values[idx * 3 + 2], this.values[idx * 3 + 1], this.values[idx * 3]]; }; return CapturedBlockArguments; }(); var EMPTY_NAMED = new CapturedNamedArguments(_reference2.CONSTANT_TAG, _util.EMPTY_ARRAY, _util.EMPTY_ARRAY); var EMPTY_POSITIONAL = new CapturedPositionalArguments(_reference2.CONSTANT_TAG, _util.EMPTY_ARRAY); var EMPTY_ARGS = new CapturedArguments(_reference2.CONSTANT_TAG, EMPTY_POSITIONAL, EMPTY_NAMED, 0); _exports.EMPTY_ARGS = EMPTY_ARGS; var VM = /*#__PURE__*/ function () { function VM(runtime, scope, dynamicScope, elementStack) { var _this19 = this; this.runtime = runtime; this.elementStack = elementStack; this.dynamicScopeStack = new _util.Stack(); this.scopeStack = new _util.Stack(); this.updatingOpcodeStack = new _util.Stack(); this.cacheGroups = new _util.Stack(); this.listBlockStack = new _util.Stack(); this.s0 = null; this.s1 = null; this.t0 = null; this.t1 = null; this.v0 = null; this.heap = this.program.heap; this.constants = this.program.constants; this.elementStack = elementStack; this.scopeStack.push(scope); this.dynamicScopeStack.push(dynamicScope); this.args = new Arguments(); this.inner = new LowLevelVM(EvaluationStack.empty(), this.heap, runtime.program, { debugBefore: function debugBefore(opcode) { return APPEND_OPCODES.debugBefore(_this19, opcode, opcode.type); }, debugAfter: function debugAfter(opcode, state) { APPEND_OPCODES.debugAfter(_this19, opcode, opcode.type, state); } }); } var _proto64 = VM.prototype; // Fetch a value from a register onto the stack _proto64.fetch = function fetch(register) { this.stack.push(this[_vm2.Register[register]]); } // Load a value from the stack into a register ; _proto64.load = function load(register) { this[_vm2.Register[register]] = this.stack.pop(); } // Fetch a value from a register ; _proto64.fetchValue = function fetchValue(register) { return this[_vm2.Register[register]]; } // Load a value into a register ; _proto64.loadValue = function loadValue(register, value$$1) { this[_vm2.Register[register]] = value$$1; } /** * Migrated to Inner */ // Start a new frame and save $ra and $fp on the stack ; _proto64.pushFrame = function pushFrame() { this.inner.pushFrame(); } // Restore $ra, $sp and $fp ; _proto64.popFrame = function popFrame() { this.inner.popFrame(); } // Jump to an address in `program` ; _proto64.goto = function goto(offset) { this.inner.goto(offset); } // Save $pc into $ra, then jump to a new address in `program` (jal in MIPS) ; _proto64.call = function call(handle) { this.inner.call(handle); } // Put a specific `program` address in $ra ; _proto64.returnTo = function returnTo(offset) { this.inner.returnTo(offset); } // Return to the `program` address stored in $ra ; _proto64.return = function _return() { this.inner.return(); } /** * End of migrated. */ ; VM.initial = function initial(program, env, self, dynamicScope, elementStack, handle) { var scopeSize = program.heap.scopesizeof(handle); var scope = Scope.root(self, scopeSize); var vm = new VM({ program: program, env: env }, scope, dynamicScope, elementStack); vm.pc = vm.heap.getaddr(handle); vm.updatingOpcodeStack.push(new _util.LinkedList()); return vm; }; VM.empty = function empty(program, env, elementStack, handle) { var dynamicScope = { get: function get() { return UNDEFINED_REFERENCE; }, set: function set() { return UNDEFINED_REFERENCE; }, child: function child() { return dynamicScope; } }; var vm = new VM({ program: program, env: env }, Scope.root(UNDEFINED_REFERENCE, 0), dynamicScope, elementStack); vm.updatingOpcodeStack.push(new _util.LinkedList()); vm.pc = vm.heap.getaddr(handle); return vm; }; VM.resume = function resume(_ref59, runtime, stack) { var scope = _ref59.scope, dynamicScope = _ref59.dynamicScope; return new VM(runtime, scope, dynamicScope, stack); }; _proto64.capture = function capture(args) { return { dynamicScope: this.dynamicScope(), scope: this.scope(), stack: this.stack.capture(args) }; }; _proto64.beginCacheGroup = function beginCacheGroup() { this.cacheGroups.push(this.updating().tail()); }; _proto64.commitCacheGroup = function commitCacheGroup() { // JumpIfNotModified(END) // (head) // (....) // (tail) // DidModify // END: Noop var END = new LabelOpcode('END'); var opcodes = this.updating(); var marker = this.cacheGroups.pop(); var head = marker ? opcodes.nextNode(marker) : opcodes.head(); var tail = opcodes.tail(); var tag = (0, _reference2.combineSlice)(new _util.ListSlice(head, tail)); var guard = new JumpIfNotModifiedOpcode(tag, END); opcodes.insertBefore(guard, head); opcodes.append(new DidModifyOpcode(guard)); opcodes.append(END); }; _proto64.enter = function enter(args) { var updating = new _util.LinkedList(); var state = this.capture(args); var tracker = this.elements().pushUpdatableBlock(); var tryOpcode = new TryOpcode(this.heap.gethandle(this.pc), state, this.runtime, tracker, updating); this.didEnter(tryOpcode); }; _proto64.iterate = function iterate(memo, value$$1) { var stack = this.stack; stack.push(value$$1); stack.push(memo); var state = this.capture(2); var tracker = this.elements().pushUpdatableBlock(); // let ip = this.ip; // this.ip = end + 4; // this.frames.push(ip); return new TryOpcode(this.heap.gethandle(this.pc), state, this.runtime, tracker, new _util.LinkedList()); }; _proto64.enterItem = function enterItem(key, opcode) { this.listBlock().map[key] = opcode; this.didEnter(opcode); }; _proto64.enterList = function enterList(relativeStart) { var updating = new _util.LinkedList(); var state = this.capture(0); var tracker = this.elements().pushBlockList(updating); var artifacts = this.stack.peek().artifacts; var addr = this.pc + relativeStart - this.currentOpSize; var start = this.heap.gethandle(addr); var opcode = new ListBlockOpcode(start, state, this.runtime, tracker, updating, artifacts); this.listBlockStack.push(opcode); this.didEnter(opcode); }; _proto64.didEnter = function didEnter(opcode) { this.updateWith(opcode); this.updatingOpcodeStack.push(opcode.children); }; _proto64.exit = function exit() { this.elements().popBlock(); this.updatingOpcodeStack.pop(); var parent = this.updating().tail(); parent.didInitializeChildren(); }; _proto64.exitList = function exitList() { this.exit(); this.listBlockStack.pop(); }; _proto64.updateWith = function updateWith(opcode) { this.updating().append(opcode); }; _proto64.listBlock = function listBlock() { return this.listBlockStack.current; }; _proto64.updating = function updating() { return this.updatingOpcodeStack.current; }; _proto64.elements = function elements() { return this.elementStack; }; _proto64.scope = function scope() { return this.scopeStack.current; }; _proto64.dynamicScope = function dynamicScope() { return this.dynamicScopeStack.current; }; _proto64.pushChildScope = function pushChildScope() { this.scopeStack.push(this.scope().child()); }; _proto64.pushDynamicScope = function pushDynamicScope() { var child = this.dynamicScope().child(); this.dynamicScopeStack.push(child); return child; }; _proto64.pushRootScope = function pushRootScope(size, bindCaller) { var scope = Scope.sized(size); if (bindCaller) scope.bindCallerScope(this.scope()); this.scopeStack.push(scope); return scope; }; _proto64.pushScope = function pushScope(scope) { this.scopeStack.push(scope); }; _proto64.popScope = function popScope() { this.scopeStack.pop(); }; _proto64.popDynamicScope = function popDynamicScope() { this.dynamicScopeStack.pop(); }; _proto64.newDestroyable = function newDestroyable(d) { this.elements().didAddDestroyable(d); } /// SCOPE HELPERS ; _proto64.getSelf = function getSelf() { return this.scope().getSelf(); }; _proto64.referenceForSymbol = function referenceForSymbol(symbol) { return this.scope().getSymbol(symbol); } /// EXECUTION ; _proto64.execute = function execute(start, initialize) { this.pc = this.heap.getaddr(start); if (initialize) initialize(this); var result; while (true) { result = this.next(); if (result.done) break; } return result.value; }; _proto64.next = function next() { var env = this.env, program = this.program, updatingOpcodeStack = this.updatingOpcodeStack, elementStack = this.elementStack; var opcode = this.inner.nextStatement(); var result; if (opcode !== null) { this.inner.evaluateOuter(opcode, this); result = { done: false, value: null }; } else { // Unload the stack this.stack.reset(); result = { done: true, value: new RenderResult(env, program, updatingOpcodeStack.pop(), elementStack.popBlock()) }; } return result; }; _proto64.bindDynamicScope = function bindDynamicScope(names) { var scope = this.dynamicScope(); for (var i = names.length - 1; i >= 0; i--) { var name = this.constants.getString(names[i]); scope.set(name, this.stack.pop()); } }; (0, _emberBabel.createClass)(VM, [{ key: "stack", get: function get() { return this.inner.stack; }, set: function set(value$$1) { this.inner.stack = value$$1; } /* Registers */ }, { key: "currentOpSize", set: function set(value$$1) { this.inner.currentOpSize = value$$1; }, get: function get() { return this.inner.currentOpSize; } }, { key: "pc", get: function get() { return this.inner.pc; }, set: function set(value$$1) { this.inner.pc = value$$1; } }, { key: "ra", get: function get() { return this.inner.ra; }, set: function set(value$$1) { this.inner.ra = value$$1; } }, { key: "fp", get: function get() { return this.stack.fp; }, set: function set(fp) { this.stack.fp = fp; } }, { key: "sp", get: function get() { return this.stack.sp; }, set: function set(sp) { this.stack.sp = sp; } }, { key: "program", get: function get() { return this.runtime.program; } }, { key: "env", get: function get() { return this.runtime.env; } }]); return VM; }(); _exports.LowLevelVM = VM; var TemplateIteratorImpl = /*#__PURE__*/ function () { function TemplateIteratorImpl(vm) { this.vm = vm; } var _proto65 = TemplateIteratorImpl.prototype; _proto65.next = function next() { return this.vm.next(); }; return TemplateIteratorImpl; }(); function renderMain(program, env, self, dynamicScope, builder, handle) { var vm = VM.initial(program, env, self, dynamicScope, builder, handle); return new TemplateIteratorImpl(vm); } /** * Returns a TemplateIterator configured to render a root component. */ function renderComponent(program, env, builder, main, name, args) { if (args === void 0) { args = {}; } var vm = VM.empty(program, env, builder, main); var resolver = vm.constants.resolver; var definition = resolveComponent(resolver, name, null); var manager = definition.manager, state = definition.state; var capabilities = capabilityFlagsFrom(manager.getCapabilities(state)); var invocation; if (hasStaticLayoutCapability(capabilities, manager)) { invocation = manager.getLayout(state, resolver); } else { throw new Error('Cannot invoke components with dynamic layouts as a root component.'); } // Get a list of tuples of argument names and references, like // [['title', reference], ['name', reference]] var argList = Object.keys(args).map(function (key) { return [key, args[key]]; }); var blockNames = ['main', 'else', 'attrs']; // Prefix argument names with `@` symbol var argNames = argList.map(function (_ref60) { var name = _ref60[0]; return "@" + name; }); vm.pushFrame(); // Push blocks on to the stack, three stack values per block for (var i = 0; i < 3 * blockNames.length; i++) { vm.stack.push(null); } vm.stack.push(null); // For each argument, push its backing reference on to the stack argList.forEach(function (_ref61) { var reference = _ref61[1]; vm.stack.push(reference); }); // Configure VM based on blocks and args just pushed on to the stack. vm.args.setup(vm.stack, argNames, blockNames, 0, false); // Needed for the Op.Main opcode: arguments, component invocation object, and // component definition. vm.stack.push(vm.args); vm.stack.push(invocation); vm.stack.push(definition); return new TemplateIteratorImpl(vm); } var DynamicVarReference = /*#__PURE__*/ function () { function DynamicVarReference(scope, nameRef) { this.scope = scope; this.nameRef = nameRef; var varTag = this.varTag = (0, _reference2.createUpdatableTag)(); this.tag = (0, _reference2.combine)([nameRef.tag, varTag]); } var _proto66 = DynamicVarReference.prototype; _proto66.value = function value() { return this.getVar().value(); }; _proto66.get = function get(key) { return this.getVar().get(key); }; _proto66.getVar = function getVar() { var name = String(this.nameRef.value()); var ref = this.scope.get(name); (0, _reference2.update)(this.varTag, ref.tag); return ref; }; return DynamicVarReference; }(); function getDynamicVar(vm, args) { var scope = vm.dynamicScope(); var nameRef = args.positional.at(0); return new DynamicVarReference(scope, nameRef); } /** @internal */ var DEFAULT_CAPABILITIES = { dynamicLayout: true, dynamicTag: true, prepareArgs: true, createArgs: true, attributeHook: false, elementHook: false, dynamicScope: true, createCaller: false, updateHook: true, createInstance: true }; _exports.DEFAULT_CAPABILITIES = DEFAULT_CAPABILITIES; var MINIMAL_CAPABILITIES = { dynamicLayout: false, dynamicTag: false, prepareArgs: false, createArgs: false, attributeHook: false, elementHook: false, dynamicScope: false, createCaller: false, updateHook: false, createInstance: false }; _exports.MINIMAL_CAPABILITIES = MINIMAL_CAPABILITIES; var SERIALIZATION_FIRST_NODE_STRING = '%+b:0%'; _exports.SERIALIZATION_FIRST_NODE_STRING = SERIALIZATION_FIRST_NODE_STRING; function isSerializationFirstNode(node) { return node.nodeValue === SERIALIZATION_FIRST_NODE_STRING; } var RehydratingCursor = /*#__PURE__*/ function (_Cursor) { (0, _emberBabel.inheritsLoose)(RehydratingCursor, _Cursor); function RehydratingCursor(element, nextSibling, startingBlockDepth) { var _this20; _this20 = _Cursor.call(this, element, nextSibling) || this; _this20.startingBlockDepth = startingBlockDepth; _this20.candidate = null; _this20.injectedOmittedNode = false; _this20.openBlockDepth = startingBlockDepth - 1; return _this20; } return RehydratingCursor; }(Cursor); var RehydrateBuilder = /*#__PURE__*/ function (_NewElementBuilder) { (0, _emberBabel.inheritsLoose)(RehydrateBuilder, _NewElementBuilder); // private candidate: Option<Simple.Node> = null; function RehydrateBuilder(env, parentNode, nextSibling) { var _this21; _this21 = _NewElementBuilder.call(this, env, parentNode, nextSibling) || this; _this21.unmatchedAttributes = null; _this21.blockDepth = 0; if (nextSibling) throw new Error('Rehydration with nextSibling not supported'); var node = _this21.currentCursor.element.firstChild; while (node !== null) { if (isComment(node) && isSerializationFirstNode(node)) { break; } node = node.nextSibling; } _this21.candidate = node; return _this21; } var _proto67 = RehydrateBuilder.prototype; _proto67.pushElement = function pushElement(element, nextSibling) { var _this$blockDepth = this.blockDepth, blockDepth = _this$blockDepth === void 0 ? 0 : _this$blockDepth; var cursor = new RehydratingCursor(element, nextSibling, blockDepth); var currentCursor = this.currentCursor; if (currentCursor) { if (currentCursor.candidate) { /** * <div> <--------------- currentCursor.element * <!--%+b:1%--> * <div> <--------------- currentCursor.candidate -> cursor.element * <!--%+b:2%--> <- currentCursor.candidate.firstChild -> cursor.candidate * Foo * <!--%-b:2%--> * </div> * <!--%-b:1%--> <-- becomes currentCursor.candidate */ // where to rehydrate from if we are in rehydration mode cursor.candidate = element.firstChild; // where to continue when we pop currentCursor.candidate = element.nextSibling; } } this.cursorStack.push(cursor); }; _proto67.clearMismatch = function clearMismatch(candidate) { var current = candidate; var currentCursor = this.currentCursor; if (currentCursor !== null) { var openBlockDepth = currentCursor.openBlockDepth; if (openBlockDepth >= currentCursor.startingBlockDepth) { while (current && !(isComment(current) && getCloseBlockDepth(current) === openBlockDepth)) { current = this.remove(current); } } else { while (current !== null) { current = this.remove(current); } } // current cursor parentNode should be openCandidate if element // or openCandidate.parentNode if comment currentCursor.nextSibling = current; // disable rehydration until we popElement or closeBlock for openBlockDepth currentCursor.candidate = null; } }; _proto67.__openBlock = function __openBlock() { var currentCursor = this.currentCursor; if (currentCursor === null) return; var blockDepth = this.blockDepth; this.blockDepth++; var candidate = currentCursor.candidate; if (candidate === null) return; var tagName = currentCursor.element.tagName; if (isComment(candidate) && getOpenBlockDepth(candidate) === blockDepth) { currentCursor.candidate = this.remove(candidate); currentCursor.openBlockDepth = blockDepth; } else if (tagName !== 'TITLE' && tagName !== 'SCRIPT' && tagName !== 'STYLE') { this.clearMismatch(candidate); } }; _proto67.__closeBlock = function __closeBlock() { var currentCursor = this.currentCursor; if (currentCursor === null) return; // openBlock is the last rehydrated open block var openBlockDepth = currentCursor.openBlockDepth; // this currently is the expected next open block depth this.blockDepth--; var candidate = currentCursor.candidate; // rehydrating if (candidate !== null) { if (isComment(candidate) && getCloseBlockDepth(candidate) === openBlockDepth) { currentCursor.candidate = this.remove(candidate); currentCursor.openBlockDepth--; } else { this.clearMismatch(candidate); } // if the openBlockDepth matches the blockDepth we just closed to // then restore rehydration } if (currentCursor.openBlockDepth === this.blockDepth) { currentCursor.candidate = this.remove(currentCursor.nextSibling); currentCursor.openBlockDepth--; } }; _proto67.__appendNode = function __appendNode(node) { var candidate = this.candidate; // This code path is only used when inserting precisely one node. It needs more // comparison logic, but we can probably lean on the cases where this code path // is actually used. if (candidate) { return candidate; } else { return _NewElementBuilder.prototype.__appendNode.call(this, node); } }; _proto67.__appendHTML = function __appendHTML(html) { var candidateBounds = this.markerBounds(); if (candidateBounds) { var first = candidateBounds.firstNode(); var last = candidateBounds.lastNode(); var newBounds = new ConcreteBounds(this.element, first.nextSibling, last.previousSibling); var possibleEmptyMarker = this.remove(first); this.remove(last); if (possibleEmptyMarker !== null && isEmpty$1(possibleEmptyMarker)) { this.candidate = this.remove(possibleEmptyMarker); if (this.candidate !== null) { this.clearMismatch(this.candidate); } } return newBounds; } else { return _NewElementBuilder.prototype.__appendHTML.call(this, html); } }; _proto67.remove = function remove(node) { var element = node.parentNode; var next = node.nextSibling; element.removeChild(node); return next; }; _proto67.markerBounds = function markerBounds() { var _candidate = this.candidate; if (_candidate && isMarker(_candidate)) { var first = _candidate; var last = first.nextSibling; while (last && !isMarker(last)) { last = last.nextSibling; } return new ConcreteBounds(this.element, first, last); } else { return null; } }; _proto67.__appendText = function __appendText(string) { var candidate = this.candidate; if (candidate) { if (isTextNode(candidate)) { if (candidate.nodeValue !== string) { candidate.nodeValue = string; } this.candidate = candidate.nextSibling; return candidate; } else if (candidate && (isSeparator(candidate) || isEmpty$1(candidate))) { this.candidate = candidate.nextSibling; this.remove(candidate); return this.__appendText(string); } else if (isEmpty$1(candidate)) { var next = this.remove(candidate); this.candidate = next; var text = this.dom.createTextNode(string); this.dom.insertBefore(this.element, text, next); return text; } else { this.clearMismatch(candidate); return _NewElementBuilder.prototype.__appendText.call(this, string); } } else { return _NewElementBuilder.prototype.__appendText.call(this, string); } }; _proto67.__appendComment = function __appendComment(string) { var _candidate = this.candidate; if (_candidate && isComment(_candidate)) { if (_candidate.nodeValue !== string) { _candidate.nodeValue = string; } this.candidate = _candidate.nextSibling; return _candidate; } else if (_candidate) { this.clearMismatch(_candidate); } return _NewElementBuilder.prototype.__appendComment.call(this, string); }; _proto67.__openElement = function __openElement(tag) { var _candidate = this.candidate; if (_candidate && isElement(_candidate) && isSameNodeType(_candidate, tag)) { this.unmatchedAttributes = [].slice.call(_candidate.attributes); return _candidate; } else if (_candidate) { if (isElement(_candidate) && _candidate.tagName === 'TBODY') { this.pushElement(_candidate, null); this.currentCursor.injectedOmittedNode = true; return this.__openElement(tag); } this.clearMismatch(_candidate); } return _NewElementBuilder.prototype.__openElement.call(this, tag); }; _proto67.__setAttribute = function __setAttribute(name, value$$1, namespace) { var unmatched = this.unmatchedAttributes; if (unmatched) { var attr = findByName(unmatched, name); if (attr) { if (attr.value !== value$$1) { attr.value = value$$1; } unmatched.splice(unmatched.indexOf(attr), 1); return; } } return _NewElementBuilder.prototype.__setAttribute.call(this, name, value$$1, namespace); }; _proto67.__setProperty = function __setProperty(name, value$$1) { var unmatched = this.unmatchedAttributes; if (unmatched) { var attr = findByName(unmatched, name); if (attr) { if (attr.value !== value$$1) { attr.value = value$$1; } unmatched.splice(unmatched.indexOf(attr), 1); return; } } return _NewElementBuilder.prototype.__setProperty.call(this, name, value$$1); }; _proto67.__flushElement = function __flushElement(parent, constructing) { var unmatched = this.unmatchedAttributes; if (unmatched) { for (var i = 0; i < unmatched.length; i++) { this.constructing.removeAttribute(unmatched[i].name); } this.unmatchedAttributes = null; } else { _NewElementBuilder.prototype.__flushElement.call(this, parent, constructing); } }; _proto67.willCloseElement = function willCloseElement() { var candidate = this.candidate, currentCursor = this.currentCursor; if (candidate !== null) { this.clearMismatch(candidate); } if (currentCursor && currentCursor.injectedOmittedNode) { this.popElement(); } _NewElementBuilder.prototype.willCloseElement.call(this); }; _proto67.getMarker = function getMarker(element, guid) { var marker = element.querySelector("script[glmr=\"" + guid + "\"]"); if (marker) { return marker; } throw new Error('Cannot find serialized cursor for `in-element`'); }; _proto67.__pushRemoteElement = function __pushRemoteElement(element, cursorId, nextSibling) { if (nextSibling === void 0) { nextSibling = null; } var marker = this.getMarker(element, cursorId); if (marker.parentNode === element) { var currentCursor = this.currentCursor; var candidate = currentCursor.candidate; this.pushElement(element, nextSibling); currentCursor.candidate = candidate; this.candidate = this.remove(marker); var tracker = new RemoteBlockTracker(element); this.pushBlockTracker(tracker, true); } }; _proto67.didAppendBounds = function didAppendBounds(bounds) { _NewElementBuilder.prototype.didAppendBounds.call(this, bounds); if (this.candidate) { var last = bounds.lastNode(); this.candidate = last && last.nextSibling; } return bounds; }; (0, _emberBabel.createClass)(RehydrateBuilder, [{ key: "currentCursor", get: function get() { return this.cursorStack.current; } }, { key: "candidate", get: function get() { if (this.currentCursor) { return this.currentCursor.candidate; } return null; }, set: function set(node) { this.currentCursor.candidate = node; } }]); return RehydrateBuilder; }(NewElementBuilder); _exports.RehydrateBuilder = RehydrateBuilder; function isTextNode(node) { return node.nodeType === 3; } function isComment(node) { return node.nodeType === 8; } function getOpenBlockDepth(node) { var boundsDepth = node.nodeValue.match(/^%\+b:(\d+)%$/); if (boundsDepth && boundsDepth[1]) { return Number(boundsDepth[1]); } else { return null; } } function getCloseBlockDepth(node) { var boundsDepth = node.nodeValue.match(/^%\-b:(\d+)%$/); if (boundsDepth && boundsDepth[1]) { return Number(boundsDepth[1]); } else { return null; } } function isElement(node) { return node.nodeType === 1; } function isMarker(node) { return node.nodeType === 8 && node.nodeValue === '%glmr%'; } function isSeparator(node) { return node.nodeType === 8 && node.nodeValue === '%|%'; } function isEmpty$1(node) { return node.nodeType === 8 && node.nodeValue === '% %'; } function isSameNodeType(candidate, tag) { if (candidate.namespaceURI === SVG_NAMESPACE) { return candidate.tagName === tag; } return candidate.tagName === tag.toUpperCase(); } function findByName(array, name) { for (var i = 0; i < array.length; i++) { var attr = array[i]; if (attr.name === name) return attr; } return undefined; } function rehydrationBuilder(env, cursor) { return RehydrateBuilder.forInitialRender(env, cursor); } });
hspasov/datastreamer-server
src/modules/chunk-array-to-text.js
<filename>src/modules/chunk-array-to-text.js function chunkArrayToText(chunkArray) { let text = ""; const decoder = new TextDecoder(); for (let i = 0; i < chunkArray.length; i++) { text += decoder.decode(chunkArray[i]); } return text; } export default chunkArrayToText;
maxiko/gitlabhq
app/assets/javascripts/prometheus_metrics/prometheus_metrics.js
import $ from 'jquery'; import { escape } from 'lodash'; import { s__, n__, sprintf } from '~/locale'; import axios from '../lib/utils/axios_utils'; import PANEL_STATE from './constants'; import { backOff } from '../lib/utils/common_utils'; export default class PrometheusMetrics { constructor(wrapperSelector) { this.backOffRequestCounter = 0; this.$wrapper = $(wrapperSelector); this.$monitoredMetricsPanel = this.$wrapper.find('.js-panel-monitored-metrics'); this.$monitoredMetricsCount = this.$monitoredMetricsPanel.find('.js-monitored-count'); this.$monitoredMetricsLoading = this.$monitoredMetricsPanel.find('.js-loading-metrics'); this.$monitoredMetricsEmpty = this.$monitoredMetricsPanel.find('.js-empty-metrics'); this.$monitoredMetricsList = this.$monitoredMetricsPanel.find('.js-metrics-list'); this.$missingEnvVarPanel = this.$wrapper.find('.js-panel-missing-env-vars'); this.$panelToggleRight = this.$missingEnvVarPanel.find('.js-panel-toggle-right'); this.$panelToggleDown = this.$missingEnvVarPanel.find('.js-panel-toggle-down'); this.$missingEnvVarMetricCount = this.$missingEnvVarPanel.find('.js-env-var-count'); this.$missingEnvVarMetricsList = this.$missingEnvVarPanel.find('.js-missing-var-metrics-list'); this.activeMetricsEndpoint = this.$monitoredMetricsPanel.data('activeMetrics'); this.helpMetricsPath = this.$monitoredMetricsPanel.data('metrics-help-path'); this.$panelToggleRight.on('click', e => this.handlePanelToggle(e)); this.$panelToggleDown.on('click', e => this.handlePanelToggle(e)); } init() { this.loadActiveMetrics(); } handlePanelToggle(e) { const $toggleBtn = $(e.currentTarget); const $currentPanelBody = $toggleBtn.closest('.card').find('.card-body'); $currentPanelBody.toggleClass('hidden'); if ($toggleBtn.hasClass('js-panel-toggle-right')) { $toggleBtn.addClass('hidden'); this.$panelToggleDown.removeClass('hidden'); } else if ($toggleBtn.hasClass('js-panel-toggle-down')) { $toggleBtn.addClass('hidden'); this.$panelToggleRight.removeClass('hidden'); } } showMonitoringMetricsPanelState(stateName) { switch (stateName) { case PANEL_STATE.LOADING: this.$monitoredMetricsLoading.removeClass('hidden'); this.$monitoredMetricsEmpty.addClass('hidden'); this.$monitoredMetricsList.addClass('hidden'); break; case PANEL_STATE.LIST: this.$monitoredMetricsLoading.addClass('hidden'); this.$monitoredMetricsEmpty.addClass('hidden'); this.$monitoredMetricsList.removeClass('hidden'); break; default: this.$monitoredMetricsLoading.addClass('hidden'); this.$monitoredMetricsEmpty.removeClass('hidden'); this.$monitoredMetricsList.addClass('hidden'); break; } } populateActiveMetrics(metrics) { let totalMonitoredMetrics = 0; let totalMissingEnvVarMetrics = 0; let totalExporters = 0; metrics.forEach(metric => { if (metric.active_metrics > 0) { totalExporters += 1; this.$monitoredMetricsList.append( `<li>${escape(metric.group)}<span class="badge">${escape( metric.active_metrics, )}</span></li>`, ); totalMonitoredMetrics += metric.active_metrics; if (metric.metrics_missing_requirements > 0) { this.$missingEnvVarMetricsList.append(`<li>${escape(metric.group)}</li>`); totalMissingEnvVarMetrics += 1; } } }); if (totalMonitoredMetrics === 0) { const emptyCommonMetricsText = sprintf( s__('PrometheusService|No %{docsUrlStart}common metrics%{docsUrlEnd} were found'), { docsUrlStart: `<a href="${this.helpMetricsPath}">`, docsUrlEnd: '</a>', }, false, ); this.$monitoredMetricsEmpty.empty(); this.$monitoredMetricsEmpty.append(`<p class="text-tertiary">${emptyCommonMetricsText}</p>`); this.showMonitoringMetricsPanelState(PANEL_STATE.EMPTY); } else { const metricsCountText = sprintf( s__('PrometheusService|%{exporters} with %{metrics} were found'), { exporters: n__('%d exporter', '%d exporters', totalExporters), metrics: n__('%d metric', '%d metrics', totalMonitoredMetrics), }, ); this.$monitoredMetricsCount.text(metricsCountText); this.showMonitoringMetricsPanelState(PANEL_STATE.LIST); if (totalMissingEnvVarMetrics > 0) { this.$missingEnvVarPanel.removeClass('hidden'); this.$missingEnvVarMetricCount.text(totalMissingEnvVarMetrics); } } } loadActiveMetrics() { this.showMonitoringMetricsPanelState(PANEL_STATE.LOADING); backOff((next, stop) => { axios .get(this.activeMetricsEndpoint) .then(({ data }) => { if (data && data.success) { stop(data); } else { this.backOffRequestCounter += 1; if (this.backOffRequestCounter < 3) { next(); } else { stop(data); } } }) .catch(stop); }) .then(res => { if (res && res.data && res.data.length) { this.populateActiveMetrics(res.data); } else { this.showMonitoringMetricsPanelState(PANEL_STATE.EMPTY); } }) .catch(() => { this.showMonitoringMetricsPanelState(PANEL_STATE.EMPTY); }); } }
fedka27/meatApp
app/src/main/java/app/meat/view/base/BaseRecyclerViewHolder.java
<filename>app/src/main/java/app/meat/view/base/BaseRecyclerViewHolder.java package app.meat.view.base; import android.support.annotation.LayoutRes; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import butterknife.ButterKnife; public abstract class BaseRecyclerViewHolder extends RecyclerView.ViewHolder { public BaseRecyclerViewHolder(ViewGroup viewGroup, @LayoutRes int layoutIdRes) { super(LayoutInflater.from(viewGroup.getContext()).inflate(layoutIdRes, viewGroup, false)); ButterKnife.bind(this, getView()); } public View getView() { return itemView; } }
Hgaylor0220/WWCap
components/App.js
<filename>components/App.js import React from 'react'; import Header from './Header'; import Home from './Home'; import RiverList from './RiverList'; import NewOrderControl from './NewOrderControl'; import Error404 from './Error404'; import { Switch, Route } from 'react-router-dom'; import Admin from './Admin'; class App extends React.Component { constructor(props) { super(props); this.state = { masterRiverList: [] }; this.handleAddingNewOrderToList = this.handleAddingNewOrderToList.bind(this); } handleAddingNewOrderToList(newOrder) { var newMasterRiverList = this.state.masterRiverList.slice(); newMasterRiverList.push(newOrder); this.setState({ masterRiverList: newMasterRiverList }); } render() { return ( <div> <Header /> <Switch> <Route path='/RiverList' render={() => <RiverList RiverList={this.state.masterRiverList} />} /> <Route component={Error404} /> </Switch> </div> ); } } export default App;
felixny/SFML-Painting
server/docs/html/search/related_4.js
var searchData= [ ['runcontext_0',['RunContext',['../class_catch_1_1_lazy_expression.html#af3aa096bb29a772bc534830f29a2ce7a',1,'Catch::LazyExpression']]] ];
dplbsd/soc2013
head/sys/i386/include/cpufunc.h
<reponame>dplbsd/soc2013<gh_stars>0 /*- * Copyright (c) 1993 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: soc2013/dpl/head/sys/i386/include/cpufunc.h 239991 2012-08-01 17:24:53Z kib $ */ /* * Functions to provide access to special i386 instructions. * This in included in sys/systm.h, and that file should be * used in preference to this. */ #ifndef _MACHINE_CPUFUNC_H_ #define _MACHINE_CPUFUNC_H_ #ifndef _SYS_CDEFS_H_ #error this file needs sys/cdefs.h as a prerequisite #endif #ifdef XEN extern void xen_cli(void); extern void xen_sti(void); extern u_int xen_rcr2(void); extern void xen_load_cr3(u_int data); extern void xen_tlb_flush(void); extern void xen_invlpg(u_int addr); extern void write_eflags(u_int eflags); extern u_int read_eflags(void); #endif struct region_descriptor; #define readb(va) (*(volatile uint8_t *) (va)) #define readw(va) (*(volatile uint16_t *) (va)) #define readl(va) (*(volatile uint32_t *) (va)) #define writeb(va, d) (*(volatile uint8_t *) (va) = (d)) #define writew(va, d) (*(volatile uint16_t *) (va) = (d)) #define writel(va, d) (*(volatile uint32_t *) (va) = (d)) #if defined(__GNUCLIKE_ASM) && defined(__CC_SUPPORTS___INLINE) static __inline void breakpoint(void) { __asm __volatile("int $3"); } static __inline u_int bsfl(u_int mask) { u_int result; __asm("bsfl %1,%0" : "=r" (result) : "rm" (mask) : "cc"); return (result); } static __inline u_int bsrl(u_int mask) { u_int result; __asm("bsrl %1,%0" : "=r" (result) : "rm" (mask) : "cc"); return (result); } static __inline void clflush(u_long addr) { __asm __volatile("clflush %0" : : "m" (*(char *)addr)); } static __inline void clts(void) { __asm __volatile("clts"); } static __inline void disable_intr(void) { #ifdef XEN xen_cli(); #else __asm __volatile("cli" : : : "memory"); #endif } static __inline void do_cpuid(u_int ax, u_int *p) { __asm __volatile("cpuid" : "=a" (p[0]), "=b" (p[1]), "=c" (p[2]), "=d" (p[3]) : "0" (ax)); } static __inline void cpuid_count(u_int ax, u_int cx, u_int *p) { __asm __volatile("cpuid" : "=a" (p[0]), "=b" (p[1]), "=c" (p[2]), "=d" (p[3]) : "0" (ax), "c" (cx)); } static __inline void enable_intr(void) { #ifdef XEN xen_sti(); #else __asm __volatile("sti"); #endif } static __inline void cpu_monitor(const void *addr, u_long extensions, u_int hints) { __asm __volatile("monitor" : : "a" (addr), "c" (extensions), "d" (hints)); } static __inline void cpu_mwait(u_long extensions, u_int hints) { __asm __volatile("mwait" : : "a" (hints), "c" (extensions)); } static __inline void lfence(void) { __asm __volatile("lfence" : : : "memory"); } static __inline void mfence(void) { __asm __volatile("mfence" : : : "memory"); } #ifdef _KERNEL #define HAVE_INLINE_FFS static __inline int ffs(int mask) { /* * Note that gcc-2's builtin ffs would be used if we didn't declare * this inline or turn off the builtin. The builtin is faster but * broken in gcc-2.4.5 and slower but working in gcc-2.5 and later * versions. */ return (mask == 0 ? mask : (int)bsfl((u_int)mask) + 1); } #define HAVE_INLINE_FLS static __inline int fls(int mask) { return (mask == 0 ? mask : (int)bsrl((u_int)mask) + 1); } #endif /* _KERNEL */ static __inline void halt(void) { __asm __volatile("hlt"); } static __inline u_char inb(u_int port) { u_char data; __asm __volatile("inb %w1, %0" : "=a" (data) : "Nd" (port)); return (data); } static __inline u_int inl(u_int port) { u_int data; __asm __volatile("inl %w1, %0" : "=a" (data) : "Nd" (port)); return (data); } static __inline void insb(u_int port, void *addr, size_t count) { __asm __volatile("cld; rep; insb" : "+D" (addr), "+c" (count) : "d" (port) : "memory"); } static __inline void insw(u_int port, void *addr, size_t count) { __asm __volatile("cld; rep; insw" : "+D" (addr), "+c" (count) : "d" (port) : "memory"); } static __inline void insl(u_int port, void *addr, size_t count) { __asm __volatile("cld; rep; insl" : "+D" (addr), "+c" (count) : "d" (port) : "memory"); } static __inline void invd(void) { __asm __volatile("invd"); } static __inline u_short inw(u_int port) { u_short data; __asm __volatile("inw %w1, %0" : "=a" (data) : "Nd" (port)); return (data); } static __inline void outb(u_int port, u_char data) { __asm __volatile("outb %0, %w1" : : "a" (data), "Nd" (port)); } static __inline void outl(u_int port, u_int data) { __asm __volatile("outl %0, %w1" : : "a" (data), "Nd" (port)); } static __inline void outsb(u_int port, const void *addr, size_t count) { __asm __volatile("cld; rep; outsb" : "+S" (addr), "+c" (count) : "d" (port)); } static __inline void outsw(u_int port, const void *addr, size_t count) { __asm __volatile("cld; rep; outsw" : "+S" (addr), "+c" (count) : "d" (port)); } static __inline void outsl(u_int port, const void *addr, size_t count) { __asm __volatile("cld; rep; outsl" : "+S" (addr), "+c" (count) : "d" (port)); } static __inline void outw(u_int port, u_short data) { __asm __volatile("outw %0, %w1" : : "a" (data), "Nd" (port)); } static __inline void ia32_pause(void) { __asm __volatile("pause"); } static __inline u_int #ifdef XEN _read_eflags(void) #else read_eflags(void) #endif { u_int ef; __asm __volatile("pushfl; popl %0" : "=r" (ef)); return (ef); } static __inline uint64_t rdmsr(u_int msr) { uint64_t rv; __asm __volatile("rdmsr" : "=A" (rv) : "c" (msr)); return (rv); } static __inline uint64_t rdpmc(u_int pmc) { uint64_t rv; __asm __volatile("rdpmc" : "=A" (rv) : "c" (pmc)); return (rv); } static __inline uint64_t rdtsc(void) { uint64_t rv; __asm __volatile("rdtsc" : "=A" (rv)); return (rv); } static __inline uint32_t rdtsc32(void) { uint32_t rv; __asm __volatile("rdtsc" : "=a" (rv) : : "edx"); return (rv); } static __inline void wbinvd(void) { __asm __volatile("wbinvd"); } static __inline void #ifdef XEN _write_eflags(u_int ef) #else write_eflags(u_int ef) #endif { __asm __volatile("pushl %0; popfl" : : "r" (ef)); } static __inline void wrmsr(u_int msr, uint64_t newval) { __asm __volatile("wrmsr" : : "A" (newval), "c" (msr)); } static __inline void load_cr0(u_int data) { __asm __volatile("movl %0,%%cr0" : : "r" (data)); } static __inline u_int rcr0(void) { u_int data; __asm __volatile("movl %%cr0,%0" : "=r" (data)); return (data); } static __inline u_int rcr2(void) { u_int data; #ifdef XEN return (xen_rcr2()); #endif __asm __volatile("movl %%cr2,%0" : "=r" (data)); return (data); } static __inline void load_cr3(u_int data) { #ifdef XEN xen_load_cr3(data); #else __asm __volatile("movl %0,%%cr3" : : "r" (data) : "memory"); #endif } static __inline u_int rcr3(void) { u_int data; __asm __volatile("movl %%cr3,%0" : "=r" (data)); return (data); } static __inline void load_cr4(u_int data) { __asm __volatile("movl %0,%%cr4" : : "r" (data)); } static __inline u_int rcr4(void) { u_int data; __asm __volatile("movl %%cr4,%0" : "=r" (data)); return (data); } /* * Global TLB flush (except for thise for pages marked PG_G) */ static __inline void invltlb(void) { #ifdef XEN xen_tlb_flush(); #else load_cr3(rcr3()); #endif } /* * TLB flush for an individual page (even if it has PG_G). * Only works on 486+ CPUs (i386 does not have PG_G). */ static __inline void invlpg(u_int addr) { #ifdef XEN xen_invlpg(addr); #else __asm __volatile("invlpg %0" : : "m" (*(char *)addr) : "memory"); #endif } static __inline u_short rfs(void) { u_short sel; __asm __volatile("movw %%fs,%0" : "=rm" (sel)); return (sel); } static __inline uint64_t rgdt(void) { uint64_t gdtr; __asm __volatile("sgdt %0" : "=m" (gdtr)); return (gdtr); } static __inline u_short rgs(void) { u_short sel; __asm __volatile("movw %%gs,%0" : "=rm" (sel)); return (sel); } static __inline uint64_t ridt(void) { uint64_t idtr; __asm __volatile("sidt %0" : "=m" (idtr)); return (idtr); } static __inline u_short rldt(void) { u_short ldtr; __asm __volatile("sldt %0" : "=g" (ldtr)); return (ldtr); } static __inline u_short rss(void) { u_short sel; __asm __volatile("movw %%ss,%0" : "=rm" (sel)); return (sel); } static __inline u_short rtr(void) { u_short tr; __asm __volatile("str %0" : "=g" (tr)); return (tr); } static __inline void load_fs(u_short sel) { __asm __volatile("movw %0,%%fs" : : "rm" (sel)); } static __inline void load_gs(u_short sel) { __asm __volatile("movw %0,%%gs" : : "rm" (sel)); } static __inline void lidt(struct region_descriptor *addr) { __asm __volatile("lidt (%0)" : : "r" (addr)); } static __inline void lldt(u_short sel) { __asm __volatile("lldt %0" : : "r" (sel)); } static __inline void ltr(u_short sel) { __asm __volatile("ltr %0" : : "r" (sel)); } static __inline u_int rdr0(void) { u_int data; __asm __volatile("movl %%dr0,%0" : "=r" (data)); return (data); } static __inline void load_dr0(u_int dr0) { __asm __volatile("movl %0,%%dr0" : : "r" (dr0)); } static __inline u_int rdr1(void) { u_int data; __asm __volatile("movl %%dr1,%0" : "=r" (data)); return (data); } static __inline void load_dr1(u_int dr1) { __asm __volatile("movl %0,%%dr1" : : "r" (dr1)); } static __inline u_int rdr2(void) { u_int data; __asm __volatile("movl %%dr2,%0" : "=r" (data)); return (data); } static __inline void load_dr2(u_int dr2) { __asm __volatile("movl %0,%%dr2" : : "r" (dr2)); } static __inline u_int rdr3(void) { u_int data; __asm __volatile("movl %%dr3,%0" : "=r" (data)); return (data); } static __inline void load_dr3(u_int dr3) { __asm __volatile("movl %0,%%dr3" : : "r" (dr3)); } static __inline u_int rdr4(void) { u_int data; __asm __volatile("movl %%dr4,%0" : "=r" (data)); return (data); } static __inline void load_dr4(u_int dr4) { __asm __volatile("movl %0,%%dr4" : : "r" (dr4)); } static __inline u_int rdr5(void) { u_int data; __asm __volatile("movl %%dr5,%0" : "=r" (data)); return (data); } static __inline void load_dr5(u_int dr5) { __asm __volatile("movl %0,%%dr5" : : "r" (dr5)); } static __inline u_int rdr6(void) { u_int data; __asm __volatile("movl %%dr6,%0" : "=r" (data)); return (data); } static __inline void load_dr6(u_int dr6) { __asm __volatile("movl %0,%%dr6" : : "r" (dr6)); } static __inline u_int rdr7(void) { u_int data; __asm __volatile("movl %%dr7,%0" : "=r" (data)); return (data); } static __inline void load_dr7(u_int dr7) { __asm __volatile("movl %0,%%dr7" : : "r" (dr7)); } static __inline u_char read_cyrix_reg(u_char reg) { outb(0x22, reg); return inb(0x23); } static __inline void write_cyrix_reg(u_char reg, u_char data) { outb(0x22, reg); outb(0x23, data); } static __inline register_t intr_disable(void) { register_t eflags; eflags = read_eflags(); disable_intr(); return (eflags); } static __inline void intr_restore(register_t eflags) { write_eflags(eflags); } #else /* !(__GNUCLIKE_ASM && __CC_SUPPORTS___INLINE) */ int breakpoint(void); u_int bsfl(u_int mask); u_int bsrl(u_int mask); void clflush(u_long addr); void clts(void); void cpuid_count(u_int ax, u_int cx, u_int *p); void disable_intr(void); void do_cpuid(u_int ax, u_int *p); void enable_intr(void); void halt(void); void ia32_pause(void); u_char inb(u_int port); u_int inl(u_int port); void insb(u_int port, void *addr, size_t count); void insl(u_int port, void *addr, size_t count); void insw(u_int port, void *addr, size_t count); register_t intr_disable(void); void intr_restore(register_t ef); void invd(void); void invlpg(u_int addr); void invltlb(void); u_short inw(u_int port); void lidt(struct region_descriptor *addr); void lldt(u_short sel); void load_cr0(u_int cr0); void load_cr3(u_int cr3); void load_cr4(u_int cr4); void load_dr0(u_int dr0); void load_dr1(u_int dr1); void load_dr2(u_int dr2); void load_dr3(u_int dr3); void load_dr4(u_int dr4); void load_dr5(u_int dr5); void load_dr6(u_int dr6); void load_dr7(u_int dr7); void load_fs(u_short sel); void load_gs(u_short sel); void ltr(u_short sel); void outb(u_int port, u_char data); void outl(u_int port, u_int data); void outsb(u_int port, const void *addr, size_t count); void outsl(u_int port, const void *addr, size_t count); void outsw(u_int port, const void *addr, size_t count); void outw(u_int port, u_short data); u_int rcr0(void); u_int rcr2(void); u_int rcr3(void); u_int rcr4(void); uint64_t rdmsr(u_int msr); uint64_t rdpmc(u_int pmc); u_int rdr0(void); u_int rdr1(void); u_int rdr2(void); u_int rdr3(void); u_int rdr4(void); u_int rdr5(void); u_int rdr6(void); u_int rdr7(void); uint64_t rdtsc(void); u_char read_cyrix_reg(u_char reg); u_int read_eflags(void); u_int rfs(void); uint64_t rgdt(void); u_int rgs(void); uint64_t ridt(void); u_short rldt(void); u_short rtr(void); void wbinvd(void); void write_cyrix_reg(u_char reg, u_char data); void write_eflags(u_int ef); void wrmsr(u_int msr, uint64_t newval); #endif /* __GNUCLIKE_ASM && __CC_SUPPORTS___INLINE */ void reset_dbregs(void); #ifdef _KERNEL int rdmsr_safe(u_int msr, uint64_t *val); int wrmsr_safe(u_int msr, uint64_t newval); #endif #endif /* !_MACHINE_CPUFUNC_H_ */
bgalloway1/enroll
spec/controllers/events/individuals_controller.rb
require "rails_helper" describe Events::IndividualsController do describe "#created with an individual created event" do let(:individual) { double } let(:individual_id) { "the hbx id for this individual" } let(:rendered_template) { double } let(:di) { double } let(:channel) { double(:default_exchange => exchange, :close => nil) } let(:reply_to_key) { "some queue name" } let(:exchange) { double } let(:connection) { double(:create_channel => channel) } let(:props) { double(:headers => {:individual_id => individual_id}, :reply_to => reply_to_key) } before :each do allow(Person).to receive(:by_hbx_id).with(individual_id).and_return(found_individuals) allow(controller).to receive(:render_to_string).with( "created", {:formats => ["xml"], :locals => { :individual => individual }}).and_return(rendered_template) end describe "for an existing individual" do let(:found_individuals) { [individual] } it "should send out a message to the bus with the rendered individual object" do expect(exchange).to receive(:publish).with(rendered_template, { :routing_key => reply_to_key, :headers => { :individual_id => individual_id, :return_status => "200" } }) controller.resource(connection, di, props, "") end end describe "for an individual which doesn't exist" do let(:found_individuals) { [] } it "should send out a message to the bus with no individual object" do expect(exchange).to receive(:publish).with("", { :routing_key => reply_to_key, :headers => { :individual_id => individual_id, :return_status => "404" } }) controller.resource(connection, di, props, "") end end describe "for when an exception is thrown" do let(:found_individuals) { [individual] } let(:exception) { Exception.new("error thrown")} let(:exception_backtrace) { ["error backtrace"] } before :each do allow(Person).to receive(:by_hbx_id).with(individual_id).and_return(found_individuals) allow(controller).to receive(:render_to_string).and_raise(exception) allow(exception).to receive(:backtrace).and_return(exception_backtrace) end it "should return a 500 response and the error message" do expect(exchange).to receive(:publish).with(JSON.dump({ exception: exception.inspect, backtrace: exception_backtrace.inspect }), { :routing_key => reply_to_key, :headers => { :return_status => "500", :individual_id => individual_id } }) controller.resource(connection, di, props, "") end end end end
dmacka/MultiverseClientServer
multiverse server/multiverse-server/multiverse/bin/login_manager.py
from multiverse.mars import * from multiverse.server.worldmgr import * from multiverse.mars.objects import * from multiverse.mars.util import * from multiverse.server.math import * from multiverse.server.events import * from multiverse.server.objects import * from multiverse.server.engine import * from multiverse.server.util import * from multiverse.msgsys import * True=1 False=0 # Uncomment if you want to set a log level for this process # that is different from the server's default log level # Log.setLogLevel(1) LoginPlugin.SecureToken = False
tenomoto/ncl
ncarg2d/src/libncarg/conpacktC/c_cttdbf.c
/* * $Id: c_cttdbf.c,v 1.3 2008-07-23 16:16:44 haley Exp $ */ /************************************************************************ * * * Copyright (C) 2000 * * University Corporation for Atmospheric Research * * All Rights Reserved * * * * The use of this Software is governed by a License Agreement. * * * ************************************************************************/ #include <ncarg/ncargC.h> extern void NGCALLF(cttdbf,CTTDBF)(float*,int*,int*,float*,int*,int*,float*); void c_cttdbf #ifdef NeedFuncProto ( float *rpnt, int *iedg, int *itri, float *rwrk, int *iwrk, int iflg, float atol ) #else (rpnt,iedg,itri,rwrk,iwrk,iflg,atol) float *rpnt; int *iedg; int *itri; float *rwrk; int *iwrk; int iflg; float atol; #endif { NGCALLF(cttdbf,CTTDBF)(rpnt,iedg,itri,rwrk,iwrk,&iflg,&atol); }
metehkaya/LeetCode
Algorithms/1019.Next_Greater_Node_In_Linked_List.cpp
<reponame>metehkaya/LeetCode<filename>Algorithms/1019.Next_Greater_Node_In_Linked_List.cpp struct ListNode { int val; ListNode *next; ListNode() : val(0), next(nullptr) {} ListNode(int x) : val(x), next(nullptr) {} ListNode(int x, ListNode *next) : val(x), next(next) {} }; class Solution { public: vector<int> nextLargerNodes(ListNode* head) { vector<int> ar; while(head != NULL) { ar.push_back(head->val); head = head->next; } int n = ar.size(); stack<int> st; vector<int> ans(n); for( int i = n-1 ; i >= 0 ; i-- ) { while(!st.empty() && ar[st.top()] <= ar[i]) st.pop(); ans[i] = st.empty() ? 0 : ar[st.top()]; st.push(i); } return ans; } };
statsbiblioteket/doms-client
domsClient-common-impl/src/main/java/dk/statsbiblioteket/doms/client/impl/objects/DigitalObjectFactoryImpl.java
<gh_stars>1-10 package dk.statsbiblioteket.doms.client.impl.objects; import dk.statsbiblioteket.doms.central.CentralWebservice; import dk.statsbiblioteket.doms.central.InvalidCredentialsException; import dk.statsbiblioteket.doms.central.InvalidResourceException; import dk.statsbiblioteket.doms.central.MethodFailedException; import dk.statsbiblioteket.doms.central.ObjectProfile; import dk.statsbiblioteket.doms.client.exceptions.ServerOperationFailed; import dk.statsbiblioteket.doms.client.objects.DigitalObject; import dk.statsbiblioteket.doms.client.objects.MissingObject; import dk.statsbiblioteket.doms.client.utils.Constants; import dk.statsbiblioteket.util.caching.TimeSensitiveCache; import java.lang.ref.SoftReference; import java.util.HashMap; import java.util.Map; /** * This class retrieves and loads objects from the server. Use this class as the basis for requesting information from * the server */ public class DigitalObjectFactoryImpl extends AbstractDigitalObjectFactory { private final DigitalObject MISSING = new MissingObject(); private Map<String, SoftReference<DigitalObject>> cache; private TimeSensitiveCache<String, DigitalObject> timeSensitiveCache; /** * Constructor. Feed this a api, to talk to the Doms system. * * @param api the api for DOMs. */ public DigitalObjectFactoryImpl(CentralWebservice api) { super(api); cache = new HashMap<String, SoftReference<DigitalObject>>(); timeSensitiveCache = new TimeSensitiveCache<String, DigitalObject>(10000, false); } /** * Retrieve an object from the server. If the object cannot be found, an instance of MissingObject is returned * instead. * * @param pid the pid of the object to retrieve * * @return an instance of the DigitalObject interface * @throws ServerOperationFailed in something failed in retrieving the object * @see DataObjectImpl * @see ContentModelObjectImpl * @see dk.statsbiblioteket.doms.client.objects.MissingObject * @see TemplateObjectImpl */ @Override public synchronized DigitalObject getDigitalObject(String pid) throws ServerOperationFailed { pid = Constants.ensurePID(pid); DigitalObject object = timeSensitiveCache.get(pid); if (object == null) { try { try { //System.out.println("Object "+pid+" not in cache, loading"); AbstractDigitalObject newobj = retrieveObject(pid); timeSensitiveCache.put(pid, newobj); newobj.loadContentModels(); object = newobj; } catch (InvalidResourceException e) { object = MISSING; timeSensitiveCache.put(pid, object); } } catch (InvalidCredentialsException e) { throw new ServerOperationFailed("Invalid Credentials", e); } catch (MethodFailedException e) { throw new ServerOperationFailed("Failed to load object", e); } } return object; } private synchronized AbstractDigitalObject retrieveObject(String pid) throws InvalidCredentialsException, MethodFailedException, InvalidResourceException, ServerOperationFailed { ObjectProfile profile = getApi().getObjectProfile(pid); AbstractDigitalObject object; if ("ContentModel".equals(profile.getType())) { object = new ContentModelObjectImpl(profile, getApi(), this); } else if ("TemplateObject".equals(profile.getType())) { object = new TemplateObjectImpl(profile, getApi(), this); } else if ("CollectionObject".equals(profile.getType())) { object = new CollectionObjectImpl(profile, getApi(), this); } else if ("FileObject".equals(profile.getType())) { object = new FileObjectImpl(profile, getApi(), this); } else { object = new DataObjectImpl(profile, getApi(), this); } return object; } }