text
stringlengths 2
100k
| meta
dict |
---|---|
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright 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.
#import "TargetConditionals.h"
#if TARGET_OS_TV
// This is an unfortunate hack for Swift Package Manager support.
// SPM does not allow us to conditionally exclude Swift files for compilation by platform.
//
// So to support tvOS with SPM we need to use runtime availability checks in the Swift files.
// This means that even though the Swift extension of ShareDialog will never be run for tvOS
// targets, it still needs to be able to compile. Hence we need to declare it here.
//
// The way to fix this is to remove extensions of ObjC types in Swift.
NS_SWIFT_NAME(ShareDialog)
@interface FBSDKShareDialog : NSObject
@end
#else
#import <UIKit/UIKit.h>
#import "FBSDKShareDialogMode.h"
#import "FBSDKSharing.h"
#import "FBSDKSharingContent.h"
NS_ASSUME_NONNULL_BEGIN
/**
A dialog for sharing content on Facebook.
*/
NS_SWIFT_NAME(ShareDialog)
@interface FBSDKShareDialog : NSObject <FBSDKSharingDialog>
/**
Convenience method to create a FBSDKShareDialog with a fromViewController, content and a delegate.
@param viewController A UIViewController to present the dialog from, if appropriate.
@param content The content to be shared.
@param delegate The receiver's delegate.
*/
+ (instancetype)dialogWithViewController:(nullable UIViewController *)viewController
withContent:(id<FBSDKSharingContent>)content
delegate:(nullable id<FBSDKSharingDelegate>)delegate
NS_SWIFT_NAME(init(fromViewController:content:delegate:));
/**
Convenience method to show an FBSDKShareDialog with a fromViewController, content and a delegate.
@param viewController A UIViewController to present the dialog from, if appropriate.
@param content The content to be shared.
@param delegate The receiver's delegate.
*/
+ (instancetype)showFromViewController:(UIViewController *)viewController
withContent:(id<FBSDKSharingContent>)content
delegate:(nullable id<FBSDKSharingDelegate>)delegate
NS_SWIFT_UNAVAILABLE("Use init(fromViewController:content:delegate:).show() instead");
/**
A UIViewController to present the dialog from.
If not specified, the top most view controller will be automatically determined as best as possible.
*/
@property (nonatomic, weak) UIViewController *fromViewController;
/**
The mode with which to display the dialog.
Defaults to FBSDKShareDialogModeAutomatic, which will automatically choose the best available mode.
*/
@property (nonatomic, assign) FBSDKShareDialogMode mode;
@end
NS_ASSUME_NONNULL_END
#endif
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2019 Xilinx, 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.
*/
#define T_8U 1 // Input type of 8U
#define T_16S 0 // Input type of 16S
/* set the optimisation type */
#define NO 1 // Normal Operation
#define RO 0 // Resource Optimized
#define GRAY 1
#define ARRAY 1
#define SCALAR 0
// macros for accel
#define FUNCT_NUM 7
//#define EXTRA_ARG 0.05
//#define EXTRA_PARM XF_CONVERT_POLICY_SATURATE
// OpenCV reference macros
#define CV_FUNCT_NAME bitwise_and
//#define CV_EXTRA_ARG 0.05
| {
"pile_set_name": "Github"
} |
################## mysql-test\t\ssl_cipher_basic.test #########################
# #
# Variable Name: ssl_cipher #
# Scope: Global #
# Access Type: Static #
# Data Type: filename #
# #
# #
# Creation Date: 2008-02-07 #
# Author : Sharique Abdullah #
# #
# #
# Description:Test Cases of Dynamic System Variable ssl_cipher #
# that checks the behavior of this variable in the following ways #
# * Value Check #
# * Scope Check #
# #
# Reference: http://dev.mysql.com/doc/refman/5.1/en/ #
# server-system-variables.html #
# #
###############################################################################
--echo '#---------------------BS_STVARS_048_01----------------------#'
####################################################################
# Displaying default value #
####################################################################
SELECT COUNT(@@GLOBAL.ssl_cipher);
--echo 0 Expected
--echo '#---------------------BS_STVARS_048_02----------------------#'
####################################################################
# Check if Value can set #
####################################################################
--error ER_WRONG_TYPE_FOR_VAR
SET @@GLOBAL.ssl_cipher=1;
--echo Expected error 'Read only variable'
SELECT COUNT(@@GLOBAL.ssl_cipher);
--echo 0 Expected
--echo '#---------------------BS_STVARS_048_03----------------------#'
#################################################################
# Check if the value in GLOBAL Table matches value in variable #
#################################################################
--disable_warnings
SELECT @@GLOBAL.ssl_cipher = VARIABLE_VALUE
FROM performance_schema.global_variables
WHERE VARIABLE_NAME='ssl_cipher';
--enable_warnings
--echo 1 Expected
SELECT COUNT(@@GLOBAL.ssl_cipher);
--echo 0 Expected
--disable_warnings
SELECT COUNT(VARIABLE_VALUE)
FROM performance_schema.global_variables
WHERE VARIABLE_NAME='ssl_cipher';
--enable_warnings
--echo 1 Expected
--echo '#---------------------BS_STVARS_048_04----------------------#'
################################################################################
# Check if accessing variable with and without GLOBAL point to same variable #
################################################################################
SELECT @@ssl_cipher = @@GLOBAL.ssl_cipher;
--echo 1 Expected
--echo '#---------------------BS_STVARS_048_05----------------------#'
################################################################################
# Check if ssl_cipher can be accessed with and without @@ sign #
################################################################################
SELECT COUNT(@@ssl_cipher);
--echo 0 Expected
--Error ER_INCORRECT_GLOBAL_LOCAL_VAR
SELECT COUNT(@@local.ssl_cipher);
--echo Expected error 'Variable is a GLOBAL variable'
--Error ER_INCORRECT_GLOBAL_LOCAL_VAR
SELECT COUNT(@@SESSION.ssl_cipher);
--echo Expected error 'Variable is a GLOBAL variable'
SELECT COUNT(@@GLOBAL.ssl_cipher);
--echo 0 Expected
--Error ER_BAD_FIELD_ERROR
SELECT ssl_cipher = @@SESSION.ssl_cipher;
--echo Expected error 'Readonly variable'
| {
"pile_set_name": "Github"
} |
body {
overflow:hidden;
margin:0;
padding:0;
}
#container a {
display:inline-block;
color:inherit;
text-decoration:none;
line-height:25px;
height:100%;
width:100%;
}
#bgimg {
z-index:-10;
position:absolute;
height:100vh;
width:100vw;
background-size:cover;
background-repeat:no-repeat;
box-sizing: border-box;
}
#container {
position: absolute;
top:0;
left:0;
height:100vh;
width:100vw;
display:flex;
align-items:center;
justify-content:center;
text-align:center;
}
.sqr {
display:inline-block;
width:150px;
height:150px;
margin:3px 3px;
border:0 solid #000000;
overflow:hidden;
-moz-transition:all .25s ease-in-out;
-webkit-transition:all .25s ease-in-out;
-o-transition:all .25s ease-in-out;
transition:all .25s ease-in-out;
}
#container span {
width:inherit;
height:inherit;
line-height:150px;
text-transform:uppercase;
}
#searchinput {
width:150px;
height:37px;
padding:0 10px;
border:none;
box-sizing:border-box;
}
.popup {
z-index:101;
position:absolute;
right:40px;
padding:25px;
-moz-transition:bottom .25s ease-in-out;
-webkit-transition:bottom .25s ease-in-out;
-o-transition:bottom .25s ease-in-out;
transition:bottom .25s ease-in-out;
text-align:left;
}
.popup table {
margin-bottom: 1em;
}
.popup td:first-child {
padding-right: 3em;
}
#gearContainer {
position: fixed;
bottom: 0;
right: 0;
height: 20px;
width: 20px;
padding: 10px;
cursor: pointer;
}
#gear {
opacity: 0;
transition: opacity 0.2s ease-in-out;
}
#version {
z-index:100;
position:absolute;
bottom:5px;
right:5px;
}
/* CONFIGMENU */
.menuContainer {
display:flex;
position:absolute;
z-index:120;
top:0;
left:0;
width:100vw;
height:100vh;
font-family:Arial;
font-size:14px;
background-color:rgba(255,255,255,0.2);
box-sizing:border-box;
}
.menu {
background-color:#ffffff;
box-shadow:0 0 15px rgba(0,0,0,0.5);
margin:auto;
}
.menuBar {
height:40px;
font-size:20px;
background-color:#fbfbfb;
}
.tabBar {
display:inline-table;
table-layout:fixed;
height:100%;
width:100%;
}
.tab {
display:table-cell;
line-height:38px;
height:auto;
width:100%;
padding-left:10px;
border-width:0 0 2px 2px;
border-style:solid;
border-color:#ccc;
background-color:#eee;
opacity:0.5;
-webkit-user-select:none;
-moz-user-select:none;
-ms-user-select:none;
user-select:none;
cursor:pointer;
}
.tab:first-child {
border-left-width:0;
}
.tab:last-child {
border-right-width:0;
}
.tab:hover {
background-color:#ccc;
}
#activeTab {
background-color:#fff;
border-bottom:none;
border-color:#e5e5e5;
opacity:1;
}
.menuContent {
position:relative;
height:calc(100% - 40px);
overflow-y:auto;
}
.tabContent {
position:absolute;
top:0;
left:0;
width:100%;
}
input {
line-height:19px;
padding:0 0 0 5px;
border-radius:0;
border:1px solid #ddd;
background-color:#fbfbfb;
}
.menu input {
font-family:monospace;
font-size:inherit;
}
.squareHeading {
display:inline-block;
position:relative;
line-height:21px;
height:21px;
width:21px;
margin:30px 0 10px 0;
}
.squareHeading_addS {
display:inline-block;
position:relative;
line-height:21px;
height:21px;
width:21px;
margin:10px 0;
}
.category img {
display:inline-block;
opacity:0.5;
cursor:pointer;
}
.category img:hover {
opacity:1;
}
.squareHeading input {
display:inline-block;
position:absolute;
top:0;
width:150px;
}
.squareHeading input[name="prefix"] {
margin-left:165px;
width:30px;
}
.squareURL {
display: flex;
position:relative;
line-height:21px;
height:21px;
margin:5px 0 0 21px;
}
.squareURL input {
width:150px;
}
.squareURL input[name="url"] {
width:100%;
margin-left:5px;
}
.squareOption {
display: flex;
position:relative;
line-height:21px;
height:21px;
margin:5px 0 0 21px;
}
.squareOption input {
margin-left:5px;
}
.squareOption input[name="opt"] {
width:70px;
}
.squareOption input[name="url"] {
width:100%;
}
.squareOption input[name="space"] {
width:50px;
}
.option {
display: inline-flex;
width:100%;
line-height:25px;
}
.radioOption {
width:50%;
}
.option label {
width:100%;
}
.option input {
margin-top:4px;
}
.option input[type="text"] {
width:100%;
}
.category {
margin:40px;
}
.categoryHeading {
display:inline-block;
margin-bottom:10px;
font-size:20px;
}
.menu-button {
width:40px;
height:40px;
float:right;
line-height:40px;
text-align:center;
background-color:#ffffff;
border-bottom:2px solid #e5e5e5;
cursor:pointer;
box-sizing:border-box;
background-color:#ccccdd;
}
.menu-button:hover {
background-color:#9999bb;
}
.menu-button:last-of-type {
border-width:0 0 2px 2px;
border-style:solid;
border-color:#e5e5e5;
}
#import {
background-image:url("../img/import.png");
background-size:contain;
}
#importinput {
display:none;
}
#export {
background-image:url("../img/export.png");
background-size:contain;
}
#save {
background-image:url("../img/save.png");
background-size:contain;
background-color:#ccddcc;
}
#save:hover {
background-color:#99bb99;
}
.splitbutton {
position:relative;
--margin:18px;
display:inline-block;
height:calc(100% - var(--margin) * 2);
width:calc(50% - (var(--margin) + var(--margin) / 2));
margin:var(--margin) 0 0 var(--margin);
font-size:14px;
background-color:#fbfbfb;
border:solid 1px #dddddd;
box-sizing:border-box;
-webkit-user-select:none;
-moz-user-select:none;
-ms-user-select:none;
user-select:none;
cursor:pointer;
}
.splitbutton_nametable {
display:table;
height:100%;
width:100%;
text-align:center;
transition:height .1s ease-in-out;
}
.splitbutton_namecell {
display:table-cell;
vertical-align:middle;
background-color:inherit;
}
.splitbutton_description {
position:absolute;
bottom:0;
left:0;
overflow:hidden;
height:0;
width:100%;
padding:20px 10px 0 10px;
box-sizing:border-box;
background:linear-gradient(#dddddd, #f4f4f4 5%);
transition:height .1s ease-in-out;
}
.splitbutton:hover .splitbutton_description {
height:calc(100% - 100px);
}
.splitbutton:hover .splitbutton_nametable {
height:100px;
}
.version {
font-size:0.8em;
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2018 Niek Haarman
*
* 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.nhaarman.acorn.samples.hellobottombar.favorites
import com.nhaarman.acorn.navigation.DisposableHandle
import com.nhaarman.acorn.presentation.BasicScene
import com.nhaarman.acorn.presentation.SavableScene
import com.nhaarman.acorn.presentation.SceneKey
import com.nhaarman.acorn.samples.hellobottombar.DestinationSelectedListener
import com.nhaarman.acorn.state.SceneState
class FavoritesScene(
private val listener: Events,
savedState: SceneState? = null
) : BasicScene<FavoritesContainer>(savedState),
SavableScene {
override val key = FavoritesScene.key
private var listenerDisposable: DisposableHandle? = null
set(value) {
field?.dispose()
field = value
}
override fun attach(v: FavoritesContainer) {
super.attach(v)
listenerDisposable = v.setDestinationSelectedListener(listener)
}
override fun detach(v: FavoritesContainer) {
listenerDisposable = null
super.detach(v)
}
interface Events : DestinationSelectedListener
companion object {
val key = SceneKey.defaultKey<FavoritesScene>()
}
}
| {
"pile_set_name": "Github"
} |
module Matestack::Ui::Core::Optgroup
class Optgroup < Matestack::Ui::Core::Component::Static
html_attributes :disabled, :label
end
end
| {
"pile_set_name": "Github"
} |
CMP0061
-------
CTest does not by default tell ``make`` to ignore errors (``-i``).
The :command:`ctest_build` and :command:`build_command` commands no
longer generate build commands for :ref:`Makefile Generators` with
the ``-i`` option. Previously this was done to help build as much
of tested projects as possible. However, this behavior is not
consistent with other generators and also causes the return code
of the ``make`` tool to be meaningless.
Of course users may still add this option manually by setting
:variable:`CTEST_BUILD_COMMAND` or the ``MAKECOMMAND`` cache entry.
See the :ref:`CTest Build Step` ``MakeCommand`` setting documentation
for their effects.
The ``OLD`` behavior for this policy is to add ``-i`` to ``make``
calls in CTest. The ``NEW`` behavior for this policy is to not
add ``-i``.
This policy was introduced in CMake version 3.3. Unlike most policies,
CMake version |release| does *not* warn when this policy is not set and
simply uses OLD behavior.
.. include:: DEPRECATED.txt
| {
"pile_set_name": "Github"
} |
baseclass: fightingship.FightingShip
id: UNITS.FRIGATE
name: Frigate
radius: 5
velocity: 12.0
components:
- SelectableComponent:
type: ship
tabs: [FightingShipOverviewTab, TradeTab]
enemy_tabs: [EnemyShipOverviewTab,]
- AmbientSoundComponent
- StorageComponent:
PositiveTotalNumSlotsStorage:
limit: 120
slotnum: 4
- ShipNameComponent
- HealthComponent:
maxhealth: 200
- CommandableComponent
actionsets:
TIER.SAILORS:
as_frigate0:
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.server.hdmi;
import android.view.KeyEvent;
import libcore.util.EmptyArray;
import java.util.Arrays;
/**
* Helper class to translate android keycode to hdmi cec keycode and vice versa.
*/
final class HdmiCecKeycode {
public static final int UNSUPPORTED_KEYCODE = -1;
public static final int NO_PARAM = -1;
// =========================================================================
// Hdmi CEC keycodes
public static final int CEC_KEYCODE_SELECT = 0x00;
public static final int CEC_KEYCODE_UP = 0x01;
public static final int CEC_KEYCODE_DOWN = 0x02;
public static final int CEC_KEYCODE_LEFT = 0x03;
public static final int CEC_KEYCODE_RIGHT = 0x04;
public static final int CEC_KEYCODE_RIGHT_UP = 0x05;
public static final int CEC_KEYCODE_RIGHT_DOWN = 0x06;
public static final int CEC_KEYCODE_LEFT_UP = 0x07;
public static final int CEC_KEYCODE_LEFT_DOWN = 0x08;
public static final int CEC_KEYCODE_ROOT_MENU = 0x09;
public static final int CEC_KEYCODE_SETUP_MENU = 0x0A;
public static final int CEC_KEYCODE_CONTENTS_MENU = 0x0B;
public static final int CEC_KEYCODE_FAVORITE_MENU = 0x0C;
public static final int CEC_KEYCODE_EXIT = 0x0D;
// RESERVED = 0x0E - 0x0F
public static final int CEC_KEYCODE_MEDIA_TOP_MENU = 0x10;
public static final int CEC_KEYCODE_MEDIA_CONTEXT_SENSITIVE_MENU = 0x11;
// RESERVED = 0x12 – 0x1C
public static final int CEC_KEYCODE_NUMBER_ENTRY_MODE = 0x1D;
public static final int CEC_KEYCODE_NUMBER_11 = 0x1E;
public static final int CEC_KEYCODE_NUMBER_12 = 0x1F;
public static final int CEC_KEYCODE_NUMBER_0_OR_NUMBER_10 = 0x20;
public static final int CEC_KEYCODE_NUMBERS_1 = 0x21;
public static final int CEC_KEYCODE_NUMBERS_2 = 0x22;
public static final int CEC_KEYCODE_NUMBERS_3 = 0x23;
public static final int CEC_KEYCODE_NUMBERS_4 = 0x24;
public static final int CEC_KEYCODE_NUMBERS_5 = 0x25;
public static final int CEC_KEYCODE_NUMBERS_6 = 0x26;
public static final int CEC_KEYCODE_NUMBERS_7 = 0x27;
public static final int CEC_KEYCODE_NUMBERS_8 = 0x28;
public static final int CEC_KEYCODE_NUMBERS_9 = 0x29;
public static final int CEC_KEYCODE_DOT = 0x2A;
public static final int CEC_KEYCODE_ENTER = 0x2B;
public static final int CEC_KEYCODE_CLEAR = 0x2C;
// RESERVED = 0x2D - 0x2E
public static final int CEC_KEYCODE_NEXT_FAVORITE = 0x2F;
public static final int CEC_KEYCODE_CHANNEL_UP = 0x30;
public static final int CEC_KEYCODE_CHANNEL_DOWN = 0x31;
public static final int CEC_KEYCODE_PREVIOUS_CHANNEL = 0x32;
public static final int CEC_KEYCODE_SOUND_SELECT = 0x33;
public static final int CEC_KEYCODE_INPUT_SELECT = 0x34;
public static final int CEC_KEYCODE_DISPLAY_INFORMATION = 0x35;
public static final int CEC_KEYCODE_HELP = 0x36;
public static final int CEC_KEYCODE_PAGE_UP = 0x37;
public static final int CEC_KEYCODE_PAGE_DOWN = 0x38;
// RESERVED = 0x39 - 0x3F
public static final int CEC_KEYCODE_POWER = 0x40;
public static final int CEC_KEYCODE_VOLUME_UP = 0x41;
public static final int CEC_KEYCODE_VOLUME_DOWN = 0x42;
public static final int CEC_KEYCODE_MUTE = 0x43;
public static final int CEC_KEYCODE_PLAY = 0x44;
public static final int CEC_KEYCODE_STOP = 0x45;
public static final int CEC_KEYCODE_PAUSE = 0x46;
public static final int CEC_KEYCODE_RECORD = 0x47;
public static final int CEC_KEYCODE_REWIND = 0x48;
public static final int CEC_KEYCODE_FAST_FORWARD = 0x49;
public static final int CEC_KEYCODE_EJECT = 0x4A;
public static final int CEC_KEYCODE_FORWARD = 0x4B;
public static final int CEC_KEYCODE_BACKWARD = 0x4C;
public static final int CEC_KEYCODE_STOP_RECORD = 0x4D;
public static final int CEC_KEYCODE_PAUSE_RECORD = 0x4E;
public static final int CEC_KEYCODE_RESERVED = 0x4F;
public static final int CEC_KEYCODE_ANGLE = 0x50;
public static final int CEC_KEYCODE_SUB_PICTURE = 0x51;
public static final int CEC_KEYCODE_VIDEO_ON_DEMAND = 0x52;
public static final int CEC_KEYCODE_ELECTRONIC_PROGRAM_GUIDE = 0x53;
public static final int CEC_KEYCODE_TIMER_PROGRAMMING = 0x54;
public static final int CEC_KEYCODE_INITIAL_CONFIGURATION = 0x55;
public static final int CEC_KEYCODE_SELECT_BROADCAST_TYPE = 0x56;
public static final int CEC_KEYCODE_SELECT_SOUND_PRESENTATION = 0x57;
// RESERVED = 0x58-0x5F
public static final int CEC_KEYCODE_PLAY_FUNCTION = 0x60;
public static final int CEC_KEYCODE_PAUSE_PLAY_FUNCTION = 0x61;
public static final int CEC_KEYCODE_RECORD_FUNCTION = 0x62;
public static final int CEC_KEYCODE_PAUSE_RECORD_FUNCTION = 0x63;
public static final int CEC_KEYCODE_STOP_FUNCTION = 0x64;
public static final int CEC_KEYCODE_MUTE_FUNCTION = 0x65;
public static final int CEC_KEYCODE_RESTORE_VOLUME_FUNCTION = 0x66;
public static final int CEC_KEYCODE_TUNE_FUNCTION = 0x67;
public static final int CEC_KEYCODE_SELECT_MEDIA_FUNCTION = 0x68;
public static final int CEC_KEYCODE_SELECT_AV_INPUT_FUNCTION = 0x69;
public static final int CEC_KEYCODE_SELECT_AUDIO_INPUT_FUNCTION = 0x6A;
public static final int CEC_KEYCODE_POWER_TOGGLE_FUNCTION = 0x6B;
public static final int CEC_KEYCODE_POWER_OFF_FUNCTION = 0x6C;
public static final int CEC_KEYCODE_POWER_ON_FUNCTION = 0x6D;
// RESERVED = 0x6E-0x70
public static final int CEC_KEYCODE_F1_BLUE = 0x71;
public static final int CEC_KEYCODE_F2_RED = 0x72;
public static final int CEC_KEYCODE_F3_GREEN = 0x73;
public static final int CEC_KEYCODE_F4_YELLOW = 0x74;
public static final int CEC_KEYCODE_F5 = 0x75;
public static final int CEC_KEYCODE_DATA = 0x76;
// RESERVED = 0x77-0xFF
// =========================================================================
// UI Broadcast Type
public static final int UI_BROADCAST_TOGGLE_ALL = 0x00;
public static final int UI_BROADCAST_TOGGLE_ANALOGUE_DIGITAL = 0x01;
public static final int UI_BROADCAST_ANALOGUE = 0x10;
public static final int UI_BROADCAST_ANALOGUE_TERRESTRIAL = 0x20;
public static final int UI_BROADCAST_ANALOGUE_CABLE = 0x30;
public static final int UI_BROADCAST_ANALOGUE_SATELLITE = 0x40;
public static final int UI_BROADCAST_DIGITAL = 0x50;
public static final int UI_BROADCAST_DIGITAL_TERRESTRIAL = 0x60;
public static final int UI_BROADCAST_DIGITAL_CABLE = 0x70;
public static final int UI_BROADCAST_DIGITAL_SATELLITE = 0x80;
public static final int UI_BROADCAST_DIGITAL_COMMNICATIONS_SATELLITE = 0x90;
public static final int UI_BROADCAST_DIGITAL_COMMNICATIONS_SATELLITE_2 = 0x91;
public static final int UI_BROADCAST_IP = 0xA0;
// =========================================================================
// UI Sound Presentation Control
public static final int UI_SOUND_PRESENTATION_SOUND_MIX_DUAL_MONO = 0x20;
public static final int UI_SOUND_PRESENTATION_SOUND_MIX_KARAOKE = 0x30;
public static final int UI_SOUND_PRESENTATION_SELECT_AUDIO_DOWN_MIX = 0x80;
public static final int UI_SOUND_PRESENTATION_SELECT_AUDIO_AUTO_REVERBERATION = 0x90;
public static final int UI_SOUND_PRESENTATION_SELECT_AUDIO_AUTO_EQUALIZER = 0xA0;
public static final int UI_SOUND_PRESENTATION_BASS_STEP_PLUS = 0xB1;
public static final int UI_SOUND_PRESENTATION_BASS_NEUTRAL = 0xB2;
public static final int UI_SOUND_PRESENTATION_BASS_STEP_MINUS = 0xB3;
public static final int UI_SOUND_PRESENTATION_TREBLE_STEP_PLUS = 0xC1;
public static final int UI_SOUND_PRESENTATION_TREBLE_NEUTRAL = 0xC2;
public static final int UI_SOUND_PRESENTATION_TREBLE_STEP_MINUS = 0xC3;
private HdmiCecKeycode() {
}
/**
* A mapping between Android and CEC keycode.
* <p>
* Normal implementation of this looks like
*
* <pre>
* new KeycodeEntry(KeyEvent.KEYCODE_DPAD_CENTER, CEC_KEYCODE_SELECT);
* </pre>
* <p>
* However, some keys in CEC requires additional parameter. In order to use parameterized cec
* key, add unique android keycode (existing or custom) corresponding to a pair of cec keycode
* and and its param.
*
* <pre>
* new KeycodeEntry(CUSTOME_ANDORID_KEY_1, CEC_KEYCODE_SELECT_BROADCAST_TYPE,
* UI_BROADCAST_TOGGLE_ALL);
* new KeycodeEntry(CUSTOME_ANDORID_KEY_2, CEC_KEYCODE_SELECT_BROADCAST_TYPE,
* UI_BROADCAST_ANALOGUE);
* </pre>
*/
private static class KeycodeEntry {
private final int mAndroidKeycode;
private final boolean mIsRepeatable;
private final byte[] mCecKeycodeAndParams;
private KeycodeEntry(int androidKeycode, int cecKeycode, boolean isRepeatable,
byte[] cecParams) {
mAndroidKeycode = androidKeycode;
mIsRepeatable = isRepeatable;
mCecKeycodeAndParams = new byte[cecParams.length + 1];
System.arraycopy(cecParams, 0, mCecKeycodeAndParams, 1, cecParams.length);
mCecKeycodeAndParams[0] = (byte) (cecKeycode & 0xFF);
}
private KeycodeEntry(int androidKeycode, int cecKeycode, boolean isRepeatable) {
this(androidKeycode, cecKeycode, isRepeatable, EmptyArray.BYTE);
}
private KeycodeEntry(int androidKeycode, int cecKeycode, byte[] cecParams) {
this(androidKeycode, cecKeycode, true, cecParams);
}
private KeycodeEntry(int androidKeycode, int cecKeycode) {
this(androidKeycode, cecKeycode, true, EmptyArray.BYTE);
}
private byte[] toCecKeycodeAndParamIfMatched(int androidKeycode) {
if (mAndroidKeycode == androidKeycode) {
return mCecKeycodeAndParams;
} else {
return null;
}
}
private int toAndroidKeycodeIfMatched(byte[] cecKeycodeAndParams) {
if (Arrays.equals(mCecKeycodeAndParams, cecKeycodeAndParams)) {
return mAndroidKeycode;
} else {
return UNSUPPORTED_KEYCODE;
}
}
private Boolean isRepeatableIfMatched(int androidKeycode) {
if (mAndroidKeycode == androidKeycode) {
return mIsRepeatable;
} else {
return null;
}
}
}
private static byte[] intToSingleByteArray(int value) {
return new byte[] {
(byte) (value & 0xFF) };
}
// Keycode entry container for all mappings.
// Note that order of entry is the same as above cec keycode definition.
private static final KeycodeEntry[] KEYCODE_ENTRIES = new KeycodeEntry[] {
new KeycodeEntry(KeyEvent.KEYCODE_DPAD_CENTER, CEC_KEYCODE_SELECT),
new KeycodeEntry(KeyEvent.KEYCODE_DPAD_UP, CEC_KEYCODE_UP),
new KeycodeEntry(KeyEvent.KEYCODE_DPAD_DOWN, CEC_KEYCODE_DOWN),
new KeycodeEntry(KeyEvent.KEYCODE_DPAD_LEFT, CEC_KEYCODE_LEFT),
new KeycodeEntry(KeyEvent.KEYCODE_DPAD_RIGHT, CEC_KEYCODE_RIGHT),
// No Android keycode defined for CEC_KEYCODE_RIGHT_UP
new KeycodeEntry(UNSUPPORTED_KEYCODE, CEC_KEYCODE_RIGHT_UP),
// No Android keycode defined for CEC_KEYCODE_RIGHT_DOWN
new KeycodeEntry(UNSUPPORTED_KEYCODE, CEC_KEYCODE_RIGHT_DOWN),
// No Android keycode defined for CEC_KEYCODE_LEFT_UP
new KeycodeEntry(UNSUPPORTED_KEYCODE, CEC_KEYCODE_LEFT_UP),
// No Android keycode defined for CEC_KEYCODE_LEFT_DOWN
new KeycodeEntry(UNSUPPORTED_KEYCODE, CEC_KEYCODE_LEFT_DOWN),
// Both KEYCODE_HOME and KEYCODE_MENU keys are sent as CEC_KEYCODE_ROOT_MENU
// NOTE that the HOME key is not usually forwarded.
// When CEC_KEYCODE_ROOT_MENU is received, it is translated to KEYCODE_HOME
new KeycodeEntry(KeyEvent.KEYCODE_HOME, CEC_KEYCODE_ROOT_MENU),
new KeycodeEntry(KeyEvent.KEYCODE_MENU, CEC_KEYCODE_ROOT_MENU),
new KeycodeEntry(KeyEvent.KEYCODE_SETTINGS, CEC_KEYCODE_SETUP_MENU),
new KeycodeEntry(KeyEvent.KEYCODE_TV_CONTENTS_MENU, CEC_KEYCODE_CONTENTS_MENU, false),
// No Android keycode defined for CEC_KEYCODE_FAVORITE_MENU
new KeycodeEntry(UNSUPPORTED_KEYCODE, CEC_KEYCODE_FAVORITE_MENU),
// Note that both BACK and ESCAPE are mapped to EXIT of CEC keycode.
// This would be problematic when translates CEC keycode to Android keycode.
// In current implementation, we pick BACK as mapping of EXIT key.
// If you'd like to map CEC EXIT to Android EXIT key, change order of
// the following two definition.
new KeycodeEntry(KeyEvent.KEYCODE_BACK, CEC_KEYCODE_EXIT),
new KeycodeEntry(KeyEvent.KEYCODE_ESCAPE, CEC_KEYCODE_EXIT),
// RESERVED
new KeycodeEntry(KeyEvent.KEYCODE_MEDIA_TOP_MENU, CEC_KEYCODE_MEDIA_TOP_MENU),
new KeycodeEntry(KeyEvent.KEYCODE_TV_MEDIA_CONTEXT_MENU,
CEC_KEYCODE_MEDIA_CONTEXT_SENSITIVE_MENU),
// RESERVED
// No Android keycode defined for CEC_KEYCODE_NUMBER_ENTRY_MODE
new KeycodeEntry(KeyEvent.KEYCODE_TV_NUMBER_ENTRY, CEC_KEYCODE_NUMBER_ENTRY_MODE),
new KeycodeEntry(KeyEvent.KEYCODE_11, CEC_KEYCODE_NUMBER_11),
new KeycodeEntry(KeyEvent.KEYCODE_12, CEC_KEYCODE_NUMBER_12),
new KeycodeEntry(KeyEvent.KEYCODE_0, CEC_KEYCODE_NUMBER_0_OR_NUMBER_10),
new KeycodeEntry(KeyEvent.KEYCODE_1, CEC_KEYCODE_NUMBERS_1),
new KeycodeEntry(KeyEvent.KEYCODE_2, CEC_KEYCODE_NUMBERS_2),
new KeycodeEntry(KeyEvent.KEYCODE_3, CEC_KEYCODE_NUMBERS_3),
new KeycodeEntry(KeyEvent.KEYCODE_4, CEC_KEYCODE_NUMBERS_4),
new KeycodeEntry(KeyEvent.KEYCODE_5, CEC_KEYCODE_NUMBERS_5),
new KeycodeEntry(KeyEvent.KEYCODE_6, CEC_KEYCODE_NUMBERS_6),
new KeycodeEntry(KeyEvent.KEYCODE_7, CEC_KEYCODE_NUMBERS_7),
new KeycodeEntry(KeyEvent.KEYCODE_8, CEC_KEYCODE_NUMBERS_8),
new KeycodeEntry(KeyEvent.KEYCODE_9, CEC_KEYCODE_NUMBERS_9),
new KeycodeEntry(KeyEvent.KEYCODE_PERIOD, CEC_KEYCODE_DOT),
new KeycodeEntry(KeyEvent.KEYCODE_NUMPAD_ENTER, CEC_KEYCODE_ENTER),
new KeycodeEntry(KeyEvent.KEYCODE_CLEAR, CEC_KEYCODE_CLEAR),
// RESERVED
// No Android keycode defined for CEC_KEYCODE_NEXT_FAVORITE
new KeycodeEntry(UNSUPPORTED_KEYCODE, CEC_KEYCODE_NEXT_FAVORITE),
new KeycodeEntry(KeyEvent.KEYCODE_CHANNEL_UP, CEC_KEYCODE_CHANNEL_UP),
new KeycodeEntry(KeyEvent.KEYCODE_CHANNEL_DOWN, CEC_KEYCODE_CHANNEL_DOWN),
new KeycodeEntry(KeyEvent.KEYCODE_LAST_CHANNEL, CEC_KEYCODE_PREVIOUS_CHANNEL),
new KeycodeEntry(KeyEvent.KEYCODE_MEDIA_AUDIO_TRACK, CEC_KEYCODE_SOUND_SELECT),
new KeycodeEntry(KeyEvent.KEYCODE_TV_INPUT, CEC_KEYCODE_INPUT_SELECT),
new KeycodeEntry(KeyEvent.KEYCODE_INFO, CEC_KEYCODE_DISPLAY_INFORMATION),
// No Android keycode defined for CEC_KEYCODE_HELP
new KeycodeEntry(UNSUPPORTED_KEYCODE, CEC_KEYCODE_HELP),
new KeycodeEntry(KeyEvent.KEYCODE_PAGE_UP, CEC_KEYCODE_PAGE_UP),
new KeycodeEntry(KeyEvent.KEYCODE_PAGE_DOWN, CEC_KEYCODE_PAGE_DOWN),
// RESERVED
new KeycodeEntry(KeyEvent.KEYCODE_POWER, CEC_KEYCODE_POWER, false),
new KeycodeEntry(KeyEvent.KEYCODE_VOLUME_UP, CEC_KEYCODE_VOLUME_UP),
new KeycodeEntry(KeyEvent.KEYCODE_VOLUME_DOWN, CEC_KEYCODE_VOLUME_DOWN),
new KeycodeEntry(KeyEvent.KEYCODE_VOLUME_MUTE, CEC_KEYCODE_MUTE, false),
new KeycodeEntry(KeyEvent.KEYCODE_MEDIA_PLAY, CEC_KEYCODE_PLAY),
new KeycodeEntry(KeyEvent.KEYCODE_MEDIA_STOP, CEC_KEYCODE_STOP),
// Note that we map both MEDIA_PAUSE and MEDIA_PLAY_PAUSE to CEC PAUSE key.
// When it translates CEC PAUSE key, it picks Android MEDIA_PAUSE key as a mapping of
// it. If you'd like to choose MEDIA_PLAY_PAUSE, please change order of the following
// two lines.
new KeycodeEntry(KeyEvent.KEYCODE_MEDIA_PAUSE, CEC_KEYCODE_PAUSE),
new KeycodeEntry(KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE, CEC_KEYCODE_PAUSE),
new KeycodeEntry(KeyEvent.KEYCODE_MEDIA_RECORD, CEC_KEYCODE_RECORD),
new KeycodeEntry(KeyEvent.KEYCODE_MEDIA_REWIND, CEC_KEYCODE_REWIND),
new KeycodeEntry(KeyEvent.KEYCODE_MEDIA_FAST_FORWARD, CEC_KEYCODE_FAST_FORWARD),
new KeycodeEntry(KeyEvent.KEYCODE_MEDIA_EJECT, CEC_KEYCODE_EJECT),
new KeycodeEntry(KeyEvent.KEYCODE_MEDIA_NEXT, CEC_KEYCODE_FORWARD),
new KeycodeEntry(KeyEvent.KEYCODE_MEDIA_PREVIOUS, CEC_KEYCODE_BACKWARD),
// No Android keycode defined for CEC_KEYCODE_STOP_RECORD
new KeycodeEntry(UNSUPPORTED_KEYCODE, CEC_KEYCODE_STOP_RECORD),
// No Android keycode defined for CEC_KEYCODE_PAUSE_RECORD
new KeycodeEntry(UNSUPPORTED_KEYCODE, CEC_KEYCODE_PAUSE_RECORD),
// No Android keycode defined for CEC_KEYCODE_RESERVED
new KeycodeEntry(UNSUPPORTED_KEYCODE, CEC_KEYCODE_RESERVED),
// No Android keycode defined for CEC_KEYCODE_ANGLE
new KeycodeEntry(UNSUPPORTED_KEYCODE, CEC_KEYCODE_ANGLE),
new KeycodeEntry(KeyEvent.KEYCODE_CAPTIONS, CEC_KEYCODE_SUB_PICTURE),
// No Android keycode defined for CEC_KEYCODE_VIDEO_ON_DEMAND
new KeycodeEntry(UNSUPPORTED_KEYCODE, CEC_KEYCODE_VIDEO_ON_DEMAND),
new KeycodeEntry(KeyEvent.KEYCODE_GUIDE, CEC_KEYCODE_ELECTRONIC_PROGRAM_GUIDE),
new KeycodeEntry(KeyEvent.KEYCODE_TV_TIMER_PROGRAMMING, CEC_KEYCODE_TIMER_PROGRAMMING),
// No Android keycode defined for CEC_KEYCODE_INITIAL_CONFIGURATION
new KeycodeEntry(UNSUPPORTED_KEYCODE, CEC_KEYCODE_INITIAL_CONFIGURATION),
// No Android keycode defined for CEC_KEYCODE_SELECT_BROADCAST_TYPE
new KeycodeEntry(UNSUPPORTED_KEYCODE, CEC_KEYCODE_SELECT_BROADCAST_TYPE),
new KeycodeEntry(KeyEvent.KEYCODE_TV_TERRESTRIAL_ANALOG,
CEC_KEYCODE_SELECT_BROADCAST_TYPE, true,
intToSingleByteArray(UI_BROADCAST_ANALOGUE)),
new KeycodeEntry(KeyEvent.KEYCODE_TV_TERRESTRIAL_DIGITAL,
CEC_KEYCODE_SELECT_BROADCAST_TYPE, true,
intToSingleByteArray(UI_BROADCAST_DIGITAL_TERRESTRIAL)),
new KeycodeEntry(KeyEvent.KEYCODE_TV_SATELLITE_BS,
CEC_KEYCODE_SELECT_BROADCAST_TYPE, true,
intToSingleByteArray(UI_BROADCAST_DIGITAL_SATELLITE)),
new KeycodeEntry(KeyEvent.KEYCODE_TV_SATELLITE_CS,
CEC_KEYCODE_SELECT_BROADCAST_TYPE, true,
intToSingleByteArray(UI_BROADCAST_DIGITAL_COMMNICATIONS_SATELLITE)),
new KeycodeEntry(KeyEvent.KEYCODE_TV_NETWORK,
CEC_KEYCODE_SELECT_BROADCAST_TYPE, true,
intToSingleByteArray(UI_BROADCAST_TOGGLE_ANALOGUE_DIGITAL)),
// No Android keycode defined for CEC_KEYCODE_SELECT_SOUND_PRESENTATION
new KeycodeEntry(UNSUPPORTED_KEYCODE, CEC_KEYCODE_SELECT_SOUND_PRESENTATION),
// RESERVED
// The following deterministic key definitions do not need key mapping
// since they are supposed to be generated programmatically only.
// No Android keycode defined for CEC_KEYCODE_PLAY_FUNCTION
new KeycodeEntry(UNSUPPORTED_KEYCODE, CEC_KEYCODE_PLAY_FUNCTION, false),
// No Android keycode defined for CEC_KEYCODE_PAUSE_PLAY_FUNCTION
new KeycodeEntry(UNSUPPORTED_KEYCODE, CEC_KEYCODE_PAUSE_PLAY_FUNCTION, false),
// No Android keycode defined for CEC_KEYCODE_RECORD_FUNCTION
new KeycodeEntry(UNSUPPORTED_KEYCODE, CEC_KEYCODE_RECORD_FUNCTION, false),
// No Android keycode defined for CEC_KEYCODE_PAUSE_RECORD_FUNCTION
new KeycodeEntry(UNSUPPORTED_KEYCODE, CEC_KEYCODE_PAUSE_RECORD_FUNCTION, false),
// No Android keycode defined for CEC_KEYCODE_STOP_FUNCTION
new KeycodeEntry(UNSUPPORTED_KEYCODE, CEC_KEYCODE_STOP_FUNCTION, false),
// No Android keycode defined for CEC_KEYCODE_MUTE_FUNCTION
new KeycodeEntry(UNSUPPORTED_KEYCODE, CEC_KEYCODE_MUTE_FUNCTION, false),
// No Android keycode defined for CEC_KEYCODE_RESTORE_VOLUME_FUNCTION
new KeycodeEntry(UNSUPPORTED_KEYCODE, CEC_KEYCODE_RESTORE_VOLUME_FUNCTION, false),
// No Android keycode defined for CEC_KEYCODE_TUNE_FUNCTION
new KeycodeEntry(UNSUPPORTED_KEYCODE, CEC_KEYCODE_TUNE_FUNCTION, false),
// No Android keycode defined for CEC_KEYCODE_SELECT_MEDIA_FUNCTION
new KeycodeEntry(UNSUPPORTED_KEYCODE, CEC_KEYCODE_SELECT_MEDIA_FUNCTION, false),
// No Android keycode defined for CEC_KEYCODE_SELECT_AV_INPUT_FUNCTION
new KeycodeEntry(UNSUPPORTED_KEYCODE, CEC_KEYCODE_SELECT_AV_INPUT_FUNCTION, false),
// No Android keycode defined for CEC_KEYCODE_SELECT_AUDIO_INPUT_FUNCTION
new KeycodeEntry(UNSUPPORTED_KEYCODE, CEC_KEYCODE_SELECT_AUDIO_INPUT_FUNCTION, false),
// No Android keycode defined for CEC_KEYCODE_POWER_TOGGLE_FUNCTION
new KeycodeEntry(UNSUPPORTED_KEYCODE, CEC_KEYCODE_POWER_TOGGLE_FUNCTION, false),
// No Android keycode defined for CEC_KEYCODE_POWER_OFF_FUNCTION
new KeycodeEntry(UNSUPPORTED_KEYCODE, CEC_KEYCODE_POWER_OFF_FUNCTION, false),
// No Android keycode defined for CEC_KEYCODE_POWER_ON_FUNCTION
new KeycodeEntry(UNSUPPORTED_KEYCODE, CEC_KEYCODE_POWER_ON_FUNCTION, false),
// RESERVED
new KeycodeEntry(KeyEvent.KEYCODE_PROG_BLUE, CEC_KEYCODE_F1_BLUE),
new KeycodeEntry(KeyEvent.KEYCODE_PROG_RED, CEC_KEYCODE_F2_RED),
new KeycodeEntry(KeyEvent.KEYCODE_PROG_GREEN, CEC_KEYCODE_F3_GREEN),
new KeycodeEntry(KeyEvent.KEYCODE_PROG_YELLOW, CEC_KEYCODE_F4_YELLOW),
new KeycodeEntry(KeyEvent.KEYCODE_F5, CEC_KEYCODE_F5),
new KeycodeEntry(KeyEvent.KEYCODE_TV_DATA_SERVICE, CEC_KEYCODE_DATA),
// RESERVED
// Add a new key mapping here if new keycode is introduced.
};
/**
* Translate Android keycode to Hdmi Cec keycode and params.
*
* @param keycode Android keycode. For details, refer {@link KeyEvent}
* @return byte array of CEC keycode and params if matched. Otherwise, return null.
*/
static byte[] androidKeyToCecKey(int keycode) {
for (int i = 0; i < KEYCODE_ENTRIES.length; ++i) {
byte[] cecKeycodeAndParams = KEYCODE_ENTRIES[i].toCecKeycodeAndParamIfMatched(keycode);
if (cecKeycodeAndParams != null) {
return cecKeycodeAndParams;
}
}
return null;
}
/**
* Translate Hdmi CEC keycode with params to Android keycode.
*
* @param cecKeycodeAndParams CEC keycode and params
* @return cec keycode corresponding to the given android keycode. If finds no matched keycode,
* return {@link #UNSUPPORTED_KEYCODE}
*/
static int cecKeycodeAndParamsToAndroidKey(byte[] cecKeycodeAndParams) {
for (int i = 0; i < KEYCODE_ENTRIES.length; ++i) {
int androidKey = KEYCODE_ENTRIES[i].toAndroidKeycodeIfMatched(cecKeycodeAndParams);
if (androidKey != UNSUPPORTED_KEYCODE) {
return androidKey;
}
}
return UNSUPPORTED_KEYCODE;
}
/**
* Whether the given {@code androidKeycode} is repeatable key or not.
*
* @param androidKeycode keycode of android
* @return false if the given {@code androidKeycode} is not supported key code
*/
static boolean isRepeatableKey(int androidKeycode) {
for (int i = 0; i < KEYCODE_ENTRIES.length; ++i) {
Boolean isRepeatable = KEYCODE_ENTRIES[i].isRepeatableIfMatched(androidKeycode);
if (isRepeatable != null) {
return isRepeatable;
}
}
return false;
}
/**
* Returns {@code true} if given Android keycode is supported, otherwise {@code false}.
*/
static boolean isSupportedKeycode(int androidKeycode) {
return HdmiCecKeycode.androidKeyToCecKey(androidKeycode) != null;
}
/**
* Returns {@code true} if given Android keycode is volume control related,
* otherwise {@code false}.
*/
static boolean isVolumeKeycode(int androidKeycode) {
int cecKeyCode = HdmiCecKeycode.androidKeyToCecKey(androidKeycode)[0];
return isSupportedKeycode(androidKeycode)
&& (cecKeyCode == CEC_KEYCODE_VOLUME_UP
|| cecKeyCode == CEC_KEYCODE_VOLUME_DOWN
|| cecKeyCode == CEC_KEYCODE_MUTE
|| cecKeyCode == CEC_KEYCODE_MUTE_FUNCTION
|| cecKeyCode == CEC_KEYCODE_RESTORE_VOLUME_FUNCTION);
}
/**
* Returns CEC keycode to control audio mute status.
*
* @param muting {@code true} if audio is being muted
*/
public static int getMuteKey(boolean muting) {
// CEC_KEYCODE_MUTE_FUNCTION, CEC_KEYCODE_RESTORE_VOLUME_FUNCTION are deterministic
// commands that ensures the status changes to what we want, while CEC_KEYCODE_MUTE
// simply toggles the status.
// The former is a better choice in this regard, but there are compatibility issues
// observed - many audio receivers don't recognize the commands. We fall back on
// CEC_KEYCODE_MUTE for now.
// return muting ? CEC_KEYCODE_MUTE_FUNCTION : CEC_KEYCODE_RESTORE_VOLUME_FUNCTION;
return CEC_KEYCODE_MUTE;
}
}
| {
"pile_set_name": "Github"
} |
// SPDX-License-Identifier: GPL-2.0+
/*
* Copyright (C) 2019 Texas Instruments Incorporated - http://www.ti.com/
*/
/ {
xtal25mhz: xtal25mhz {
compatible = "fixed-clock";
#clock-cells = <0>;
clock-frequency = <25000000>;
};
};
&i2c0 {
cdce913: cdce913@65 {
compatible = "ti,cdce913";
reg = <0x65>;
clocks = <&xtal25mhz>;
#clock-cells = <1>;
xtal-load-pf = <0>;
};
};
| {
"pile_set_name": "Github"
} |
8000 20
100 3 0
400 5 0
300 5 0
1400 2 2
500 2 2
800 2 3
1400 5 0
300 5 0
1400 3 0
500 2 0
1800 4 0
440 5 10
1340 5 10
1430 3 0
500 2 0
800 2 0
1400 5 0
300 4 0
400 3 0
500 3 18
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>CMSIS DSP Software Library: arm_std_q31.c Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javaScript" src="search/search.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>
</head>
<body onload='searchBox.OnSelectItem(0);'>
<!-- Generated by Doxygen 1.7.2 -->
<script type="text/javascript"><!--
var searchBox = new SearchBox("searchBox", "search",false,'Search');
--></script>
<div class="navigation" id="top">
<div class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="modules.html"><span>Modules</span></a></li>
<li><a href="annotated.html"><span>Data Structures</span></a></li>
<li class="current"><a href="files.html"><span>Files</span></a></li>
<li><a href="examples.html"><span>Examples</span></a></li>
<li id="searchli">
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div class="tabs2">
<ul class="tablist">
<li><a href="files.html"><span>File List</span></a></li>
<li><a href="globals.html"><span>Globals</span></a></li>
</ul>
</div>
<div class="header">
<div class="headertitle">
<h1>arm_std_q31.c</h1> </div>
</div>
<div class="contents">
<a href="arm__std__q31_8c.html">Go to the documentation of this file.</a><div class="fragment"><pre class="fragment"><a name="l00001"></a>00001 <span class="comment">/* ---------------------------------------------------------------------- </span>
<a name="l00002"></a>00002 <span class="comment">* Copyright (C) 2010 ARM Limited. All rights reserved. </span>
<a name="l00003"></a>00003 <span class="comment">* </span>
<a name="l00004"></a>00004 <span class="comment">* $Date: 15. July 2011 </span>
<a name="l00005"></a>00005 <span class="comment">* $Revision: V1.0.10 </span>
<a name="l00006"></a>00006 <span class="comment">* </span>
<a name="l00007"></a>00007 <span class="comment">* Project: CMSIS DSP Library </span>
<a name="l00008"></a>00008 <span class="comment">* Title: arm_std_q31.c </span>
<a name="l00009"></a>00009 <span class="comment">* </span>
<a name="l00010"></a>00010 <span class="comment">* Description: Standard deviation of an array of Q31 type. </span>
<a name="l00011"></a>00011 <span class="comment">* </span>
<a name="l00012"></a>00012 <span class="comment">* Target Processor: Cortex-M4/Cortex-M3/Cortex-M0</span>
<a name="l00013"></a>00013 <span class="comment">* </span>
<a name="l00014"></a>00014 <span class="comment">* Version 1.0.10 2011/7/15 </span>
<a name="l00015"></a>00015 <span class="comment">* Big Endian support added and Merged M0 and M3/M4 Source code. </span>
<a name="l00016"></a>00016 <span class="comment">* </span>
<a name="l00017"></a>00017 <span class="comment">* Version 1.0.3 2010/11/29 </span>
<a name="l00018"></a>00018 <span class="comment">* Re-organized the CMSIS folders and updated documentation. </span>
<a name="l00019"></a>00019 <span class="comment">* </span>
<a name="l00020"></a>00020 <span class="comment">* Version 1.0.2 2010/11/11 </span>
<a name="l00021"></a>00021 <span class="comment">* Documentation updated. </span>
<a name="l00022"></a>00022 <span class="comment">* </span>
<a name="l00023"></a>00023 <span class="comment">* Version 1.0.1 2010/10/05 </span>
<a name="l00024"></a>00024 <span class="comment">* Production release and review comments incorporated. </span>
<a name="l00025"></a>00025 <span class="comment">* </span>
<a name="l00026"></a>00026 <span class="comment">* Version 1.0.0 2010/09/20 </span>
<a name="l00027"></a>00027 <span class="comment">* Production release and review comments incorporated. </span>
<a name="l00028"></a>00028 <span class="comment">* -------------------------------------------------------------------- */</span>
<a name="l00029"></a>00029
<a name="l00030"></a>00030 <span class="preprocessor">#include "<a class="code" href="arm__math_8h.html">arm_math.h</a>"</span>
<a name="l00031"></a>00031
<a name="l00066"></a><a class="code" href="group___s_t_d.html#ga39495e74f96116178be085c9dc7742f5">00066</a> <span class="keywordtype">void</span> <a class="code" href="group___s_t_d.html#ga39495e74f96116178be085c9dc7742f5" title="Standard deviation of the elements of a Q31 vector.">arm_std_q31</a>(
<a name="l00067"></a>00067 <a class="code" href="arm__math_8h.html#adc89a3547f5324b7b3b95adec3806bc0" title="32-bit fractional data type in 1.31 format.">q31_t</a> * pSrc,
<a name="l00068"></a>00068 uint32_t <a class="code" href="arm__fir__example__f32_8c.html#ab6558f40a619c2502fbc24c880fd4fb0">blockSize</a>,
<a name="l00069"></a>00069 <a class="code" href="arm__math_8h.html#adc89a3547f5324b7b3b95adec3806bc0" title="32-bit fractional data type in 1.31 format.">q31_t</a> * pResult)
<a name="l00070"></a>00070 {
<a name="l00071"></a>00071 <a class="code" href="arm__math_8h.html#a5aea1cb12fc02d9d44c8abf217eaa5c6" title="64-bit fractional data type in 1.63 format.">q63_t</a> sum = 0; <span class="comment">/* Accumulator */</span>
<a name="l00072"></a>00072 <a class="code" href="arm__math_8h.html#adc89a3547f5324b7b3b95adec3806bc0" title="32-bit fractional data type in 1.31 format.">q31_t</a> meanOfSquares, squareOfMean; <span class="comment">/* square of mean and mean of square */</span>
<a name="l00073"></a>00073 <a class="code" href="arm__math_8h.html#adc89a3547f5324b7b3b95adec3806bc0" title="32-bit fractional data type in 1.31 format.">q31_t</a> <a class="code" href="arm__class__marks__example__f32_8c.html#acc9290716b3c97381ce52d14b4b01681">mean</a>; <span class="comment">/* mean */</span>
<a name="l00074"></a>00074 <a class="code" href="arm__math_8h.html#adc89a3547f5324b7b3b95adec3806bc0" title="32-bit fractional data type in 1.31 format.">q31_t</a> in; <span class="comment">/* input value */</span>
<a name="l00075"></a>00075 <a class="code" href="arm__math_8h.html#adc89a3547f5324b7b3b95adec3806bc0" title="32-bit fractional data type in 1.31 format.">q31_t</a> t; <span class="comment">/* Temporary variable */</span>
<a name="l00076"></a>00076 uint32_t blkCnt; <span class="comment">/* loop counter */</span>
<a name="l00077"></a>00077
<a name="l00078"></a>00078
<a name="l00079"></a>00079 <span class="preprocessor">#ifndef ARM_MATH_CM0</span>
<a name="l00080"></a>00080 <span class="preprocessor"></span>
<a name="l00081"></a>00081 <span class="comment">/* Run the below code for Cortex-M4 and Cortex-M3 */</span>
<a name="l00082"></a>00082
<a name="l00083"></a>00083 <a class="code" href="arm__math_8h.html#adc89a3547f5324b7b3b95adec3806bc0" title="32-bit fractional data type in 1.31 format.">q31_t</a> *pIn; <span class="comment">/* Temporary pointer */</span>
<a name="l00084"></a>00084
<a name="l00085"></a>00085 pIn = pSrc;
<a name="l00086"></a>00086
<a name="l00087"></a>00087 <span class="comment">/*loop Unrolling */</span>
<a name="l00088"></a>00088 blkCnt = blockSize >> 2u;
<a name="l00089"></a>00089
<a name="l00090"></a>00090 <span class="comment">/* First part of the processing with loop unrolling. Compute 4 outputs at a time. </span>
<a name="l00091"></a>00091 <span class="comment"> ** a second loop below computes the remaining 1 to 3 samples. */</span>
<a name="l00092"></a>00092 <span class="keywordflow">while</span>(blkCnt > 0u)
<a name="l00093"></a>00093 {
<a name="l00094"></a>00094 <span class="comment">/* C = (A[0] * A[0] + A[1] * A[1] + ... + A[blockSize-1] * A[blockSize-1]) */</span>
<a name="l00095"></a>00095 <span class="comment">/* Compute Sum of squares of the input samples </span>
<a name="l00096"></a>00096 <span class="comment"> * and then store the result in a temporary variable, sum. */</span>
<a name="l00097"></a>00097 in = *pSrc++;
<a name="l00098"></a>00098 sum += ((<a class="code" href="arm__math_8h.html#a5aea1cb12fc02d9d44c8abf217eaa5c6" title="64-bit fractional data type in 1.63 format.">q63_t</a>) (in) * (in));
<a name="l00099"></a>00099 in = *pSrc++;
<a name="l00100"></a>00100 sum += ((<a class="code" href="arm__math_8h.html#a5aea1cb12fc02d9d44c8abf217eaa5c6" title="64-bit fractional data type in 1.63 format.">q63_t</a>) (in) * (in));
<a name="l00101"></a>00101 in = *pSrc++;
<a name="l00102"></a>00102 sum += ((<a class="code" href="arm__math_8h.html#a5aea1cb12fc02d9d44c8abf217eaa5c6" title="64-bit fractional data type in 1.63 format.">q63_t</a>) (in) * (in));
<a name="l00103"></a>00103 in = *pSrc++;
<a name="l00104"></a>00104 sum += ((<a class="code" href="arm__math_8h.html#a5aea1cb12fc02d9d44c8abf217eaa5c6" title="64-bit fractional data type in 1.63 format.">q63_t</a>) (in) * (in));
<a name="l00105"></a>00105
<a name="l00106"></a>00106 <span class="comment">/* Decrement the loop counter */</span>
<a name="l00107"></a>00107 blkCnt--;
<a name="l00108"></a>00108 }
<a name="l00109"></a>00109
<a name="l00110"></a>00110 <span class="comment">/* If the blockSize is not a multiple of 4, compute any remaining output samples here. </span>
<a name="l00111"></a>00111 <span class="comment"> ** No loop unrolling is used. */</span>
<a name="l00112"></a>00112 blkCnt = blockSize % 0x4u;
<a name="l00113"></a>00113
<a name="l00114"></a>00114 <span class="keywordflow">while</span>(blkCnt > 0u)
<a name="l00115"></a>00115 {
<a name="l00116"></a>00116 <span class="comment">/* C = (A[0] * A[0] + A[1] * A[1] + ... + A[blockSize-1] * A[blockSize-1]) */</span>
<a name="l00117"></a>00117 <span class="comment">/* Compute Sum of squares of the input samples </span>
<a name="l00118"></a>00118 <span class="comment"> * and then store the result in a temporary variable, sum. */</span>
<a name="l00119"></a>00119 in = *pSrc++;
<a name="l00120"></a>00120 sum += ((<a class="code" href="arm__math_8h.html#a5aea1cb12fc02d9d44c8abf217eaa5c6" title="64-bit fractional data type in 1.63 format.">q63_t</a>) (in) * (in));
<a name="l00121"></a>00121
<a name="l00122"></a>00122 <span class="comment">/* Decrement the loop counter */</span>
<a name="l00123"></a>00123 blkCnt--;
<a name="l00124"></a>00124 }
<a name="l00125"></a>00125
<a name="l00126"></a>00126 t = (<a class="code" href="arm__math_8h.html#adc89a3547f5324b7b3b95adec3806bc0" title="32-bit fractional data type in 1.31 format.">q31_t</a>) ((1.0f / (<a class="code" href="arm__math_8h.html#a4611b605e45ab401f02cab15c5e38715" title="32-bit floating-point type definition.">float32_t</a>) (blockSize - 1u)) * 1073741824.0f);
<a name="l00127"></a>00127
<a name="l00128"></a>00128 <span class="comment">/* Compute Mean of squares of the input samples </span>
<a name="l00129"></a>00129 <span class="comment"> * and then store the result in a temporary variable, meanOfSquares. */</span>
<a name="l00130"></a>00130 sum = (sum >> 31);
<a name="l00131"></a>00131 meanOfSquares = (<a class="code" href="arm__math_8h.html#adc89a3547f5324b7b3b95adec3806bc0" title="32-bit fractional data type in 1.31 format.">q31_t</a>) ((sum * t) >> 30);
<a name="l00132"></a>00132
<a name="l00133"></a>00133 <span class="comment">/* Reset the accumulator */</span>
<a name="l00134"></a>00134 sum = 0;
<a name="l00135"></a>00135
<a name="l00136"></a>00136 <span class="comment">/*loop Unrolling */</span>
<a name="l00137"></a>00137 blkCnt = blockSize >> 2u;
<a name="l00138"></a>00138
<a name="l00139"></a>00139 <span class="comment">/* Reset the input working pointer */</span>
<a name="l00140"></a>00140 pSrc = pIn;
<a name="l00141"></a>00141
<a name="l00142"></a>00142 <span class="comment">/* First part of the processing with loop unrolling. Compute 4 outputs at a time. </span>
<a name="l00143"></a>00143 <span class="comment"> ** a second loop below computes the remaining 1 to 3 samples. */</span>
<a name="l00144"></a>00144 <span class="keywordflow">while</span>(blkCnt > 0u)
<a name="l00145"></a>00145 {
<a name="l00146"></a>00146 <span class="comment">/* C = (A[0] + A[1] + A[2] + ... + A[blockSize-1]) */</span>
<a name="l00147"></a>00147 <span class="comment">/* Compute sum of all input values and then store the result in a temporary variable, sum. */</span>
<a name="l00148"></a>00148 sum += *pSrc++;
<a name="l00149"></a>00149 sum += *pSrc++;
<a name="l00150"></a>00150 sum += *pSrc++;
<a name="l00151"></a>00151 sum += *pSrc++;
<a name="l00152"></a>00152
<a name="l00153"></a>00153 <span class="comment">/* Decrement the loop counter */</span>
<a name="l00154"></a>00154 blkCnt--;
<a name="l00155"></a>00155 }
<a name="l00156"></a>00156
<a name="l00157"></a>00157 <span class="comment">/* If the blockSize is not a multiple of 4, compute any remaining output samples here. </span>
<a name="l00158"></a>00158 <span class="comment"> ** No loop unrolling is used. */</span>
<a name="l00159"></a>00159 blkCnt = blockSize % 0x4u;
<a name="l00160"></a>00160
<a name="l00161"></a>00161 <span class="keywordflow">while</span>(blkCnt > 0u)
<a name="l00162"></a>00162 {
<a name="l00163"></a>00163 <span class="comment">/* C = (A[0] + A[1] + A[2] + ... + A[blockSize-1]) */</span>
<a name="l00164"></a>00164 <span class="comment">/* Compute sum of all input values and then store the result in a temporary variable, sum. */</span>
<a name="l00165"></a>00165 sum += *pSrc++;
<a name="l00166"></a>00166
<a name="l00167"></a>00167 <span class="comment">/* Decrement the loop counter */</span>
<a name="l00168"></a>00168 blkCnt--;
<a name="l00169"></a>00169 }
<a name="l00170"></a>00170
<a name="l00171"></a>00171 <span class="preprocessor">#else</span>
<a name="l00172"></a>00172 <span class="preprocessor"></span>
<a name="l00173"></a>00173 <span class="comment">/* Run the below code for Cortex-M0 */</span>
<a name="l00174"></a>00174
<a name="l00175"></a>00175 <a class="code" href="arm__math_8h.html#a5aea1cb12fc02d9d44c8abf217eaa5c6" title="64-bit fractional data type in 1.63 format.">q63_t</a> sumOfSquares = 0; <span class="comment">/* Accumulator */</span>
<a name="l00176"></a>00176 <span class="comment">/* Loop over blockSize number of values */</span>
<a name="l00177"></a>00177 blkCnt = <a class="code" href="arm__fir__example__f32_8c.html#ab6558f40a619c2502fbc24c880fd4fb0">blockSize</a>;
<a name="l00178"></a>00178
<a name="l00179"></a>00179 <span class="keywordflow">while</span>(blkCnt > 0u)
<a name="l00180"></a>00180 {
<a name="l00181"></a>00181 <span class="comment">/* C = (A[0] * A[0] + A[1] * A[1] + ... + A[blockSize-1] * A[blockSize-1]) */</span>
<a name="l00182"></a>00182 <span class="comment">/* Compute Sum of squares of the input samples </span>
<a name="l00183"></a>00183 <span class="comment"> * and then store the result in a temporary variable, sumOfSquares. */</span>
<a name="l00184"></a>00184 in = *pSrc++;
<a name="l00185"></a>00185 sumOfSquares += ((<a class="code" href="arm__math_8h.html#a5aea1cb12fc02d9d44c8abf217eaa5c6" title="64-bit fractional data type in 1.63 format.">q63_t</a>) (in) * (in));
<a name="l00186"></a>00186
<a name="l00187"></a>00187 <span class="comment">/* C = (A[0] + A[1] + A[2] + ... + A[blockSize-1]) */</span>
<a name="l00188"></a>00188 <span class="comment">/* Compute sum of all input values and then store the result in a temporary variable, sum. */</span>
<a name="l00189"></a>00189 sum += in;
<a name="l00190"></a>00190
<a name="l00191"></a>00191 <span class="comment">/* Decrement the loop counter */</span>
<a name="l00192"></a>00192 blkCnt--;
<a name="l00193"></a>00193 }
<a name="l00194"></a>00194
<a name="l00195"></a>00195 <span class="comment">/* Compute Mean of squares of the input samples </span>
<a name="l00196"></a>00196 <span class="comment"> * and then store the result in a temporary variable, meanOfSquares. */</span>
<a name="l00197"></a>00197 t = (<a class="code" href="arm__math_8h.html#adc89a3547f5324b7b3b95adec3806bc0" title="32-bit fractional data type in 1.31 format.">q31_t</a>) ((1.0f / (<a class="code" href="arm__math_8h.html#a4611b605e45ab401f02cab15c5e38715" title="32-bit floating-point type definition.">float32_t</a>) (blockSize - 1u)) * 1073741824.0f);
<a name="l00198"></a>00198 sumOfSquares = (sumOfSquares >> 31);
<a name="l00199"></a>00199 meanOfSquares = (<a class="code" href="arm__math_8h.html#adc89a3547f5324b7b3b95adec3806bc0" title="32-bit fractional data type in 1.31 format.">q31_t</a>) ((sumOfSquares * t) >> 30);
<a name="l00200"></a>00200
<a name="l00201"></a>00201 <span class="preprocessor">#endif </span><span class="comment">/* #ifndef ARM_MATH_CM0 */</span>
<a name="l00202"></a>00202
<a name="l00203"></a>00203 <span class="comment">/* Compute mean of all input values */</span>
<a name="l00204"></a>00204 t = (<a class="code" href="arm__math_8h.html#adc89a3547f5324b7b3b95adec3806bc0" title="32-bit fractional data type in 1.31 format.">q31_t</a>) ((1.0f / (blockSize * (blockSize - 1u))) * 2147483648.0f);
<a name="l00205"></a>00205 mean = (<a class="code" href="arm__math_8h.html#adc89a3547f5324b7b3b95adec3806bc0" title="32-bit fractional data type in 1.31 format.">q31_t</a>) (sum);
<a name="l00206"></a>00206
<a name="l00207"></a>00207 <span class="comment">/* Compute square of mean */</span>
<a name="l00208"></a>00208 squareOfMean = (<a class="code" href="arm__math_8h.html#adc89a3547f5324b7b3b95adec3806bc0" title="32-bit fractional data type in 1.31 format.">q31_t</a>) (((<a class="code" href="arm__math_8h.html#a5aea1cb12fc02d9d44c8abf217eaa5c6" title="64-bit fractional data type in 1.63 format.">q63_t</a>) mean * <a class="code" href="arm__class__marks__example__f32_8c.html#acc9290716b3c97381ce52d14b4b01681">mean</a>) >> 31);
<a name="l00209"></a>00209 squareOfMean = (<a class="code" href="arm__math_8h.html#adc89a3547f5324b7b3b95adec3806bc0" title="32-bit fractional data type in 1.31 format.">q31_t</a>) (((<a class="code" href="arm__math_8h.html#a5aea1cb12fc02d9d44c8abf217eaa5c6" title="64-bit fractional data type in 1.63 format.">q63_t</a>) squareOfMean * t) >> 31);
<a name="l00210"></a>00210
<a name="l00211"></a>00211
<a name="l00212"></a>00212 <span class="comment">/* Compute standard deviation and then store the result to the destination */</span>
<a name="l00213"></a>00213 <a class="code" href="group___s_q_r_t.html#ga119e25831e141d734d7ef10636670058" title="Q31 square root function.">arm_sqrt_q31</a>(meanOfSquares - squareOfMean, pResult);
<a name="l00214"></a>00214
<a name="l00215"></a>00215 }
<a name="l00216"></a>00216
</pre></div></div>
</div>
<!--- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
<a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark"> </span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark"> </span>Data Structures</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark"> </span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark"> </span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark"> </span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark"> </span>Typedefs</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(6)"><span class="SelectionMark"> </span>Enumerations</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(7)"><span class="SelectionMark"> </span>Enumerator</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(8)"><span class="SelectionMark"> </span>Defines</a></div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<hr class="footer"/><address class="footer"><small>Generated on Fri Jul 15 2011 13:16:17 for CMSIS DSP Software Library by 
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.2 </small></address>
</body>
</html>
| {
"pile_set_name": "Github"
} |
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build linux
// +build arm64
// +build !gccgo
#include "textflag.h"
// Just jump to package syscall's implementation for all these functions.
// The runtime may know about them.
TEXT ·Syscall(SB),NOSPLIT,$0-56
B syscall·Syscall(SB)
TEXT ·Syscall6(SB),NOSPLIT,$0-80
B syscall·Syscall6(SB)
TEXT ·SyscallNoError(SB),NOSPLIT,$0-48
BL runtime·entersyscall(SB)
MOVD a1+8(FP), R0
MOVD a2+16(FP), R1
MOVD a3+24(FP), R2
MOVD $0, R3
MOVD $0, R4
MOVD $0, R5
MOVD trap+0(FP), R8 // syscall entry
SVC
MOVD R0, r1+32(FP) // r1
MOVD R1, r2+40(FP) // r2
BL runtime·exitsyscall(SB)
RET
TEXT ·RawSyscall(SB),NOSPLIT,$0-56
B syscall·RawSyscall(SB)
TEXT ·RawSyscall6(SB),NOSPLIT,$0-80
B syscall·RawSyscall6(SB)
TEXT ·RawSyscallNoError(SB),NOSPLIT,$0-48
MOVD a1+8(FP), R0
MOVD a2+16(FP), R1
MOVD a3+24(FP), R2
MOVD $0, R3
MOVD $0, R4
MOVD $0, R5
MOVD trap+0(FP), R8 // syscall entry
SVC
MOVD R0, r1+32(FP)
MOVD R1, r2+40(FP)
RET
| {
"pile_set_name": "Github"
} |
[Rank]
Dominica IV Post Pascha;;Semiduplex;;5;;
[Rule]
Gloria
Credo
Suffr=Maria3;Ecclesiae,Papa;;
[Comment]
# 4 Niedziela po Wielkanocy
! 2 klasy
! Szaty białe
W dzisiejszej liturgii Kościół uczy nas o Duchu Świętym. Jest On najdoskonalszym darem Boga (lekcja) i Pocieszycielem chrześcijan. W dziejach Kościoła Duch Święty udowadnia światu słuszność sprawy Chrystusowej, zbrodnię odrzucenia Mesjasza i przegraną szatana. Kościół Chrystusowy i dusze dobrej woli zawdzięczają Duchowi Świętemu poznanie prawdy (ewangelia). Prosimy, by życie nasze było zgodne z poznaną prawdą.
[Introitus]
!Ps 97:1; 97:2
v. Śpiewajcie Panu pieśń nową, alleluja, albowiem Pan uczynił cuda, alleluja,
w oczach pogan okazał swoją sprawiedliwość, alleluja, alleluja, alleluja.
!Ps 97:1
Zwycięstwo odniosła Jego prawica i święte ramię Jego.
&Gloria
v. Śpiewajcie Panu pieśń nową, alleluja, albowiem Pan uczynił cuda, alleluja,
w oczach pogan okazał swoją sprawiedliwość, alleluja, alleluja, alleluja.
[Oratio]
Boże, który sprawiasz, że dusze Twych wiernych mają jedno dążenie, daj ludom Twoim to miłować, co nakazujesz, tego pragnąć, co obiecujesz, abyśmy wśród zmienności świata tam utkwili nasze serca, gdzie są prawdziwe radości.
$Per Dominum
[Lectio]
Czytanie z Listu świętego Jakuba Apostoła.
!Jk 1:17-21
Najmilsi: Wszelki dar dobry i każda wzniosła łaska z wysoka pochodzi, zstępuje od Ojca światłości, u którego nie masz odmiany ani cienia zmienności. Bo z własnej woli zrodził nas słowem prawdy, abyśmy byli niejako początkiem stworzenia Jego.
Wiecie to bracia moi najmilsi! A niech każdy człowiek będzie skory do słuchania, a powolny do mówienia i powolny do gniewu. Bo gniew człowieka nie wypełnia sprawiedliwości Bożej. Dlatego też, odrzuciwszy wszelką nieczystość i nadmiar złości, przyjmujcie z łagodnością słowo w was wszczepione, które może zbawić dusze wasze.
[Graduale]
Alleluja, alleluja
!Ps 117:16
Prawica Pańska moc okazała, prawica Pańska dźwignęła mnie. Alleluja.
!Rz 6:9
Chrystus powstawszy z martwych więcej nie umiera i śmierć więcej już nad Nim nie zapanuje. Alleluja.
[Evangelium]
Ciąg dalszy ++ Ewangelii świętej według Jana.
!J 16:5-14
Onego czasu: rzekł Jezus uczniom swoim: «Idę do Tego, który mnie posłał, i nikt z was nie pyta mnie: Dokąd idziesz? Ale, żem to wam powiedział, smutek napełnił serca wasze. Lecz ja prawdę wam mówię: Lepiej dla was żebym odszedł, bo jeżeli nie odejdę, Pocieszyciel nie przyjdzie do Was, a jeśli odejdę, poślę Go do was. I gdy On przyjdzie, przekona świat o grzechu, o sprawiedliwości i o sądzie. O grzechu, mówię, że nie wierzą we mnie, o sprawiedliwości, bo idę do Ojca i już mnie nie ujrzycie, i o sądzie, bo książę tego świata już został osądzony.
Wiele jeszcze mam wam powiedzieć, ale teraz znieść nie możecie. Lecz gdy przyjdzie ów Duch Prawdy, nauczy was wszelkiej prawdy. Bo nie od siebie mówić będzie, ale cokolwiek usłyszy, powie, i co ma nadejść, oznajmi wam. On mnie uwielbi, bo z mego weźmie, a wam oznajmi».
[Offertorium]
!Ps 65:1-2; 85:16
Z radością sławcie Boga, wszystkie ziemie, opiewajcie chwałę Jego imienia. Pójdźcie wszyscy, co się Boga boicie, słuchajcie mnie, a opowiem, jak wielkie rzeczy Pan uczynił mojej duszy, alleluja.
[Secreta]
Boże, który przez przedziwną wymianę dokonującą się w tej ofierze czynisz nas uczestnikami jedynego i najwyższego Bóstwa, spraw, prosimy, aby nasze obyczaje godne były poznanej prawdy.
$Per Dominum.
[Communio]
!J 16:8
Gdy przyjdzie Pocieszyciel, Duch prawdy, przekona świat o grzechu, o sprawiedliwości i o sądzie, alleluja, alleluja.
[Postcommunio]
Przybądź nam z pomocą, Panie, Boże nasz, aby Sakrament, któryśmy z wiarą przyjęli, oczyścił nas z wad i uchronił od wszystkich niebezpieczeństw.
$Per Dominum
| {
"pile_set_name": "Github"
} |
<?php
namespace Drupal\migrate\Plugin\migrate\destination;
use Drupal\Component\Plugin\DependentPluginInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\DependencyTrait;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate\Row;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides Configuration Management destination plugin.
*
* Persists data to the config system.
*
* Available configuration keys:
* - store null: (optional) Boolean, if TRUE, when a property is NULL, NULL is
* stored, otherwise the default is used. Defaults to FALSE.
* - translations: (optional) Boolean, if TRUE, the destination will be
* associated with the langcode provided by the source plugin. Defaults to
* FALSE.
*
* Destination properties expected in the imported row:
* - config_name: The machine name of the config.
* - langcode: (optional) The language code of the config.
*
* Examples:
*
* @code
* source:
* plugin: variable
* variables:
* - node_admin_theme
* process:
* use_admin_theme: node_admin_theme
* destination:
* plugin: config
* config_name: node.settings
* @endcode
*
* This will add the value of the variable "node_admin_theme" to the config with
* the machine name "node.settings" as "node.settings.use_admin_theme".
*
* @code
* source:
* plugin: i18n_variable
* variables:
* - site_offline_message
* process:
* langcode: language
* message: site_offline_message
* destination:
* plugin: config
* config_name: system.maintenance
* translations: true
* @endcode
*
* This will add the value of the variable "site_offline_message" to the config
* with the machine name "system.maintenance" as "system.maintenance.message",
* coupled with the relevant langcode as obtained from the "i18n_variable"
* source plugin.
*
* @see \Drupal\migrate_drupal\Plugin\migrate\source\d6\i18nVariable
*
* @MigrateDestination(
* id = "config"
* )
*/
class Config extends DestinationBase implements ContainerFactoryPluginInterface, DependentPluginInterface {
use DependencyTrait;
/**
* The config object.
*
* @var \Drupal\Core\Config\Config
*/
protected $config;
/**
* The language manager.
*
* @var \Drupal\Core\Language\LanguageManagerInterface
*/
protected $language_manager;
/**
* Constructs a Config destination object.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin ID for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\migrate\Plugin\MigrationInterface $migration
* The migration entity.
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The configuration factory.
* @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
* The language manager.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration, ConfigFactoryInterface $config_factory, LanguageManagerInterface $language_manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $migration);
$this->config = $config_factory->getEditable($configuration['config_name']);
$this->language_manager = $language_manager;
if ($this->isTranslationDestination()) {
$this->supportsRollback = TRUE;
}
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration = NULL) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$migration,
$container->get('config.factory'),
$container->get('language_manager')
);
}
/**
* {@inheritdoc}
*/
public function import(Row $row, array $old_destination_id_values = []) {
if ($this->isTranslationDestination()) {
$this->config = $this->language_manager->getLanguageConfigOverride($row->getDestinationProperty('langcode'), $this->config->getName());
}
foreach ($row->getRawDestination() as $key => $value) {
if (isset($value) || !empty($this->configuration['store null'])) {
$this->config->set(str_replace(Row::PROPERTY_SEPARATOR, '.', $key), $value);
}
}
$this->config->save();
$ids[] = $this->config->getName();
if ($this->isTranslationDestination()) {
$ids[] = $row->getDestinationProperty('langcode');
}
return $ids;
}
/**
* {@inheritdoc}
*/
public function fields(MigrationInterface $migration = NULL) {
// @todo Dynamically fetch fields using Config Schema API.
}
/**
* {@inheritdoc}
*/
public function getIds() {
$ids['config_name']['type'] = 'string';
if ($this->isTranslationDestination()) {
$ids['langcode']['type'] = 'string';
}
return $ids;
}
/**
* {@inheritdoc}
*/
public function calculateDependencies() {
$provider = explode('.', $this->config->getName(), 2)[0];
$this->addDependency('module', $provider);
return $this->dependencies;
}
/**
* Get whether this destination is for translations.
*
* @return bool
* Whether this destination is for translations.
*/
protected function isTranslationDestination() {
return !empty($this->configuration['translations']);
}
/**
* {@inheritdoc}
*/
public function rollback(array $destination_identifier) {
if ($this->isTranslationDestination()) {
$language = $destination_identifier['langcode'];
$config = $this->language_manager->getLanguageConfigOverride($language, $this->config->getName());
$config->delete();
}
}
}
| {
"pile_set_name": "Github"
} |
{
"info" : {
"version" : 1,
"author" : "xcode"
}
} | {
"pile_set_name": "Github"
} |
(function() {
'use strict';
var collator;
try {
collator = (typeof Intl !== "undefined" && typeof Intl.Collator !== "undefined") ? Intl.Collator("generic", { sensitivity: "base" }) : null;
} catch (err){
console.log("Collator could not be initialized and wouldn't be used");
}
// arrays to re-use
var prevRow = [],
str2Char = [];
/**
* Based on the algorithm at http://en.wikipedia.org/wiki/Levenshtein_distance.
*/
var Levenshtein = {
/**
* Calculate levenshtein distance of the two strings.
*
* @param str1 String the first string.
* @param str2 String the second string.
* @param [options] Additional options.
* @param [options.useCollator] Use `Intl.Collator` for locale-sensitive string comparison.
* @return Integer the levenshtein distance (0 and above).
*/
get: function(str1, str2, options) {
var useCollator = (options && collator && options.useCollator);
var str1Len = str1.length,
str2Len = str2.length;
// base cases
if (str1Len === 0) return str2Len;
if (str2Len === 0) return str1Len;
// two rows
var curCol, nextCol, i, j, tmp;
// initialise previous row
for (i=0; i<str2Len; ++i) {
prevRow[i] = i;
str2Char[i] = str2.charCodeAt(i);
}
prevRow[str2Len] = str2Len;
var strCmp;
if (useCollator) {
// calculate current row distance from previous row using collator
for (i = 0; i < str1Len; ++i) {
nextCol = i + 1;
for (j = 0; j < str2Len; ++j) {
curCol = nextCol;
// substution
strCmp = 0 === collator.compare(str1.charAt(i), String.fromCharCode(str2Char[j]));
nextCol = prevRow[j] + (strCmp ? 0 : 1);
// insertion
tmp = curCol + 1;
if (nextCol > tmp) {
nextCol = tmp;
}
// deletion
tmp = prevRow[j + 1] + 1;
if (nextCol > tmp) {
nextCol = tmp;
}
// copy current col value into previous (in preparation for next iteration)
prevRow[j] = curCol;
}
// copy last col value into previous (in preparation for next iteration)
prevRow[j] = nextCol;
}
}
else {
// calculate current row distance from previous row without collator
for (i = 0; i < str1Len; ++i) {
nextCol = i + 1;
for (j = 0; j < str2Len; ++j) {
curCol = nextCol;
// substution
strCmp = str1.charCodeAt(i) === str2Char[j];
nextCol = prevRow[j] + (strCmp ? 0 : 1);
// insertion
tmp = curCol + 1;
if (nextCol > tmp) {
nextCol = tmp;
}
// deletion
tmp = prevRow[j + 1] + 1;
if (nextCol > tmp) {
nextCol = tmp;
}
// copy current col value into previous (in preparation for next iteration)
prevRow[j] = curCol;
}
// copy last col value into previous (in preparation for next iteration)
prevRow[j] = nextCol;
}
}
return nextCol;
}
};
// amd
if (typeof define !== "undefined" && define !== null && define.amd) {
define(function() {
return Levenshtein;
});
}
// commonjs
else if (typeof module !== "undefined" && module !== null && typeof exports !== "undefined" && module.exports === exports) {
module.exports = Levenshtein;
}
// web worker
else if (typeof self !== "undefined" && typeof self.postMessage === 'function' && typeof self.importScripts === 'function') {
self.Levenshtein = Levenshtein;
}
// browser main thread
else if (typeof window !== "undefined" && window !== null) {
window.Levenshtein = Levenshtein;
}
}());
| {
"pile_set_name": "Github"
} |
var FastTracker = function(){
var me = {};
// see ftp://ftp.modland.com/pub/documents/format_documentation/FastTracker%202%20v2.04%20(.xm).html
me.load = function(file,name){
console.log("loading FastTracker");
Tracker.setTrackerMode(TRACKERMODE.FASTTRACKER);
Tracker.clearInstruments(1);
var mod = {};
var song = {
patterns:[],
instruments:[]
};
file.litteEndian = true;
file.goto(17);
song.title = file.readString(20);
file.jump(1); //$1a
mod.trackerName = file.readString(20);
mod.trackerVersion = file.readByte();
mod.trackerVersion = file.readByte() + "." + mod.trackerVersion;
mod.headerSize = file.readDWord(); // is this always 276?
mod.songlength = file.readWord();
mod.restartPosition = file.readWord();
mod.numberOfChannels = file.readWord();
mod.numberOfPatterns = file.readWord(); // this is sometimes more then the actual number? should we scan for highest pattern? -> YES! -> NO!
mod.numberOfInstruments = file.readWord();
mod.flags = file.readWord();
if (mod.flags%2 === 1){
Tracker.useLinearFrequency = true;
}else{
Tracker.useLinearFrequency = false;
}
mod.defaultTempo = file.readWord();
mod.defaultBPM = file.readWord();
console.log("File was made in " + mod.trackerName + " version " + mod.trackerVersion);
var patternTable = [];
var highestPattern = 0;
for (var i = 0; i < mod.songlength; ++i) {
patternTable[i] = file.readUbyte();
if (highestPattern < patternTable[i]) highestPattern = patternTable[i];
}
song.patternTable = patternTable;
song.length = mod.songlength;
song.channels = mod.numberOfChannels;
song.restartPosition = (mod.restartPosition + 1);
var fileStartPos = 60 + mod.headerSize;
file.goto(fileStartPos);
for (i = 0; i < mod.numberOfPatterns; i++) {
var patternData = [];
var thisPattern = {};
thisPattern.headerSize = file.readDWord();
thisPattern.packingType = file.readUbyte(); // always 0
thisPattern.patternLength = file.readWord();
thisPattern.patternSize = file.readWord();
fileStartPos += thisPattern.headerSize;
file.goto(fileStartPos);
for (var step = 0; step<thisPattern.patternLength; step++){
var row = [];
var channel;
for (channel = 0; channel < mod.numberOfChannels; channel++){
var note = Note();
var v = file.readUbyte();
if (v & 128) {
if (v & 1) note.setIndex(file.readUbyte());
if (v & 2) note.instrument = file.readUbyte();
if (v & 4) note.volumeEffect = file.readUbyte();
if (v & 8) note.effect = file.readUbyte();
if (v & 16) note.param = file.readUbyte();
} else {
note.setIndex(v);
note.instrument = file.readUbyte();
note.volumeEffect = file.readUbyte();
note.effect = file.readUbyte();
note.param = file.readUbyte();
}
row.push(note);
}
patternData.push(row);
}
fileStartPos += thisPattern.patternSize;
file.goto(fileStartPos);
song.patterns.push(patternData);
}
var instrumentContainer = [];
for (i = 1; i <= mod.numberOfInstruments; ++i) {
var instrument = Instrument();
try{
instrument.filePosition = file.index;
instrument.headerSize = file.readDWord();
instrument.name = file.readString(22);
instrument.type = file.readUbyte();
instrument.numberOfSamples = file.readWord();
instrument.samples = [];
instrument.sampleHeaderSize = 0;
if (instrument.numberOfSamples>0){
instrument.sampleHeaderSize = file.readDWord();
// some files report incorrect sampleheadersize (18, without the samplename)
// e.g. dubmood - cybernostra weekends.xm
// sample header should be at least 40 bytes
instrument.sampleHeaderSize = Math.max(instrument.sampleHeaderSize,40);
// and not too much ... (Files saved with sk@letracker)
if (instrument.sampleHeaderSize>200) instrument.sampleHeaderSize=40;
//should we assume it's always 40? not according to specs ...
for (var si = 0; si<96; si++) instrument.sampleNumberForNotes.push(file.readUbyte());
for (si = 0; si<24; si++) instrument.volumeEnvelope.raw.push(file.readWord());
for (si = 0; si<24; si++) instrument.panningEnvelope.raw.push(file.readWord());
instrument.volumeEnvelope.count = file.readUbyte();
instrument.panningEnvelope.count = file.readUbyte();
instrument.volumeEnvelope.sustainPoint = file.readUbyte();
instrument.volumeEnvelope.loopStartPoint = file.readUbyte();
instrument.volumeEnvelope.loopEndPoint = file.readUbyte();
instrument.panningEnvelope.sustainPoint = file.readUbyte();
instrument.panningEnvelope.loopStartPoint = file.readUbyte();
instrument.panningEnvelope.loopEndPoint = file.readUbyte();
instrument.volumeEnvelope.type = file.readUbyte();
instrument.panningEnvelope.type = file.readUbyte();
instrument.vibrato.type = file.readUbyte();
instrument.vibrato.sweep = file.readUbyte();
instrument.vibrato.depth = Math.min(file.readUbyte(),15); // some trackers have a different scale here? (e.g. Ambrozia)
instrument.vibrato.rate = file.readUbyte();
instrument.fadeout = file.readWord();
instrument.reserved = file.readWord();
function processEnvelope(envelope){
envelope.points = [];
for (si = 0; si < 12; si++) envelope.points.push(envelope.raw.slice(si*2,si*2+2));
if (envelope.type & 1){ // on
envelope.enabled = true;
}
if (envelope.type & 2){
// sustain
envelope.sustain = true;
}
if (envelope.type & 4){
// loop
envelope.loop = true;
}
return envelope;
}
instrument.volumeEnvelope = processEnvelope(instrument.volumeEnvelope);
instrument.panningEnvelope = processEnvelope(instrument.panningEnvelope);
}
}catch (e) {
console.error("error",e);
}
fileStartPos += instrument.headerSize;
file.goto(fileStartPos);
if (instrument.numberOfSamples === 0){
var sample = Sample();
instrument.samples.push(sample);
}else{
if (file.isEOF(1)){
console.error("seek past EOF");
console.error(instrument);
break;
}
for (var sampleI = 0; sampleI < instrument.numberOfSamples; sampleI++){
sample = Sample();
sample.length = file.readDWord();
sample.loop.start = file.readDWord();
sample.loop.length = file.readDWord();
sample.volume = file.readUbyte();
sample.finetuneX = file.readByte();
sample.type = file.readUbyte();
sample.panning = file.readUbyte() - 128;
sample.relativeNote = file.readByte();
sample.reserved = file.readByte();
sample.name = file.readString(22);
sample.bits = 8;
instrument.samples.push(sample);
fileStartPos += instrument.sampleHeaderSize;
file.goto(fileStartPos);
}
for (sampleI = 0; sampleI < instrument.numberOfSamples; sampleI++){
sample = instrument.samples[sampleI];
if (!sample.length) continue;
fileStartPos += sample.length;
if (sample.type & 16) {
sample.bits = 16;
sample.type ^= 16;
sample.length >>= 1;
sample.loop.start >>= 1;
sample.loop.length >>= 1;
}
sample.loop.type = sample.type || 0;
sample.loop.enabled = !!sample.loop.type;
// sample data
console.log("Reading sample from 0x" + file.index + " with length of " + sample.length + (sample.bits === 16 ? " words" : " bytes") + " and repeat length of " + sample.loop.length);
var sampleEnd = sample.length;
var old = 0;
if (sample.bits === 16){
for (var j = 0; j<sampleEnd; j++){
var b = file.readShort() + old;
if (b < -32768) b += 65536;
else if (b > 32767) b -= 65536;
old = b;
sample.data.push(b / 32768);
}
}else{
for (j = 0; j<sampleEnd; j++){
b = file.readByte() + old;
if (b < -128) b += 256;
else if (b > 127) b -= 256;
old = b;
sample.data.push(b / 127); // TODO: or /128 ? seems to introduce artifacts - see test-loop-fadeout.xm
}
}
// unroll ping pong loops
if (sample.loop.type === LOOPTYPE.PINGPONG){
// TODO: keep original sample?
var loopPart = sample.data.slice(sample.loop.start,sample.loop.start + sample.loop.length);
sample.data = sample.data.slice(0,sample.loop.start + sample.loop.length);
sample.data = sample.data.concat(loopPart.reverse());
sample.loop.length = sample.loop.length*2;
sample.length = sample.loop.start + sample.loop.length;
}
file.goto(fileStartPos);
}
}
instrument.setSampleIndex(0);
Tracker.setInstrument(i,instrument);
instrumentContainer.push({label: i + " " + instrument.name, data: i});
}
EventBus.trigger(EVENT.instrumentListChange,instrumentContainer);
song.instruments = Tracker.getInstruments();
Tracker.setBPM(mod.defaultBPM);
Tracker.setAmigaSpeed(mod.defaultTempo);
me.validate(song);
return song;
};
// build internal
//<!--
me.write = function(next){
var song = Tracker.getSong();
var instruments = Tracker.getInstruments(); // note: intruments start at index 1, not 0
var trackCount = Tracker.getTrackCount();
var version = typeof versionNumber === "undefined" ? "dev" : versionNumber;
var highestPattern = 0;
for (i = 0;i<128;i++){
var p = song.patternTable[i] || 0;
highestPattern = Math.max(highestPattern,p);
}
// first get filesize
var fileSize = 60 + 276;
for (i = 0; i<=highestPattern; i++){
if (song.patterns[i]){
fileSize += (9 + (song.patterns[i].length * trackCount * 5));
}
}
// TODO: trim instrument list;
for (i = 1; i<instruments.length; i++){
var instrument = instruments[i];
if (instrument && instrument.hasSamples()){
instrument.samples.forEach(function(sample){
var len = sample.length;
if (sample.bits === 16) len *= 2;
fileSize += 243 + 40 + len;
});
}else{
fileSize += 29;
}
}
var i;
var arrayBuffer = new ArrayBuffer(fileSize);
var file = new BinaryStream(arrayBuffer,false);
file.writeStringSection("Extended Module: ",17);
file.writeStringSection(song.title,20);
file.writeByte(26);
file.writeStringSection("BassoonTracker " + version,20);
file.writeByte(4); // minor version xm format
file.writeByte(1); // major version xm format
file.writeDWord(276); // header size;
file.writeWord(song.length);
file.writeWord(0); //restart position
file.writeWord(Tracker.getTrackCount());
file.writeWord(highestPattern+1); // number of patterns
file.writeWord(instruments.length-1); // number of instruments
file.writeWord(Tracker.useLinearFrequency?1:0);
file.writeWord(Tracker.getAmigaSpeed()); // default tempo
file.writeWord(Tracker.getBPM()); // default BPM
//TO CHECK: are most players compatible when we only only write the actual song length instead of all 256?
for (i = 0; i < 256; i++) {
file.writeUByte(song.patternTable[i] || 0);
}
// write pattern data
for (i = 0; i <= highestPattern; i++) {
var thisPattern = song.patterns[i];
var patternLength = 0;
var patternSize = 0;
if (thisPattern) {
patternLength = thisPattern.length;
patternSize = patternLength * trackCount * 5;
}
file.writeDWord(9); // header size;
file.writeUByte(0); // packing type
file.writeWord(patternLength);
file.writeWord(patternSize);
if (thisPattern){
// TODO: packing?
for (var step=0, max=thisPattern.length; step<max;step++){
var row = thisPattern[step];
for (var channel=0; channel<trackCount;channel++){
var note = row[channel] || {};
file.writeUByte(note.index || 0);
file.writeUByte(note.instrument || 0);
file.writeUByte(note.volumeEffect || 0);
file.writeUByte(note.effect || 0);
file.writeUByte(note.param || 0);
}
}
}
}
// write instrument data
for (i=1; i<instruments.length; i++){
instrument = instruments[i];
if (instrument && instrument.hasSamples()){
instrument.numberOfSamples = instrument.samples.length;
file.writeDWord(243); // header size;
file.writeStringSection(instrument.name,22);
file.writeUByte(0); // instrument type
file.writeWord(instrument.numberOfSamples); // number of samples
var volumeEnvelopeType =
(instrument.volumeEnvelope.enabled?1:0)
+ (instrument.volumeEnvelope.sustain?2:0)
+ (instrument.volumeEnvelope.loop?4:0);
var panningEnvelopeType =
(instrument.panningEnvelope.enabled?1:0)
+ (instrument.panningEnvelope.sustain?2:0)
+ (instrument.panningEnvelope.loop?4:0);
file.writeDWord(40); // sample header size;
for (var si = 0; si<96; si++){
file.writeUByte(instrument.sampleNumberForNotes[si] || 0); // sample number for notes
}
// volume envelope
for (si = 0; si<12; si++){
var point = instrument.volumeEnvelope.points[si] || [0,0];
file.writeWord(point[0]);
file.writeWord(point[1]);
}
// panning envelope
for (si = 0; si<12; si++){
point = instrument.panningEnvelope.points[si] || [0,0];
file.writeWord(point[0]);
file.writeWord(point[1]);
}
file.writeUByte(instrument.volumeEnvelope.count || 0);
file.writeUByte(instrument.panningEnvelope.count || 0);
file.writeUByte(instrument.volumeEnvelope.sustainPoint || 0);
file.writeUByte(instrument.volumeEnvelope.loopStartPoint || 0);
file.writeUByte(instrument.volumeEnvelope.loopEndPoint || 0);
file.writeUByte(instrument.panningEnvelope.sustainPoint || 0);
file.writeUByte(instrument.panningEnvelope.loopStartPoint || 0);
file.writeUByte(instrument.panningEnvelope.loopEndPoint || 0);
file.writeUByte(volumeEnvelopeType);
file.writeUByte(panningEnvelopeType);
file.writeUByte(instrument.vibrato.type || 0);
file.writeUByte(instrument.vibrato.sweep || 0);
file.writeUByte(instrument.vibrato.depth || 0);
file.writeUByte(instrument.vibrato.rate || 0);
file.writeWord(instrument.fadeout || 0);
file.writeWord(0); // reserved
// write samples
// first all sample headers
for (var sampleI = 0; sampleI < instrument.numberOfSamples; sampleI++){
var thisSample = instrument.samples[sampleI];
var sampleType = 0;
if (thisSample.loop.length>2 && thisSample.loop.enabled) sampleType=1;
//TODO pingpong loops, or are we keeping pingpong loops unrolled?
var sampleByteLength = thisSample.length;
var sampleLoopByteStart = thisSample.loop.start;
var sampleLoopByteLength = thisSample.loop.length;
if (thisSample.bits === 16) {
sampleType+=16;
sampleByteLength *= 2;
sampleLoopByteStart *= 2;
sampleLoopByteLength *= 2;
}
file.writeDWord(sampleByteLength);
file.writeDWord(sampleLoopByteStart);
file.writeDWord(sampleLoopByteLength);
file.writeUByte(thisSample.volume);
file.writeByte(thisSample.finetuneX);
file.writeUByte(sampleType);
file.writeUByte((thisSample.panning || 0) + 128);
file.writeUByte(thisSample.relativeNote || 0);
file.writeUByte(0);
file.writeStringSection(thisSample.name || "",22);
}
// then all sample data
for (sampleI = 0; sampleI < instrument.numberOfSamples; sampleI++){
thisSample = instrument.samples[sampleI];
var b;
var delta = 0;
var prev = 0;
if (thisSample.bits === 16){
for (si = 0, max=thisSample.length; si<max ; si++){
// write 16-bit sample data
b = Math.round(thisSample.data[si] * 32768);
delta = b-prev;
prev = b;
if (delta < -32768) delta += 65536;
else if (delta > 32767) delta -= 65536;
file.writeWord(delta);
}
}else{
for (si = 0, max=thisSample.length; si<max ; si++){
// write 8-bit sample data
b = Math.round(thisSample.data[si] * 127);
delta = b-prev;
prev = b;
if (delta < -128) delta += 256;
else if (delta > 127) delta -= 256;
file.writeByte(delta);
}
}
}
}else{
// empty instrument
file.writeDWord(29); // header size;
file.writeStringSection(instrument ? instrument.name : "",22);
file.writeUByte(0); // instrument type
file.writeWord(0); // number of samples
}
}
if (next) next(file);
};
//-->
me.validate = function(song){
function checkEnvelope(envelope,type){
var isValid = true;
if (envelope.points && envelope.points[0]){
if (envelope.points[0][0] === 0){
var c = 0;
for (var i=1;i<envelope.count;i++){
var point = envelope.points[i];
if (point && point[0]>c){
c = point[0];
}else{
isValid=false;
}
}
}else{
isValid = false;
}
}else{
isValid = false;
}
if (isValid){
return envelope;
}else{
console.warn("Invalid envelope, resetting to default");
return type === "volume"
? {raw: [], enabled: false, points: [[0,48],[10,64],[20,40],[30,18],[40,28],[50,18]], count:6}
: {raw: [], enabled: false, points: [[0,32],[20,40],[40,24],[60,32],[80,32]], count:5};
}
}
song.instruments.forEach(function(instrument){
// check envelope
instrument.volumeEnvelope = checkEnvelope(instrument.volumeEnvelope,"volume");
instrument.panningEnvelope = checkEnvelope(instrument.panningEnvelope,"panning");
// check sampleIndexes;
var maxSampleIndex = instrument.samples.length-1;
for (var i = 0, max = instrument.sampleNumberForNotes.length; i<max; i++){
instrument.sampleNumberForNotes[i] = Math.min(instrument.sampleNumberForNotes[i],maxSampleIndex);
}
})
};
return me;
};
| {
"pile_set_name": "Github"
} |
## How to make a smart picture showing with css [Back](./qa.md)
- Here is a smart way to show a picture in a html web page. Only with some **CSS**, the picture will be displayed in a different way like the [**example**](http://aleen42.github.io/example/smartPic/index.html).
#### 1. have the html files
```html
<div class="pic-container">
<!-- the link of the picture you want to jump into -->
<a href="">
<div class="over">
<!-- set the over picture icon -->
<div class="link-btn" style="background-image: url();"></div>
</div>
</a>
<!-- set the picture src -->
<div class="shop" style="background-image: url();"></div>
</div>
```
#### 2. set the css
```css
.pic-container {
margin-top: 2%;
display: inline-block;
width: 75%;
height: 300px;
overflow: hidden;
position: relative;
cursor: pointer;
z-index: 1;
}
.pic-container .shop {
width: 100%;
height: 100%;
position: absolute;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
transition: transform 1.5s;
-webkit-transition: transform 1.5s;
}
.pic-container .over {
position: absolute;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.7);
z-index: 2;
opacity: 0;
transition: opacity 0.4s;
-webkit-transition: opacity 0.4s;
}
.pic-container .over .link-btn {
width: 100%;
height: 100%;
position: absolute;
background-position: center;
background-repeat: no-repeat;
background-size: auto 15%;
z-index: 3;
}
.pic-container .over .product-name {
color: #fff;
position: absolute;
bottom: 3%;
text-align: center;
width: 100%;
font-size: 1.2em;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.pic-container .over .product-price {
color: #ffa200;
position: absolute;
top: 3%;
right: 3%;
font-size: 1.5em;
}
.pic-container .line {
height: 1px;
background-color: white;
width: 40%;
left: 30%;
position: absolute;
transition: transform 1.5s;
-webkit-transition: transform 1.5s;
}
.pic-container .ln1 {
top: 40%;
}
.pic-container .ln2 {
bottom: 40%;
transition-delay: 0.2s;
-webkit-transition-delay: 0.2s;
}
.pic-container:hover .shop {
transform: scale(1.04, 1.04);
-webkit-transform: scale(1.04, 1.04);
}
.pic-container:hover .over {
opacity: 1;
}
.pic-container:hover .line {
transform: scale(0.2, 1);
-webkit-transform: scale(0.2, 1);
}
```
| {
"pile_set_name": "Github"
} |
1415 1565597611173 httpcache-v1
Method: POST
URL: https://www.notion.so/api/v3/getRecordValues
Body:+110
{
"requests": [
{
"id": "c257caf4-7140-4773-b69e-7886cfebc866",
"table": "block"
}
]
}
Response:+1215
{
"results": [
{
"role": "comment_only",
"value": {
"alive": true,
"content": [
"9afb533a-ac91-45b9-b5b6-16160eeb14c0",
"7b110c7a-f4ae-4ed6-a3c0-b61eeb4665a2",
"4b8f142f-5f14-4766-9c15-7fc933af3594",
"b3950310-8a36-4293-b856-53ab1bda29ef",
"2e81bd49-f720-4476-9ea4-17ee2e0bc3b9"
],
"created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"created_time": 1552101300000,
"format": {
"page_full_width": true,
"page_small_text": true
},
"id": "c257caf4-7140-4773-b69e-7886cfebc866",
"last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"last_edited_time": 1552101600000,
"parent_id": "51f7633c-df1f-4ab1-a777-8e8095f599bd",
"parent_table": "block",
"permissions": [
{
"role": "editor",
"type": "user_permission",
"user_id": "bb760e2d-d679-4b64-b2a9-03005b21870a"
}
],
"properties": {
"title": [
[
"Method missing"
]
]
},
"type": "page",
"version": 33
}
}
]
}
12261 1565597611174 httpcache-v1
Method: POST
URL: https://www.notion.so/api/v3/loadPageChunk
Body:+152
{
"chunkNumber": 0,
"cursor": {
"stack": []
},
"limit": 50,
"pageId": "c257caf4-7140-4773-b69e-7886cfebc866",
"verticalColumns": false
}
Response:+12020
{
"cursor": {
"stack": []
},
"recordMap": {
"block": {
"2e81bd49-f720-4476-9ea4-17ee2e0bc3b9": {
"role": "comment_only",
"value": {
"alive": true,
"content": [
"1998f71b-e5fb-41e3-83b2-639a036d3bc5"
],
"created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"created_time": 1552101304914,
"format": {
"page_full_width": true,
"page_small_text": true
},
"id": "2e81bd49-f720-4476-9ea4-17ee2e0bc3b9",
"ignore_block_count": true,
"last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"last_edited_time": 1552101304914,
"parent_id": "c257caf4-7140-4773-b69e-7886cfebc866",
"parent_table": "block",
"properties": {
"title": [
[
"Using the missing method"
]
]
},
"type": "page",
"version": 3
}
},
"4b8f142f-5f14-4766-9c15-7fc933af3594": {
"role": "comment_only",
"value": {
"alive": true,
"content": [
"279d74cf-ac04-442e-998e-74b0c96d2947"
],
"created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"created_time": 1552101302926,
"format": {
"page_full_width": true,
"page_small_text": true
},
"id": "4b8f142f-5f14-4766-9c15-7fc933af3594",
"ignore_block_count": true,
"last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"last_edited_time": 1552101302926,
"parent_id": "c257caf4-7140-4773-b69e-7886cfebc866",
"parent_table": "block",
"properties": {
"title": [
[
"Use with block"
]
]
},
"type": "page",
"version": 3
}
},
"51f7633c-df1f-4ab1-a777-8e8095f599bd": {
"role": "comment_only",
"value": {
"alive": true,
"content": [
"c644c69a-7b97-448a-a252-970bcba3dbc5",
"15c95d8e-ee3b-4cbc-916b-22ba9be56012",
"3efb1b78-3f39-4bb2-9cf8-9795f8fdeacb",
"d02a2bbf-2a24-4c97-802e-aa220f4dbe24",
"526b98b2-3732-4941-ae3c-1e34440107c3",
"5d7c03e8-234e-44ac-99c0-de7bac145d55",
"6d75b2af-48c2-4f57-a52d-16232196c696",
"bd841f16-9559-465f-bd31-488dd383c486",
"d037520d-b311-450d-93c0-56ebd4112937",
"09e1b5cf-1a4d-40ce-9988-4288a4269d46",
"d43d4630-d5f4-4667-982d-03e02440c201",
"9cce7d8d-7d75-4c89-8d3d-4b403c63ca7a",
"dad9079e-f86e-45ca-a86d-64c83fac38ae",
"c257caf4-7140-4773-b69e-7886cfebc866",
"98460cdd-6994-4ad2-97d6-27deab14079c",
"d879941a-3f7c-4970-b09f-cbd77cb932d2",
"04e23c6b-c2cd-4606-81d6-13cc2dce5d78",
"f6d62287-fb0f-4bcb-afb4-5cf3437a357c",
"39077d16-6763-4235-9e51-82d2579b35df",
"c5283f07-4be2-4750-9418-3727592670e2",
"1833e628-8643-4e8c-ad78-0531e86722ae",
"541465a3-a3f8-453c-a793-f17d5824260e",
"fb26c2f8-f71d-4bc9-ae23-a82861d8ea47",
"e9481ae9-ca5e-4b9f-b722-d570649c2cfe",
"d3393ec6-47a7-47e4-ba42-d101db781d0a",
"4bb329de-b3fd-45b4-a19c-735d2948a10e",
"37bbd008-8fcb-44e6-a318-2023467879c3",
"421c1221-be5c-42b4-89bc-611d14ed995b",
"bb7b92de-fe97-478d-b6fb-13a05cc83213",
"0d7a4d19-fb72-485a-8da6-7465910936ff",
"79781265-6a05-4558-8302-be7fd30fa720",
"0beba742-561b-4cc3-bb40-d171ebf4b35f",
"d8406e27-f8d8-4f50-a58a-e03727420eb3",
"bcfaa3e1-f118-49ad-b63f-82d373de34f3",
"226323b1-302c-4a19-9833-dcd38be20f9d",
"b12e295c-908d-4ace-a221-5922b63999b9",
"fcfe325e-bfdb-4741-9e78-def959689142",
"0fef2d80-34e3-4dde-813f-ca18453232c1",
"2cd9e159-28d5-46d8-979d-8949da1379cd",
"7f9f1e81-fd42-4952-8f40-7145b0bfd61f",
"35eddfe7-54d2-4a0e-a602-87477eb8d3bc",
"60275fdc-4f50-440f-a917-b0c36e3fc177",
"cb0e2d47-43c5-4809-b173-e764dfc894dc",
"104208bf-54bf-4328-af5c-f6aeb0105199",
"1ba86719-188e-4bf3-af1d-d5522aac14d9",
"56ead039-5a17-41ac-aabb-8b32453caa32",
"7eb3d215-c3b9-459b-91a2-50b351cb9a27",
"646950e5-562c-4def-ac73-f11050db3526",
"e2c0d93a-60f5-4355-88ec-feb8992fee94",
"acd30baa-c28d-44b3-b3e4-3bffc6f38270",
"bd282be1-56e1-4d1d-8027-7d824c9f0418",
"f4a09b0e-5917-4616-bb2e-8271c834ddff",
"36398b40-cb12-4fd8-829a-5dd8aa2617b5",
"ae5dd55a-c2f8-453c-b48e-0019de81a71a",
"3d619f09-c104-4572-a105-9167b3454634",
"fd9f55c7-eaa9-432f-b822-84aafb3636ed",
"26effae7-5f43-4caf-862c-0413d8a3b33a",
"503b869c-facb-4daf-9429-76956c6e6073",
"05086c82-1b0a-43ec-ae42-dfd5af1cce18",
"ef09b0ce-fe8b-4767-8f8b-16cf766bcf5b",
"ff17ee6e-cf45-4e7e-9f1f-2d198c0da86f",
"9c88dbdc-003f-4bf8-8cd2-91e2af392489",
"2e5841e2-43c9-4064-856b-bd6e8a71db8b",
"6e074c20-aa26-42a0-90a8-e0af35c0ad06",
"cad04a1a-1384-444d-9772-f66e5db944c5",
"5742d364-d071-465e-95f8-1cd23bd1e88d",
"ef591f05-8c85-4797-9c81-2d7c75cd2621",
"35d129d5-0bd0-4afc-98ed-750fb5c3c535",
"ba664011-d11f-48ca-9190-965b7ab51da5",
"f7fe2f0b-28ed-4ce0-b500-3c33542c0316",
"af1e59e1-5fbe-4c1a-a9bc-d8692da82213",
"9650f45f-a495-462c-8fed-8d47c6532a9a"
],
"created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"created_time": 1552101097821,
"format": {
"page_full_width": true,
"page_small_text": true
},
"id": "51f7633c-df1f-4ab1-a777-8e8095f599bd",
"last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"last_edited_time": 1553725980000,
"parent_id": "a253ec1b-9a22-4fed-8092-48668a5c15df",
"parent_table": "block",
"permissions": [
{
"allow_search_engine_indexing": false,
"role": "comment_only",
"type": "public_permission"
}
],
"properties": {
"title": [
[
"Essential Ruby"
]
]
},
"type": "page",
"version": 125
}
},
"7b110c7a-f4ae-4ed6-a3c0-b61eeb4665a2": {
"role": "comment_only",
"value": {
"alive": true,
"content": [
"5b910ac1-608c-4610-baba-11f7cf927b89"
],
"created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"created_time": 1552101302006,
"format": {
"page_full_width": true,
"page_small_text": true
},
"id": "7b110c7a-f4ae-4ed6-a3c0-b61eeb4665a2",
"ignore_block_count": true,
"last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"last_edited_time": 1552101302006,
"parent_id": "c257caf4-7140-4773-b69e-7886cfebc866",
"parent_table": "block",
"properties": {
"title": [
[
"Catching calls to an undefined method"
]
]
},
"type": "page",
"version": 3
}
},
"9afb533a-ac91-45b9-b5b6-16160eeb14c0": {
"role": "comment_only",
"value": {
"alive": true,
"content": [
"665b3411-e7bf-4ae4-a631-bde59a6b2bf5",
"c11ea2f5-639c-4ae7-8be5-180107b55241",
"12b8eef1-029d-4f11-b77e-792899a81fe5",
"82c83f0c-0459-4028-9bcd-2855d52212f5",
"f7ec625f-0f4e-4780-9d4c-bcb9aa862f79",
"263f0adf-2d60-4c11-b243-c36b42c89719",
"e18cb44c-326d-4ddc-a24a-14216ad2bffd",
"f4762f01-5d05-43f5-ab40-ebfc73f785d5",
"8fd23d84-a873-438b-8a2e-abf6a3296c47",
"44fc5214-39e9-49ca-8f5f-ae052cdb5732"
],
"created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"created_time": 1552101300831,
"format": {
"page_full_width": true,
"page_small_text": true
},
"id": "9afb533a-ac91-45b9-b5b6-16160eeb14c0",
"ignore_block_count": true,
"last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"last_edited_time": 1552101300831,
"parent_id": "c257caf4-7140-4773-b69e-7886cfebc866",
"parent_table": "block",
"properties": {
"title": [
[
"method missing"
]
]
},
"type": "page",
"version": 3
}
},
"b3950310-8a36-4293-b856-53ab1bda29ef": {
"role": "comment_only",
"value": {
"alive": true,
"content": [
"b76ee6de-0e04-45e0-94dc-f59ed0ab0133"
],
"created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"created_time": 1552101303994,
"format": {
"page_full_width": true,
"page_small_text": true
},
"id": "b3950310-8a36-4293-b856-53ab1bda29ef",
"ignore_block_count": true,
"last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"last_edited_time": 1552101303994,
"parent_id": "c257caf4-7140-4773-b69e-7886cfebc866",
"parent_table": "block",
"properties": {
"title": [
[
"Use with parameter"
]
]
},
"type": "page",
"version": 3
}
},
"c257caf4-7140-4773-b69e-7886cfebc866": {
"role": "comment_only",
"value": {
"alive": true,
"content": [
"9afb533a-ac91-45b9-b5b6-16160eeb14c0",
"7b110c7a-f4ae-4ed6-a3c0-b61eeb4665a2",
"4b8f142f-5f14-4766-9c15-7fc933af3594",
"b3950310-8a36-4293-b856-53ab1bda29ef",
"2e81bd49-f720-4476-9ea4-17ee2e0bc3b9"
],
"created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"created_time": 1552101300000,
"format": {
"page_full_width": true,
"page_small_text": true
},
"id": "c257caf4-7140-4773-b69e-7886cfebc866",
"last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"last_edited_time": 1552101600000,
"parent_id": "51f7633c-df1f-4ab1-a777-8e8095f599bd",
"parent_table": "block",
"permissions": [
{
"role": "editor",
"type": "user_permission",
"user_id": "bb760e2d-d679-4b64-b2a9-03005b21870a"
}
],
"properties": {
"title": [
[
"Method missing"
]
]
},
"type": "page",
"version": 33
}
}
},
"notion_user": {
"bb760e2d-d679-4b64-b2a9-03005b21870a": {
"role": "reader",
"value": {
"clipper_onboarding_completed": true,
"email": "[email protected]",
"family_name": "Kowalczyk",
"given_name": "Krzysztof",
"id": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"mobile_onboarding_completed": true,
"onboarding_completed": true,
"profile_photo": "https://s3-us-west-2.amazonaws.com/public.notion-static.com/2dcaa66c-7674-4ff6-9924-601785b63561/head-bw-640x960.png",
"version": 179
}
}
},
"space": {}
}
}
| {
"pile_set_name": "Github"
} |
<?php
namespace PhpOffice\PhpSpreadsheet\Style;
use PhpOffice\PhpSpreadsheet\IComparable;
class Conditional implements IComparable
{
// Condition types
const CONDITION_NONE = 'none';
const CONDITION_CELLIS = 'cellIs';
const CONDITION_CONTAINSTEXT = 'containsText';
const CONDITION_EXPRESSION = 'expression';
const CONDITION_CONTAINSBLANKS = 'containsBlanks';
// Operator types
const OPERATOR_NONE = '';
const OPERATOR_BEGINSWITH = 'beginsWith';
const OPERATOR_ENDSWITH = 'endsWith';
const OPERATOR_EQUAL = 'equal';
const OPERATOR_GREATERTHAN = 'greaterThan';
const OPERATOR_GREATERTHANOREQUAL = 'greaterThanOrEqual';
const OPERATOR_LESSTHAN = 'lessThan';
const OPERATOR_LESSTHANOREQUAL = 'lessThanOrEqual';
const OPERATOR_NOTEQUAL = 'notEqual';
const OPERATOR_CONTAINSTEXT = 'containsText';
const OPERATOR_NOTCONTAINS = 'notContains';
const OPERATOR_BETWEEN = 'between';
/**
* Condition type.
*
* @var string
*/
private $conditionType = self::CONDITION_NONE;
/**
* Operator type.
*
* @var string
*/
private $operatorType = self::OPERATOR_NONE;
/**
* Text.
*
* @var string
*/
private $text;
/**
* Stop on this condition, if it matches.
*
* @var bool
*/
private $stopIfTrue = false;
/**
* Condition.
*
* @var string[]
*/
private $condition = [];
/**
* Style.
*
* @var Style
*/
private $style;
/**
* Create a new Conditional.
*/
public function __construct()
{
// Initialise values
$this->style = new Style(false, true);
}
/**
* Get Condition type.
*
* @return string
*/
public function getConditionType()
{
return $this->conditionType;
}
/**
* Set Condition type.
*
* @param string $pValue Condition type, see self::CONDITION_*
*
* @return Conditional
*/
public function setConditionType($pValue)
{
$this->conditionType = $pValue;
return $this;
}
/**
* Get Operator type.
*
* @return string
*/
public function getOperatorType()
{
return $this->operatorType;
}
/**
* Set Operator type.
*
* @param string $pValue Conditional operator type, see self::OPERATOR_*
*
* @return Conditional
*/
public function setOperatorType($pValue)
{
$this->operatorType = $pValue;
return $this;
}
/**
* Get text.
*
* @return string
*/
public function getText()
{
return $this->text;
}
/**
* Set text.
*
* @param string $value
*
* @return Conditional
*/
public function setText($value)
{
$this->text = $value;
return $this;
}
/**
* Get StopIfTrue.
*
* @return bool
*/
public function getStopIfTrue()
{
return $this->stopIfTrue;
}
/**
* Set StopIfTrue.
*
* @param bool $value
*
* @return Conditional
*/
public function setStopIfTrue($value)
{
$this->stopIfTrue = $value;
return $this;
}
/**
* Get Conditions.
*
* @return string[]
*/
public function getConditions()
{
return $this->condition;
}
/**
* Set Conditions.
*
* @param string[] $pValue Condition
*
* @return Conditional
*/
public function setConditions($pValue)
{
if (!is_array($pValue)) {
$pValue = [$pValue];
}
$this->condition = $pValue;
return $this;
}
/**
* Add Condition.
*
* @param string $pValue Condition
*
* @return Conditional
*/
public function addCondition($pValue)
{
$this->condition[] = $pValue;
return $this;
}
/**
* Get Style.
*
* @return Style
*/
public function getStyle()
{
return $this->style;
}
/**
* Set Style.
*
* @param Style $pValue
*
* @return Conditional
*/
public function setStyle(Style $pValue = null)
{
$this->style = $pValue;
return $this;
}
/**
* Get hash code.
*
* @return string Hash code
*/
public function getHashCode()
{
return md5(
$this->conditionType .
$this->operatorType .
implode(';', $this->condition) .
$this->style->getHashCode() .
__CLASS__
);
}
/**
* Implement PHP __clone to create a deep clone, not just a shallow copy.
*/
public function __clone()
{
$vars = get_object_vars($this);
foreach ($vars as $key => $value) {
if (is_object($value)) {
$this->$key = clone $value;
} else {
$this->$key = $value;
}
}
}
}
| {
"pile_set_name": "Github"
} |
# Copyright 2014 Rackspace
# 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.
from sqlalchemy import ForeignKey
from sqlalchemy.schema import Column
from sqlalchemy.schema import MetaData
from sqlalchemy.schema import UniqueConstraint
from trove.db.sqlalchemy.migrate_repo.schema import Boolean
from trove.db.sqlalchemy.migrate_repo.schema import create_tables
from trove.db.sqlalchemy.migrate_repo.schema import DateTime
from trove.db.sqlalchemy.migrate_repo.schema import String
from trove.db.sqlalchemy.migrate_repo.schema import Table
meta = MetaData()
datastore_configuration_parameters = Table(
'datastore_configuration_parameters',
meta,
Column('id', String(36), primary_key=True, nullable=False),
Column('name', String(128), primary_key=True, nullable=False),
Column('datastore_version_id', String(36),
ForeignKey("datastore_versions.id"),
primary_key=True, nullable=False),
Column('restart_required', Boolean(), nullable=False, default=False),
Column('max_size', String(40)),
Column('min_size', String(40)),
Column('data_type', String(128), nullable=False),
Column('deleted', Boolean()),
Column('deleted_at', DateTime()),
UniqueConstraint(
'datastore_version_id', 'name',
name='UQ_datastore_configuration_parameters_datastore_version_id_name')
)
def upgrade(migrate_engine):
meta.bind = migrate_engine
Table('datastore_versions', meta, autoload=True)
create_tables([datastore_configuration_parameters])
| {
"pile_set_name": "Github"
} |
*%(basename)s:6: SyntaxError: Detected cycle while resolving name 'foo' in 'modules-cycle5.mjs'
export {foo} from "modules-cycle5.mjs";
^^^
SyntaxError: Detected cycle while resolving name 'foo' in 'modules-cycle5.mjs'
| {
"pile_set_name": "Github"
} |
/**
* Module dependencies.
*/
var Route = require('./route')
, utils = require('../utils')
, methods = require('methods')
, debug = require('debug')('express:router')
, parse = require('connect').utils.parseUrl;
/**
* Expose `Router` constructor.
*/
exports = module.exports = Router;
/**
* Initialize a new `Router` with the given `options`.
*
* @param {Object} options
* @api private
*/
function Router(options) {
options = options || {};
var self = this;
this.map = {};
this.params = {};
this._params = [];
this.caseSensitive = options.caseSensitive;
this.strict = options.strict;
this.middleware = function router(req, res, next){
self._dispatch(req, res, next);
};
}
/**
* Register a param callback `fn` for the given `name`.
*
* @param {String|Function} name
* @param {Function} fn
* @return {Router} for chaining
* @api public
*/
Router.prototype.param = function(name, fn){
// param logic
if ('function' == typeof name) {
this._params.push(name);
return;
}
// apply param functions
var params = this._params
, len = params.length
, ret;
for (var i = 0; i < len; ++i) {
if (ret = params[i](name, fn)) {
fn = ret;
}
}
// ensure we end up with a
// middleware function
if ('function' != typeof fn) {
throw new Error('invalid param() call for ' + name + ', got ' + fn);
}
(this.params[name] = this.params[name] || []).push(fn);
return this;
};
/**
* Route dispatcher aka the route "middleware".
*
* @param {IncomingMessage} req
* @param {ServerResponse} res
* @param {Function} next
* @api private
*/
Router.prototype._dispatch = function(req, res, next){
var params = this.params
, self = this;
debug('dispatching %s %s (%s)', req.method, req.url, req.originalUrl);
// route dispatch
(function pass(i, err){
var paramCallbacks
, paramIndex = 0
, paramVal
, route
, keys
, key;
// match next route
function nextRoute(err) {
pass(req._route_index + 1, err);
}
// match route
req.route = route = self.matchRequest(req, i);
// implied OPTIONS
if (!route && 'OPTIONS' == req.method) return self._options(req, res);
// no route
if (!route) return next(err);
debug('matched %s %s', route.method, route.path);
// we have a route
// start at param 0
req.params = route.params;
keys = route.keys;
i = 0;
// param callbacks
function param(err) {
paramIndex = 0;
key = keys[i++];
paramVal = key && req.params[key.name];
paramCallbacks = key && params[key.name];
try {
if ('route' == err) {
nextRoute();
} else if (err) {
i = 0;
callbacks(err);
} else if (paramCallbacks && undefined !== paramVal) {
paramCallback();
} else if (key) {
param();
} else {
i = 0;
callbacks();
}
} catch (err) {
param(err);
}
};
param(err);
// single param callbacks
function paramCallback(err) {
var fn = paramCallbacks[paramIndex++];
if (err || !fn) return param(err);
fn(req, res, paramCallback, paramVal, key.name);
}
// invoke route callbacks
function callbacks(err) {
var fn = route.callbacks[i++];
try {
if ('route' == err) {
nextRoute();
} else if (err && fn) {
if (fn.length < 4) return callbacks(err);
fn(err, req, res, callbacks);
} else if (fn) {
if (fn.length < 4) return fn(req, res, callbacks);
callbacks();
} else {
nextRoute(err);
}
} catch (err) {
callbacks(err);
}
}
})(0);
};
/**
* Respond to __OPTIONS__ method.
*
* @param {IncomingMessage} req
* @param {ServerResponse} res
* @api private
*/
Router.prototype._options = function(req, res){
var path = parse(req).pathname
, body = this._optionsFor(path).join(',');
res.set('Allow', body).send(body);
};
/**
* Return an array of HTTP verbs or "options" for `path`.
*
* @param {String} path
* @return {Array}
* @api private
*/
Router.prototype._optionsFor = function(path){
var self = this;
return methods.filter(function(method){
var routes = self.map[method];
if (!routes || 'options' == method) return;
for (var i = 0, len = routes.length; i < len; ++i) {
if (routes[i].match(path)) return true;
}
}).map(function(method){
return method.toUpperCase();
});
};
/**
* Attempt to match a route for `req`
* with optional starting index of `i`
* defaulting to 0.
*
* @param {IncomingMessage} req
* @param {Number} i
* @return {Route}
* @api private
*/
Router.prototype.matchRequest = function(req, i, head){
var method = req.method.toLowerCase()
, url = parse(req)
, path = url.pathname
, routes = this.map
, i = i || 0
, route;
// HEAD support
if (!head && 'head' == method) {
route = this.matchRequest(req, i, true);
if (route) return route;
method = 'get';
}
// routes for this method
if (routes = routes[method]) {
// matching routes
for (var len = routes.length; i < len; ++i) {
route = routes[i];
if (route.match(path)) {
req._route_index = i;
return route;
}
}
}
};
/**
* Attempt to match a route for `method`
* and `url` with optional starting
* index of `i` defaulting to 0.
*
* @param {String} method
* @param {String} url
* @param {Number} i
* @return {Route}
* @api private
*/
Router.prototype.match = function(method, url, i, head){
var req = { method: method, url: url };
return this.matchRequest(req, i, head);
};
/**
* Route `method`, `path`, and one or more callbacks.
*
* @param {String} method
* @param {String} path
* @param {Function} callback...
* @return {Router} for chaining
* @api private
*/
Router.prototype.route = function(method, path, callbacks){
var method = method.toLowerCase()
, callbacks = utils.flatten([].slice.call(arguments, 2));
// ensure path was given
if (!path) throw new Error('Router#' + method + '() requires a path');
// ensure all callbacks are functions
callbacks.forEach(function(fn){
if ('function' == typeof fn) return;
var type = {}.toString.call(fn);
var msg = '.' + method + '() requires callback functions but got a ' + type;
throw new Error(msg);
});
// create the route
debug('defined %s %s', method, path);
var route = new Route(method, path, callbacks, {
sensitive: this.caseSensitive,
strict: this.strict
});
// add it
(this.map[method] = this.map[method] || []).push(route);
return this;
};
methods.forEach(function(method){
Router.prototype[method] = function(path){
var args = [method].concat([].slice.call(arguments));
this.route.apply(this, args);
return this;
};
});
| {
"pile_set_name": "Github"
} |
CFLAGS = -O0 -Wall -Wno-misleading-indentation
OBJ_DIR = elf
TEST_DIR = tests
TEST_SRC = $(wildcard $(TEST_DIR)/*.c)
TEST_OBJ = $(TEST_SRC:.c=.o)
BIN = amacc
EXEC = $(BIN) $(BIN)-native
include mk/arm.mk
include mk/common.mk
include mk/python.mk
## Build AMaCC
all: $(EXEC)
$(BIN): $(BIN).c
$(VECHO) " CC+LD\t\t$@\n"
$(Q)$(ARM_CC) $(CFLAGS) -o $@ $< -g -ldl
$(BIN)-native: $(BIN).c
$(VECHO) " CC+LD\t\t$@\n"
$(Q)$(CC) $(CFLAGS) -o $@ $< \
-Wno-pointer-to-int-cast -Wno-int-to-pointer-cast -Wno-format \
-ldl
## Run tests and show message
check: $(EXEC) $(TEST_OBJ)
$(VECHO) "[ C to IR translation ]"
$(Q)./$(BIN)-native -s tests/arginc.c | diff tests/arginc.list - \
&& $(call pass)
$(VECHO) "[ JIT compilation + execution ]"
$(Q)if [ "$(shell $(ARM_EXEC) ./$(BIN) tests/hello.c)" = "hello, world" ]; then \
$(call pass); \
fi
$(VECHO) "[ ELF generation ]"
$(Q)$(ARM_EXEC) ./$(BIN) -o $(OBJ_DIR)/hello tests/hello.c
$(Q)if [ "$(shell $(ARM_EXEC) $(OBJ_DIR)/hello)" = "hello, world" ]; then \
$(call pass); \
fi
$(VECHO) "[ nested/self compilation ]"
$(Q)if [ "$(shell $(ARM_EXEC) ./$(BIN) $(BIN).c tests/hello.c)" = "hello, world" ]; then \
$(call pass); \
fi
$(VECHO) "[ Compatibility with GCC/Arm ] "
$(Q)$(PYTHON) runtest.py || echo
$(OBJ_DIR)/$(BIN): $(BIN)
$(VECHO) " SelfCC\t$@\n"
$(Q)$(ARM_EXEC) ./$^ -o $@ $(BIN).c
SHELL_HACK := $(shell mkdir -p $(OBJ_DIR))
$(TEST_DIR)/%.o: $(TEST_DIR)/%.c $(BIN) $(OBJ_DIR)/$(BIN)
$(VECHO) "[*** verify $< <JIT> *******]\n"
$(Q)$(ARM_EXEC) ./$(BIN) $< 2 $(REDIR)
$(VECHO) "[*** verify $< <ELF> *******]\n"
$(Q)$(ARM_EXEC) ./$(BIN) -o $(OBJ_DIR)/$(notdir $(basename $<)) $< $(REDIR)
$(Q)$(ARM_EXEC) $(OBJ_DIR)/$(notdir $(basename $<)) 2 $(REDIR)
$(VECHO) "[*** verify $< <ELF-self> **]\n"
$(Q)$(ARM_EXEC) ./$(OBJ_DIR)/$(BIN) $< 2 $(REDIR)
$(Q)$(call pass,$<)
## Print available build targets
help:
@cat $(MAKEFILE_LIST) | \
awk '/^##.*$$/{l1=$$0;getline;l2=(l1 "##" $$0); print l2 $$0}' | awk -F"##" '{split($$3,t,":");printf "\033[36m%-11s\033[0m %s\n",t[1],$$2}'
## Dump assembly from source file. Usage: "make dump-ir FILE=tests/hello.c"
dump-ir: $(BIN)
@$(ARM_EXEC) $(BIN) -s $(FILE)
## Remove all generated files
clean:
$(RM) $(EXEC) $(OBJ_DIR)/* elf/* out-gcc/*
| {
"pile_set_name": "Github"
} |
# Build an installer for Windows
import argparse
import os
import shutil
import sys
import platform
import pip
from nsist import main as pynsist
from gitlabpypi import gitlab_pypi_server
PKGS_DIR = 'pynsist_pkgs'
def test_platform():
if (sys.platform != 'win32' or platform.machine() != 'AMD64'
or (sys.version_info.major, sys.version_info.minor) != (3, 5)):
raise SystemExit('Running on wrong platform/interpreter')
def find_tox_sdist():
tox_dist_dir = os.path.join('.tox', 'dist')
sdist, = os.listdir(tox_dist_dir)
assert sdist.endswith('.zip') or sdist.endswith('.tar.gz')
return os.path.join(tox_dist_dir, sdist)
def pip_install(*distributions):
rc = pip.main(['install', '--target={}'.format(PKGS_DIR), *distributions])
if rc != 0:
raise SystemExit('pip install failed')
parser = argparse.ArgumentParser(description='Create a Windows installer.')
parser.add_argument('distribution', type=str, nargs='?',
help='requirement specifier or distribution archive for '
'the rinohtype version to include in the installer')
parser.add_argument('-t', '--use-tox-sdist', action='store_true',
help='install the tox-built distribution')
parser.add_argument('-p', '--pro', action='store_true',
help='build a Pro version installer (with DITA support)')
if __name__ == '__main__':
args = parser.parse_args()
test_platform()
if os.path.exists('build'):
shutil.rmtree('build')
if os.path.exists(PKGS_DIR):
shutil.rmtree(PKGS_DIR)
os.mkdir(PKGS_DIR)
if args.use_tox_sdist:
assert args.distribution is None
rinohtype_dist = find_tox_sdist()
else:
assert args.distribution is not None
rinohtype_dist = args.distribution
pip_install('pygments', rinohtype_dist)
if args.pro:
with gitlab_pypi_server() as index_url:
pip_install('--extra-index-url', index_url, 'rinoh-frontend-dita')
pynsist(['wininst.cfg'])
| {
"pile_set_name": "Github"
} |
# Generated by superflore -- DO NOT EDIT
#
# Copyright Open Source Robotics Foundation
inherit ros_distro_rolling
inherit ros_superflore_generated
DESCRIPTION = "dummy robot bringup"
AUTHOR = "Karsten Knese <[email protected]>"
HOMEPAGE = "https://wiki.ros.org"
SECTION = "devel"
LICENSE = "Apache-2.0"
LIC_FILES_CHKSUM = "file://package.xml;beginline=10;endline=10;md5=12c26a18c7f493fdc7e8a93b16b7c04f"
ROS_CN = "demos"
ROS_BPN = "dummy_robot_bringup"
ROS_BUILD_DEPENDS = ""
ROS_BUILDTOOL_DEPENDS = " \
ament-cmake-native \
"
ROS_EXPORT_DEPENDS = ""
ROS_BUILDTOOL_EXPORT_DEPENDS = ""
ROS_EXEC_DEPENDS = " \
ament-index-python \
dummy-map-server \
dummy-sensors \
launch \
launch-ros \
robot-state-publisher \
"
# Currently informational only -- see http://www.ros.org/reps/rep-0149.html#dependency-tags.
ROS_TEST_DEPENDS = " \
ament-cmake-gtest \
ament-lint-auto \
ament-lint-common \
"
DEPENDS = "${ROS_BUILD_DEPENDS} ${ROS_BUILDTOOL_DEPENDS}"
# Bitbake doesn't support the "export" concept, so build them as if we needed them to build this package (even though we actually
# don't) so that they're guaranteed to have been staged should this package appear in another's DEPENDS.
DEPENDS += "${ROS_EXPORT_DEPENDS} ${ROS_BUILDTOOL_EXPORT_DEPENDS}"
RDEPENDS_${PN} += "${ROS_EXEC_DEPENDS}"
# matches with: https://github.com/ros2-gbp/demos-release/archive/release/rolling/dummy_robot_bringup/0.10.0-1.tar.gz
ROS_BRANCH ?= "branch=release/rolling/dummy_robot_bringup"
SRC_URI = "git://github.com/ros2-gbp/demos-release;${ROS_BRANCH};protocol=https"
SRCREV = "9959ebbb12ad3868ad75c41ff87be72364d99a8a"
S = "${WORKDIR}/git"
ROS_BUILD_TYPE = "ament_cmake"
inherit ros_${ROS_BUILD_TYPE}
| {
"pile_set_name": "Github"
} |
/*
* 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.wicket.examples.images;
import org.apache.wicket.Page;
import org.apache.wicket.examples.WicketExampleApplication;
import org.apache.wicket.markup.html.image.resource.DefaultButtonImageResource;
/**
* Application class for the linkomatic example.
*
* @author Jonathan Locke
*/
public class ImagesApplication extends WicketExampleApplication
{
/**
* Constructor
*/
public ImagesApplication()
{
}
/**
* @see org.apache.wicket.Application#getHomePage()
*/
@Override
public Class<? extends Page> getHomePage()
{
return Home.class;
}
/**
* @see org.apache.wicket.examples.WicketExampleApplication#init()
*/
@Override
protected void init()
{
super.init();
getSharedResources().add("cancelButton", new DefaultButtonImageResource("Cancel"));
}
}
| {
"pile_set_name": "Github"
} |
/*
* 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.dubbo.common.store.support;
import org.apache.dubbo.common.store.DataStore;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class SimpleDataStore implements DataStore {
// <component name or id, <data-name, data-value>>
private ConcurrentMap<String, ConcurrentMap<String, Object>> data =
new ConcurrentHashMap<String, ConcurrentMap<String, Object>>();
@Override
public Map<String, Object> get(String componentName) {
ConcurrentMap<String, Object> value = data.get(componentName);
if (value == null) {
return new HashMap<String, Object>();
}
return new HashMap<String, Object>(value);
}
@Override
public Object get(String componentName, String key) {
if (!data.containsKey(componentName)) {
return null;
}
return data.get(componentName).get(key);
}
@Override
public void put(String componentName, String key, Object value) {
Map<String, Object> componentData = data.computeIfAbsent(componentName, k -> new ConcurrentHashMap<>());
componentData.put(key, value);
}
@Override
public void remove(String componentName, String key) {
if (!data.containsKey(componentName)) {
return;
}
data.get(componentName).remove(key);
}
}
| {
"pile_set_name": "Github"
} |
<?php
#################################################################################
## -= YOU MAY NOT REMOVE OR CHANGE THIS NOTICE =- ##
## --------------------------------------------------------------------------- ##
## Filename cp.php ##
## Developed by: G3n3s!s & JimJam & LoppyLukas ##
## License: TravianX Project ##
## Copyright: TravianX (c) 2010-2011. All rights reserved. ##
## ##
#################################################################################
$cp0 = array(
1 => 0,
2 => 500,
3 => 2600,
4 => 6700,
5 => 12900,
6 => 21600,
7 => 32900,
8 => 46000,
9 => 63000,
10 => 83500,
11 => 106400,
12 => 132500,
13 => 161900,
14 => 194600,
15 => 230700,
16 => 270400,
17 => 313700,
18 => 360600,
19 => 411300,
20 => 465700,
21 => 524000,
22 => 586300,
23 => 652500,
24 => 722700,
25 => 797000,
26 => 875500,
27 => 958200,
28 => 1045000,
29 => 1136200,
30 => 1231700,
31 => 1316000,
32 => 1435900,
33 => 1435900,
34 => 1658000,
35 => 1775800,
36 => 1898300,
37 => 2025300,
38 => 2157100,
39 => 2293500,
40 => 2434700,
41 => 2580700,
42 => 2731500,
43 => 2887200,
44 => 3047700,
45 => 3213200,
46 => 3383700,
47 => 3559100,
48 => 3739600,
49 => 3925100,
50 => 4115800,
51 => 4311500,
52 => 4512400,
53 => 4718500,
54 => 4929800,
55 => 5146400,
56 => 5368300,
57 => 5595400,
58 => 5827900,
59 => 6065700,
60 => 6309000,
61 => 6557600,
62 => 6811700,
63 => 7071300,
64 => 7336400,
65 => 7607000,
66 => 7883100,
67 => 8164900,
68 => 8452200,
69 => 8745200,
70 => 9043800,
71 => 9348100,
72 => 9659100,
73 => 9973900,
74 => 10295400,
75 => 10622600,
76 => 10955700,
77 => 11294600,
78 => 11639300,
79 => 11989900,
80 => 12346400,
81 => 12708800,
82 => 13077200,
83 => 13451500,
84 => 13831800,
85 => 14218100,
86 => 14610400,
87 => 15008800,
88 => 15413200,
89 => 15823700,
90 => 16240400,
91 => 16663100,
92 => 17092000,
93 => 17527100,
94 => 17968400,
95 => 18415900,
96 => 18869600,
97 => 19329600,
98 => 19795800,
99 => 20268400,
100 => 20747200,
101 => 21232400,
102 => 21723900,
103 => 22221800,
104 => 22726100,
105 => 23236800,
106 => 23753900,
107 => 24277400,
108 => 24807400,
109 => 25343900,
110 => 25886900,
111 => 26436400,
112 => 26992400,
113 => 27555000,
114 => 28124100,
115 => 28699900,
116 => 29282200,
117 => 29871200,
118 => 30466800,
119 => 31069000,
120 => 31677900,
121 => 32293500,
122 => 32915900,
123 => 33544900,
124 => 34180700,
125 => 34823200);
$cp1= array(
1 => 0,
2 => 2000,
3 => 8000,
4 => 20000,
5 => 39000,
6 => 65000,
7 => 99000,
8 => 141000,
9 => 191000,
10 => 251000,
11 => 319000,
12 => 397000,
13 => 486000,
14 => 584000,
15 => 692000,
16 => 811000,
17 => 941000,
18 => 1082000,
19 => 1234000,
20 => 1397000,
21 => 1572000,
22 => 1759000,
23 => 1957000,
24 => 2168000,
25 => 2391000,
26 => 2627000,
27 => 2874000,
28 => 3135000,
29 => 3409000,
30 => 3695000,
31 => 3995000,
32 => 4308000,
33 => 4634000,
34 => 4974000,
35 => 5327000,
36 => 5695000,
37 => 6076000,
38 => 6471000,
39 => 6881000,
40 => 7304000,
41 => 7742000,
42 => 8195000,
43 => 8662000,
44 => 9143000,
45 => 9640000,
46 => 10151000,
47 => 10677000,
48 => 11219000,
49 => 11775000,
50 => 12347000,
51 => 12935000,
52 => 13537000,
53 => 14156000,
54 => 14790000,
55 => 15439000,
56 => 16105000,
57 => 16786000,
58 => 17484000,
59 => 18197000,
60 => 18927000,
61 => 19673000,
62 => 20435000,
63 => 21214000,
64 => 22009000,
65 => 22821000,
66 => 23649000,
67 => 24495000,
68 => 25357000,
69 => 26236000,
70 => 27131000,
71 => 28044000,
72 => 28974000,
73 => 29922000,
74 => 30886000,
75 => 31868000,
76 => 32867000,
77 => 33884000,
78 => 34918000,
79 => 35970000,
80 => 37039000,
81 => 38127000,
82 => 39232000,
83 => 40354000,
84 => 41495000,
85 => 42654000,
86 => 43831000,
87 => 45026000,
88 => 46240000,
89 => 47471000,
90 => 48721000,
91 => 49989000,
92 => 51276000,
93 => 52581000,
94 => 53905000,
95 => 55248000,
96 => 56609000,
97 => 57989000,
98 => 59387000,
99 => 60805000,
100 => 62242000,
101 => 63697000,
102 => 65172000,
103 => 66665000,
104 => 68178000,
105 => 69710000,
106 => 71262000,
107 => 72832000,
108 => 74422000,
109 => 76032000,
110 => 77661000,
111 => 79309000,
112 => 80977000,
113 => 82665000,
114 => 84372000,
115 => 86000000,
116 => 87847000,
117 => 89613000,
118 => 91400000,
119 => 93207000,
120 => 95034000,
121 => 96881000,
122 => 98748000,
123 => 100635000,
124 => 102542000,
125 => 104470000);
?> | {
"pile_set_name": "Github"
} |
/**
* Copyright (C) 2018-present MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the Server Side Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongo/platform/basic.h"
#include "mongo/db/storage/kv/kv_engine_test_harness.h"
#include <memory>
#include "mongo/base/init.h"
#include "mongo/db/operation_context_noop.h"
#include "mongo/db/repl/replication_coordinator_mock.h"
#include "mongo/db/service_context.h"
#include "mongo/db/service_context_test_fixture.h"
#include "mongo/db/storage/ephemeral_for_test/ephemeral_for_test_kv_engine.h"
#include "mongo/unittest/unittest.h"
namespace mongo {
namespace ephemeral_for_test {
class KVHarnessHelper : public mongo::KVHarnessHelper, public ScopedGlobalServiceContextForTest {
public:
KVHarnessHelper() {
invariant(hasGlobalServiceContext());
_engine = std::make_unique<KVEngine>();
repl::ReplicationCoordinator::set(
getGlobalServiceContext(),
std::unique_ptr<repl::ReplicationCoordinator>(new repl::ReplicationCoordinatorMock(
getGlobalServiceContext(), repl::ReplSettings())));
}
virtual KVEngine* getEngine() override {
return _engine.get();
}
virtual KVEngine* restartEngine() override {
return _engine.get();
}
private:
std::unique_ptr<KVEngine> _engine;
};
std::unique_ptr<mongo::KVHarnessHelper> makeHelper() {
return std::make_unique<KVHarnessHelper>();
}
MONGO_INITIALIZER(RegisterEphemeralForTestKVHarnessFactory)(InitializerContext*) {
KVHarnessHelper::registerFactory(makeHelper);
return Status::OK();
}
class EphemeralForTestKVEngineTest : public unittest::Test {
public:
EphemeralForTestKVEngineTest() : _helper(), _engine(_helper.getEngine()) {}
protected:
std::unique_ptr<KVHarnessHelper> helper;
KVHarnessHelper _helper;
KVEngine* _engine;
};
class OperationContextFromKVEngine : public OperationContextNoop {
public:
OperationContextFromKVEngine(KVEngine* engine)
: OperationContextNoop(engine->newRecoveryUnit()) {}
};
TEST_F(EphemeralForTestKVEngineTest, AvailableHistoryUpdate) {
NamespaceString nss("a.b");
std::string ident = "collection-1234";
std::string record = "abcd";
CollectionOptions defaultCollectionOptions;
std::unique_ptr<mongo::RecordStore> rs;
{
OperationContextFromKVEngine opCtx(_engine);
ASSERT_OK(_engine->createRecordStore(&opCtx, nss.ns(), ident, defaultCollectionOptions));
rs = _engine->getRecordStore(&opCtx, nss.ns(), ident, defaultCollectionOptions);
ASSERT(rs);
}
Timestamp lastMaster;
Timestamp currentMaster;
ASSERT_EQ(1, _engine->getHistory_forTest().size());
currentMaster = _engine->getHistory_forTest().rbegin()->first;
ASSERT_EQ(_engine->getOldestTimestamp(), currentMaster);
{
OperationContextFromKVEngine opCtx(_engine);
WriteUnitOfWork uow(&opCtx);
StatusWith<RecordId> res =
rs->insertRecord(&opCtx, record.c_str(), record.length() + 1, Timestamp());
ASSERT_OK(res.getStatus());
uow.commit();
}
ASSERT_EQ(1, _engine->getHistory_forTest().size());
lastMaster = currentMaster;
currentMaster = _engine->getHistory_forTest().rbegin()->first;
ASSERT_GT(currentMaster, lastMaster);
ASSERT_EQ(_engine->getOldestTimestamp(), currentMaster);
}
TEST_F(EphemeralForTestKVEngineTest, PinningOldestTimestampWithReadTransaction) {
NamespaceString nss("a.b");
std::string ident = "collection-1234";
std::string record = "abcd";
CollectionOptions defaultCollectionOptions;
std::unique_ptr<mongo::RecordStore> rs;
{
OperationContextFromKVEngine opCtx(_engine);
ASSERT_OK(_engine->createRecordStore(&opCtx, nss.ns(), ident, defaultCollectionOptions));
rs = _engine->getRecordStore(&opCtx, nss.ns(), ident, defaultCollectionOptions);
ASSERT(rs);
}
// _availableHistory starts off with master.
ASSERT_EQ(1, _engine->getHistory_forTest().size());
RecordId loc;
{
OperationContextFromKVEngine opCtx(_engine);
WriteUnitOfWork uow(&opCtx);
StatusWith<RecordId> res =
rs->insertRecord(&opCtx, record.c_str(), record.length() + 1, Timestamp());
ASSERT_OK(res.getStatus());
loc = res.getValue();
uow.commit();
}
OperationContextFromKVEngine opCtxRead(_engine);
RecordData rd;
ASSERT(rs->findRecord(&opCtxRead, loc, &rd));
{
OperationContextFromKVEngine opCtx(_engine);
WriteUnitOfWork uow(&opCtx);
StatusWith<RecordId> res =
rs->insertRecord(&opCtx, record.c_str(), record.length() + 1, Timestamp());
ASSERT_OK(res.getStatus());
uow.commit();
}
// Open read transaction prevents deletion of history.
ASSERT_EQ(2, _engine->getHistory_forTest().size());
ASSERT_GT(_engine->getHistory_forTest().rbegin()->first, _engine->getOldestTimestamp());
}
TEST_F(EphemeralForTestKVEngineTest, SettingOldestTimestampClearsHistory) {
NamespaceString nss("a.b");
std::string ident = "collection-1234";
std::string record = "abcd";
CollectionOptions defaultCollectionOptions;
std::unique_ptr<mongo::RecordStore> rs;
{
OperationContextFromKVEngine opCtx(_engine);
ASSERT_OK(_engine->createRecordStore(&opCtx, nss.ns(), ident, defaultCollectionOptions));
rs = _engine->getRecordStore(&opCtx, nss.ns(), ident, defaultCollectionOptions);
ASSERT(rs);
}
// _availableHistory starts off with master.
ASSERT_EQ(1, _engine->getHistory_forTest().size());
RecordId loc;
{
OperationContextFromKVEngine opCtx(_engine);
WriteUnitOfWork uow(&opCtx);
StatusWith<RecordId> res =
rs->insertRecord(&opCtx, record.c_str(), record.length() + 1, Timestamp());
ASSERT_OK(res.getStatus());
loc = res.getValue();
uow.commit();
}
OperationContextFromKVEngine opCtxRead(_engine);
RecordData rd;
ASSERT(rs->findRecord(&opCtxRead, loc, &rd));
{
OperationContextFromKVEngine opCtx(_engine);
WriteUnitOfWork uow(&opCtx);
StatusWith<RecordId> res =
rs->insertRecord(&opCtx, record.c_str(), record.length() + 1, Timestamp());
ASSERT_OK(res.getStatus());
uow.commit();
}
ASSERT_EQ(2, _engine->getHistory_forTest().size());
_engine->setOldestTimestamp(_engine->getHistory_forTest().rbegin()->first, false);
ASSERT_EQ(1, _engine->getHistory_forTest().size());
}
TEST_F(EphemeralForTestKVEngineTest, SettingOldestTimestampToMax) {
NamespaceString nss("a.b");
std::string ident = "collection-1234";
std::string record = "abcd";
CollectionOptions defaultCollectionOptions;
std::unique_ptr<mongo::RecordStore> rs;
{
OperationContextFromKVEngine opCtx(_engine);
ASSERT_OK(_engine->createRecordStore(&opCtx, nss.ns(), ident, defaultCollectionOptions));
rs = _engine->getRecordStore(&opCtx, nss.ns(), ident, defaultCollectionOptions);
ASSERT(rs);
}
{
OperationContextFromKVEngine opCtx(_engine);
WriteUnitOfWork uow(&opCtx);
StatusWith<RecordId> res =
rs->insertRecord(&opCtx, record.c_str(), record.length() + 1, Timestamp());
ASSERT_OK(res.getStatus());
uow.commit();
}
// Check that setting oldest to Timestamp::max() does not clear history.
ASSERT_GTE(_engine->getHistory_forTest().size(), 1);
ASSERT_LT(_engine->getHistory_forTest().rbegin()->first, Timestamp::max());
_engine->setOldestTimestamp(Timestamp::max(), true);
ASSERT_GTE(_engine->getHistory_forTest().size(), 1);
ASSERT_EQ(Timestamp::max(), _engine->getHistory_forTest().rbegin()->first);
}
TEST_F(EphemeralForTestKVEngineTest, CleanHistoryWithOpenTransaction) {
NamespaceString nss("a.b");
std::string ident = "collection-1234";
std::string record = "abcd";
CollectionOptions defaultCollectionOptions;
std::unique_ptr<mongo::RecordStore> rs;
{
OperationContextFromKVEngine opCtx(_engine);
ASSERT_OK(_engine->createRecordStore(&opCtx, nss.ns(), ident, defaultCollectionOptions));
rs = _engine->getRecordStore(&opCtx, nss.ns(), ident, defaultCollectionOptions);
ASSERT(rs);
}
// _availableHistory starts off with master.
ASSERT_EQ(1, _engine->getHistory_forTest().size());
RecordId loc;
{
OperationContextFromKVEngine opCtx(_engine);
WriteUnitOfWork uow(&opCtx);
StatusWith<RecordId> res =
rs->insertRecord(&opCtx, record.c_str(), record.length() + 1, Timestamp());
ASSERT_OK(res.getStatus());
loc = res.getValue();
uow.commit();
}
OperationContextFromKVEngine opCtxRead(_engine);
Timestamp readTime1 = _engine->getHistory_forTest().rbegin()->first;
RecordData rd;
ASSERT(rs->findRecord(&opCtxRead, loc, &rd));
{
OperationContextFromKVEngine opCtx(_engine);
WriteUnitOfWork uow(&opCtx);
StatusWith<RecordId> res =
rs->insertRecord(&opCtx, record.c_str(), record.length() + 1, Timestamp());
ASSERT_OK(res.getStatus());
uow.commit();
}
Timestamp readTime2 = _engine->getHistory_forTest().rbegin()->first;
{
OperationContextFromKVEngine opCtx(_engine);
WriteUnitOfWork uow(&opCtx);
StatusWith<RecordId> res =
rs->insertRecord(&opCtx, record.c_str(), record.length() + 1, Timestamp());
ASSERT_OK(res.getStatus());
uow.commit();
}
Timestamp readTime3 = _engine->getHistory_forTest().rbegin()->first;
_engine->cleanHistory();
// use_count() should be {2, 1, 2} without the copy from getHistory_forTest().
ASSERT_EQ(3, _engine->getHistory_forTest().size());
ASSERT_EQ(3, _engine->getHistory_forTest().at(readTime1).use_count());
ASSERT_EQ(2, _engine->getHistory_forTest().at(readTime2).use_count());
ASSERT_EQ(3, _engine->getHistory_forTest().at(readTime3).use_count());
}
TEST_F(EphemeralForTestKVEngineTest, ReadOlderSnapshotsSimple) {
NamespaceString nss("a.b");
std::string ident = "collection-1234";
std::string record = "abcd";
CollectionOptions defaultCollectionOptions;
std::unique_ptr<mongo::RecordStore> rs;
{
OperationContextFromKVEngine opCtx(_engine);
ASSERT_OK(_engine->createRecordStore(&opCtx, nss.ns(), ident, defaultCollectionOptions));
rs = _engine->getRecordStore(&opCtx, nss.ns(), ident, defaultCollectionOptions);
ASSERT(rs);
}
// Pin oldest timestamp with a read transaction.
OperationContextFromKVEngine pinningOldest(_engine);
ASSERT(!rs->findRecord(&pinningOldest, RecordId(), nullptr));
// Set readFrom to timestamp with no committed transactions.
Timestamp readFrom = _engine->getHistory_forTest().rbegin()->first;
OperationContextFromKVEngine opCtx(_engine);
WriteUnitOfWork uow1(&opCtx);
StatusWith<RecordId> res1 =
rs->insertRecord(&opCtx, record.c_str(), record.length() + 1, Timestamp());
ASSERT_OK(res1.getStatus());
RecordId loc1 = res1.getValue();
uow1.commit();
WriteUnitOfWork uow2(&opCtx);
StatusWith<RecordId> res2 =
rs->insertRecord(&opCtx, record.c_str(), record.length() + 1, Timestamp());
ASSERT_OK(res2.getStatus());
RecordId loc2 = res2.getValue();
uow2.commit();
RecordData rd;
opCtx.recoveryUnit()->abandonSnapshot();
opCtx.recoveryUnit()->setTimestampReadSource(RecoveryUnit::ReadSource::kProvided, readFrom);
ASSERT(!rs->findRecord(&opCtx, loc1, &rd));
ASSERT(!rs->findRecord(&opCtx, loc2, &rd));
opCtx.recoveryUnit()->abandonSnapshot();
opCtx.recoveryUnit()->setTimestampReadSource(RecoveryUnit::ReadSource::kNoTimestamp);
ASSERT(rs->findRecord(&opCtx, loc1, &rd));
ASSERT(rs->findRecord(&opCtx, loc2, &rd));
}
TEST_F(EphemeralForTestKVEngineTest, ReadOutdatedSnapshot) {
NamespaceString nss("a.b");
std::string ident = "collection-1234";
std::string record = "abcd";
CollectionOptions defaultCollectionOptions;
std::unique_ptr<mongo::RecordStore> rs;
{
OperationContextFromKVEngine opCtx(_engine);
ASSERT_OK(_engine->createRecordStore(&opCtx, nss.ns(), ident, defaultCollectionOptions));
rs = _engine->getRecordStore(&opCtx, nss.ns(), ident, defaultCollectionOptions);
ASSERT(rs);
}
RecordId loc1;
{
OperationContextFromKVEngine opCtx(_engine);
WriteUnitOfWork uow(&opCtx);
StatusWith<RecordId> res =
rs->insertRecord(&opCtx, record.c_str(), record.length() + 1, Timestamp());
ASSERT_OK(res.getStatus());
loc1 = res.getValue();
uow.commit();
}
OperationContextFromKVEngine opCtxRead(_engine);
RecordData rd;
ASSERT(rs->findRecord(&opCtxRead, loc1, &rd));
Timestamp readFrom = _engine->getHistory_forTest().rbegin()->first;
RecordId loc2;
{
OperationContextFromKVEngine opCtx(_engine);
WriteUnitOfWork uow(&opCtx);
StatusWith<RecordId> res =
rs->insertRecord(&opCtx, record.c_str(), record.length() + 1, Timestamp());
ASSERT_OK(res.getStatus());
loc2 = res.getValue();
uow.commit();
}
ASSERT(rs->findRecord(&opCtxRead, loc1, &rd));
opCtxRead.recoveryUnit()->abandonSnapshot();
opCtxRead.recoveryUnit()->setTimestampReadSource(RecoveryUnit::ReadSource::kProvided, readFrom);
ASSERT_THROWS_CODE(
rs->findRecord(&opCtxRead, loc1, &rd), DBException, ErrorCodes::SnapshotTooOld);
}
TEST_F(EphemeralForTestKVEngineTest, SetReadTimestampBehindOldestTimestamp) {
NamespaceString nss("a.b");
std::string ident = "collection-1234";
std::string record = "abcd";
CollectionOptions defaultCollectionOptions;
std::unique_ptr<mongo::RecordStore> rs;
{
OperationContextFromKVEngine opCtx(_engine);
ASSERT_OK(_engine->createRecordStore(&opCtx, nss.ns(), ident, defaultCollectionOptions));
rs = _engine->getRecordStore(&opCtx, nss.ns(), ident, defaultCollectionOptions);
ASSERT(rs);
}
RecordId loc1;
{
OperationContextFromKVEngine opCtx(_engine);
WriteUnitOfWork uow(&opCtx);
StatusWith<RecordId> res =
rs->insertRecord(&opCtx, record.c_str(), record.length() + 1, Timestamp());
ASSERT_OK(res.getStatus());
loc1 = res.getValue();
uow.commit();
}
RecordData rd;
Timestamp readFrom = _engine->getHistory_forTest().begin()->first;
OperationContextFromKVEngine opCtx(_engine);
WriteUnitOfWork uow(&opCtx);
StatusWith<RecordId> res =
rs->insertRecord(&opCtx, record.c_str(), record.length() + 1, Timestamp());
ASSERT_OK(res.getStatus());
RecordId loc2 = res.getValue();
uow.commit();
opCtx.recoveryUnit()->setTimestampReadSource(RecoveryUnit::ReadSource::kProvided, readFrom);
_engine->setOldestTimestamp(Timestamp::max(), true);
ASSERT_THROWS_CODE(rs->findRecord(&opCtx, loc2, &rd), DBException, ErrorCodes::SnapshotTooOld);
opCtx.recoveryUnit()->abandonSnapshot();
opCtx.recoveryUnit()->setTimestampReadSource(RecoveryUnit::ReadSource::kNoTimestamp);
ASSERT(rs->findRecord(&opCtx, loc1, &rd));
ASSERT(rs->findRecord(&opCtx, loc2, &rd));
}
} // namespace ephemeral_for_test
} // namespace mongo
| {
"pile_set_name": "Github"
} |
.loading {
display: inline-block;
}
.loading-color {
width: 60px;
height: 24px;
background: url(http://img01.taobaocdn.com/tps/i1/T1Z6DDXllbXXbb3zDj-60-24.gif) no-repeat;
}
.loading-color-mini {
width: 30px;
height: 12px;
background: url(http://img04.taobaocdn.com/tps/i4/T1h7YDXdddXXcntf6c-30-12.gif) no-repeat;
}
.loading-grey-border {
width: 40px;
height: 18px;
background: url(http://img03.taobaocdn.com/tps/i3/T1cN_yXgBnXXc.LCDe-40-18.gif) no-repeat;
}
.loading-grey {
width: 40px;
height: 18px;
background: url(http://img02.taobaocdn.com/tps/i2/T19ZHDXf4fXXc.LCDe-40-18.gif) no-repeat;
}
| {
"pile_set_name": "Github"
} |
import Avatar from "@material-ui/core/Avatar";
import { makeStyles } from "@material-ui/core/styles";
import TableCell, { TableCellProps } from "@material-ui/core/TableCell";
import Cached from "@material-ui/icons/Cached";
import classNames from "classnames";
import React from "react";
import Image from "../../icons/Image";
export const AVATAR_MARGIN = 32;
const useStyles = makeStyles(
theme => ({
alignRight: {
justifyContent: "flex-end"
},
avatar: {
background: "none",
border: `1px solid ${theme.palette.divider}`,
borderRadius: 2,
color: "#bdbdbd",
display: "inline-flex",
padding: theme.spacing(0.5)
},
children: {
alignSelf: "center",
marginLeft: theme.spacing(2),
width: "100%"
},
content: {
alignItems: "center",
display: "flex"
},
root: {
"&:not(first-child)": {
paddingLeft: 0
},
paddingRight: theme.spacing(3),
width: "1%"
}
}),
{ name: "TableCellAvatar" }
);
interface TableCellAvatarProps extends TableCellProps {
className?: string;
thumbnail?: string;
alignRight?: boolean;
avatarProps?: string;
children?: React.ReactNode | React.ReactNodeArray;
}
const TableCellAvatar: React.FC<TableCellAvatarProps> = props => {
const {
children,
className,
alignRight,
thumbnail,
avatarProps,
...rest
} = props;
const classes = useStyles(props);
return (
<TableCell className={classNames(classes.root, className)} {...rest}>
<div
className={classNames(classes.content, {
[classes.alignRight]: alignRight
})}
>
{thumbnail === undefined ? (
<Avatar className={classNames(classes.avatar, avatarProps)}>
<Cached color="primary" />
</Avatar>
) : thumbnail === null ? (
<Avatar className={classNames(classes.avatar, avatarProps)}>
<Image color="primary" />
</Avatar>
) : (
<Avatar
className={classNames(classes.avatar, avatarProps)}
src={thumbnail}
/>
)}
{!alignRight && <div className={classes.children}>{children}</div>}
</div>
</TableCell>
);
};
TableCellAvatar.displayName = "TableCellAvatar";
export default TableCellAvatar;
| {
"pile_set_name": "Github"
} |
using NHMCore;
using NHMCore.Utils;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace NiceHashMiner.Views.Common
{
/// <summary>
/// Interaction logic for EnterWalletDialog.xaml
/// </summary>
public partial class EnterWalletDialog : UserControl
{
public EnterWalletDialog()
{
InitializeComponent();
WindowUtils.Translate(this);
}
private void BtcTextValidation()
{
var trimmedBtcText = textBoxBTCAddress.Text.Trim();
var btcOK = CredentialValidators.ValidateBitcoinAddress(trimmedBtcText);
SaveButton.IsEnabled = btcOK;
if (btcOK)
{
textBoxBTCAddress.Style = Application.Current.FindResource("InputBoxGood") as Style;
textBoxBTCAddress.BorderBrush = (Brush)Application.Current.FindResource("NastyGreenBrush");
}
else
{
textBoxBTCAddress.Style = Application.Current.FindResource("InputBoxBad") as Style;
textBoxBTCAddress.BorderBrush = (Brush)Application.Current.FindResource("RedDangerColorBrush");
}
}
private void TextBoxBitcoinAddress_TextChanged(object sender, TextChangedEventArgs e)
{
BtcTextValidation();
}
private void TextBoxBitcoinAddress_KeyUp(object sender, KeyEventArgs e)
{
BtcTextValidation();
}
private void TextBoxBitcoinAddress_LostFocus(object sender, RoutedEventArgs e)
{
BtcTextValidation();
}
private void AddressHyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
{
Process.Start(e.Uri.AbsoluteUri);
}
private void CloseDialog(object sender, RoutedEventArgs e)
{
CustomDialogManager.HideCurrentModal();
}
private async void SaveButtonClicked(object sender, RoutedEventArgs e)
{
var trimmedBtcText = textBoxBTCAddress.Text.Trim();
var result = await ApplicationStateManager.SetBTCIfValidOrDifferent(trimmedBtcText);
if (ApplicationStateManager.SetResult.INVALID == result)
{
textBoxBTCAddress.Style = Application.Current.FindResource("InputBoxBad") as Style;
textBoxBTCAddress.BorderBrush = (Brush)Application.Current.FindResource("RedDangerColorBrush");
}
else
{
CustomDialogManager.HideCurrentModal();
textBoxBTCAddress.Style = Application.Current.FindResource("InputBoxGood") as Style;
textBoxBTCAddress.BorderBrush = (Brush)Application.Current.FindResource("NastyGreenBrush");
}
}
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2019 WeBank
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Constants for token types
*/
export default {
WHITESPACE: 'whitespace',
WORD: 'word',
STRING: 'string',
RESERVED: 'reserved',
RESERVED_TOPLEVEL: 'reserved-toplevel',
RESERVED_NEWLINE: 'reserved-newline',
OPERATOR: 'operator',
OPEN_PAREN: 'open-paren',
CLOSE_PAREN: 'close-paren',
LINE_COMMENT: 'line-comment',
BLOCK_COMMENT: 'block-comment',
NUMBER: 'number',
PLACEHOLDER: 'placeholder',
};
| {
"pile_set_name": "Github"
} |
var apply = require('./_apply'),
arrayMap = require('./_arrayMap'),
baseIteratee = require('./_baseIteratee'),
baseRest = require('./_baseRest'),
baseUnary = require('./_baseUnary'),
flatRest = require('./_flatRest');
/**
* Creates a function like `_.over`.
*
* @private
* @param {Function} arrayFunc The function to iterate over iteratees.
* @returns {Function} Returns the new over function.
*/
function createOver(arrayFunc) {
return flatRest(function(iteratees) {
iteratees = arrayMap(iteratees, baseUnary(baseIteratee));
return baseRest(function(args) {
var thisArg = this;
return arrayFunc(iteratees, function(iteratee) {
return apply(iteratee, thisArg, args);
});
});
});
}
module.exports = createOver;
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2017, 2020, Oracle and/or its affiliates. All rights reserved.
*/
/*
* 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.sun.org.apache.bcel.internal.generic;
import java.util.StringTokenizer;
import com.sun.org.apache.bcel.internal.Const;
import com.sun.org.apache.bcel.internal.classfile.Constant;
import com.sun.org.apache.bcel.internal.classfile.ConstantCP;
import com.sun.org.apache.bcel.internal.classfile.ConstantPool;
/**
* Super class for the INVOKExxx family of instructions.
*
* @LastModified: Jan 2020
*/
public abstract class InvokeInstruction extends FieldOrMethod implements ExceptionThrower,
StackConsumer, StackProducer {
/**
* Empty constructor needed for Instruction.readInstruction.
* Not to be used otherwise.
*/
InvokeInstruction() {
}
/**
* @param index to constant pool
*/
protected InvokeInstruction(final short opcode, final int index) {
super(opcode, index);
}
/**
* @return mnemonic for instruction with symbolic references resolved
*/
@Override
public String toString( final ConstantPool cp ) {
final Constant c = cp.getConstant(super.getIndex());
final StringTokenizer tok = new StringTokenizer(cp.constantToString(c));
final String opcodeName = Const.getOpcodeName(super.getOpcode());
final StringBuilder sb = new StringBuilder(opcodeName);
if (tok.hasMoreTokens()) {
sb.append(" ");
sb.append(tok.nextToken().replace('.', '/'));
if (tok.hasMoreTokens()) {
sb.append(tok.nextToken());
}
}
return sb.toString();
}
/**
* Also works for instructions whose stack effect depends on the
* constant pool entry they reference.
* @return Number of words consumed from stack by this instruction
*/
@Override
public int consumeStack( final ConstantPoolGen cpg ) {
int sum;
if ((super.getOpcode() == Const.INVOKESTATIC) || (super.getOpcode() == Const.INVOKEDYNAMIC)) {
sum = 0;
} else {
sum = 1; // this reference
}
final String signature = getSignature(cpg);
sum += Type.getArgumentTypesSize(signature);
return sum;
}
/**
* Also works for instructions whose stack effect depends on the
* constant pool entry they reference.
* @return Number of words produced onto stack by this instruction
*/
@Override
public int produceStack( final ConstantPoolGen cpg ) {
final String signature = getSignature(cpg);
return Type.getReturnTypeSize(signature);
}
/**
* This overrides the deprecated version as we know here that the referenced class
* may legally be an array.
*
* @deprecated in FieldOrMethod
*
* @return name of the referenced class/interface
* @throws IllegalArgumentException if the referenced class is an array (this should not happen)
*/
@Override
@Deprecated
public String getClassName( final ConstantPoolGen cpg ) {
final ConstantPool cp = cpg.getConstantPool();
final ConstantCP cmr = (ConstantCP) cp.getConstant(super.getIndex());
final String className = cp.getConstantString(cmr.getClassIndex(), Const.CONSTANT_Class);
return className.replace('/', '.');
}
/** @return return type of referenced method.
*/
@Override
public Type getType( final ConstantPoolGen cpg ) {
return getReturnType(cpg);
}
/** @return name of referenced method.
*/
public String getMethodName( final ConstantPoolGen cpg ) {
return getName(cpg);
}
/** @return return type of referenced method.
*/
public Type getReturnType( final ConstantPoolGen cpg ) {
return Type.getReturnType(getSignature(cpg));
}
/** @return argument types of referenced method.
*/
public Type[] getArgumentTypes( final ConstantPoolGen cpg ) {
return Type.getArgumentTypes(getSignature(cpg));
}
}
| {
"pile_set_name": "Github"
} |
---
title: Halve
github: 'https://github.com/TaylanTatli/Halve'
demo: 'http://taylantatli.github.io/Halve'
author: Taylan Tatlı
ssg:
- Jekyll
cms:
- No Cms
date: 2016-05-30T18:47:21.000Z
github_branch: master
description: Stylish Two-Column Jekyll Theme
stale: false
--- | {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!--
This is the Solr schema file. This file should be named "schema.xml" and
should be in the conf directory under the solr home
(i.e. ./solr/conf/schema.xml by default)
or located where the classloader for the Solr webapp can find it.
This example schema is the recommended starting point for users.
It should be kept correct and concise, usable out-of-the-box.
For more information, on how to customize this file, please see
http://wiki.apache.org/solr/SchemaXml
PERFORMANCE NOTE: this schema includes many optional features and should not
be used for benchmarking. To improve performance one could
- set stored="false" for all fields possible (esp large fields) when you
only need to search on the field but don't need to return the original
value.
- set indexed="false" if you don't need to search on the field, but only
return the field as a result of searching on other indexed fields.
- remove all unneeded copyField statements
- for best index size and searching performance, set "index" to false
for all general text fields, use copyField to copy them to the
catchall "text" field, and use that for searching.
- For maximum indexing performance, use the StreamingUpdateSolrServer
java client.
- Remember to run the JVM in server mode, and use a higher logging level
that avoids logging every request
-->
<schema name="sunspot" version="1.0">
<types>
<!-- field type definitions. The "name" attribute is
just a label to be used by field definitions. The "class"
attribute and any other attributes determine the real
behavior of the fieldType.
Class names starting with "solr" refer to java classes in the
org.apache.solr.analysis package.
-->
<!-- *** This fieldType is used by Sunspot! *** -->
<fieldType name="string" class="solr.StrField" omitNorms="true"/>
<!-- *** This fieldType is used by Sunspot! *** -->
<fieldType name="tdouble" class="solr.TrieDoubleField" omitNorms="true"/>
<!-- *** This fieldType is used by Sunspot! *** -->
<fieldType name="rand" class="solr.RandomSortField" omitNorms="true"/>
<!-- *** This fieldType is used by Sunspot! *** -->
<fieldType name="text" class="solr.TextField" omitNorms="false">
<analyzer>
<tokenizer class="solr.StandardTokenizerFactory"/>
<filter class="solr.StandardFilterFactory"/>
<filter class="solr.LowerCaseFilterFactory"/>
</analyzer>
</fieldType>
<!-- *** This fieldType is used by Sunspot! *** -->
<fieldType name="boolean" class="solr.BoolField" omitNorms="true"/>
<!-- *** This fieldType is used by Sunspot! *** -->
<fieldType name="date" class="solr.DateField" omitNorms="true"/>
<!-- *** This fieldType is used by Sunspot! *** -->
<fieldType name="sdouble" class="solr.SortableDoubleField" omitNorms="true"/>
<!-- *** This fieldType is used by Sunspot! *** -->
<fieldType name="sfloat" class="solr.SortableFloatField" omitNorms="true"/>
<!-- *** This fieldType is used by Sunspot! *** -->
<fieldType name="sint" class="solr.SortableIntField" omitNorms="true"/>
<!-- *** This fieldType is used by Sunspot! *** -->
<fieldType name="slong" class="solr.SortableLongField" omitNorms="true"/>
<!-- *** This fieldType is used by Sunspot! *** -->
<fieldType name="tint" class="solr.TrieIntField" omitNorms="true"/>
<!-- *** This fieldType is used by Sunspot! *** -->
<fieldType name="tfloat" class="solr.TrieFloatField" omitNorms="true"/>
<!-- *** This fieldType is used by Sunspot! *** -->
<fieldType name="tdate" class="solr.TrieDateField" omitNorms="true"/>
<fieldtype name="textComplex" class="solr.TextField" positionIncrementGap="100">
<analyzer>
<tokenizer class="com.chenlb.mmseg4j.solr.MMSegTokenizerFactory" mode="complex" dicPath="dic"/>
</analyzer>
</fieldtype>
<fieldtype name="textMaxWord" class="solr.TextField" positionIncrementGap="100">
<analyzer>
<tokenizer class="com.chenlb.mmseg4j.solr.MMSegTokenizerFactory" mode="max-word" dicPath="dic"/>
</analyzer>
</fieldtype>
</types>
<fields>
<!-- Valid attributes for fields:
name: mandatory - the name for the field
type: mandatory - the name of a previously defined type from the
<types> section
indexed: true if this field should be indexed (searchable or sortable)
stored: true if this field should be retrievable
compressed: [false] if this field should be stored using gzip compression
(this will only apply if the field type is compressable; among
the standard field types, only TextField and StrField are)
multiValued: true if this field may contain multiple values per document
omitNorms: (expert) set to true to omit the norms associated with
this field (this disables length normalization and index-time
boosting for the field, and saves some memory). Only full-text
fields or fields that need an index-time boost need norms.
termVectors: [false] set to true to store the term vector for a
given field.
When using MoreLikeThis, fields used for similarity should be
stored for best performance.
termPositions: Store position information with the term vector.
This will increase storage costs.
termOffsets: Store offset information with the term vector. This
will increase storage costs.
default: a value that should be used if no value is specified
when adding a document.
-->
<field name="complex" type="textComplex" indexed="true" stored="false"/>
<field name="text" type="textMaxWord" indexed="true" stored="false" multiValued="true"/>
<!-- *** This field is used by Sunspot! *** -->
<field name="id" stored="true" type="string" multiValued="false" indexed="true"/>
<!-- *** This field is used by Sunspot! *** -->
<field name="type" stored="false" type="string" multiValued="true" indexed="true"/>
<!-- *** This field is used by Sunspot! *** -->
<field name="class_name" stored="false" type="string" multiValued="false" indexed="true"/>
<!-- *** This field is used by Sunspot! *** -->
<!-- <field name="text" stored="false" type="string" multiValued="true" indexed="true"/> -->
<!-- *** This field is used by Sunspot! *** -->
<field name="lat" stored="true" type="tdouble" multiValued="false" indexed="true"/>
<!-- *** This field is used by Sunspot! *** -->
<field name="lng" stored="true" type="tdouble" multiValued="false" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="random_*" stored="false" type="rand" multiValued="false" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="_local*" stored="false" type="tdouble" multiValued="false" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_text" stored="false" type="text" multiValued="true" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_texts" stored="true" type="text" multiValued="true" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_b" stored="false" type="boolean" multiValued="false" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_bm" stored="false" type="boolean" multiValued="true" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_bs" stored="true" type="boolean" multiValued="false" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_bms" stored="true" type="boolean" multiValued="true" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_d" stored="false" type="date" multiValued="false" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_dm" stored="false" type="date" multiValued="true" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_ds" stored="true" type="date" multiValued="false" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_dms" stored="true" type="date" multiValued="true" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_e" stored="false" type="sdouble" multiValued="false" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_em" stored="false" type="sdouble" multiValued="true" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_es" stored="true" type="sdouble" multiValued="false" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_ems" stored="true" type="sdouble" multiValued="true" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_f" stored="false" type="sfloat" multiValued="false" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_fm" stored="false" type="sfloat" multiValued="true" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_fs" stored="true" type="sfloat" multiValued="false" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_fms" stored="true" type="sfloat" multiValued="true" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_i" stored="false" type="sint" multiValued="false" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_im" stored="false" type="sint" multiValued="true" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_is" stored="true" type="sint" multiValued="false" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_ims" stored="true" type="sint" multiValued="true" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_l" stored="false" type="slong" multiValued="false" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_lm" stored="false" type="slong" multiValued="true" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_ls" stored="true" type="slong" multiValued="false" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_lms" stored="true" type="slong" multiValued="true" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_s" stored="false" type="string" multiValued="false" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_sm" stored="false" type="string" multiValued="true" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_ss" stored="true" type="string" multiValued="false" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_sms" stored="true" type="string" multiValued="true" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_it" stored="false" type="tint" multiValued="false" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_itm" stored="false" type="tint" multiValued="true" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_its" stored="true" type="tint" multiValued="false" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_itms" stored="true" type="tint" multiValued="true" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_ft" stored="false" type="tfloat" multiValued="false" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_ftm" stored="false" type="tfloat" multiValued="true" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_fts" stored="true" type="tfloat" multiValued="false" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_ftms" stored="true" type="tfloat" multiValued="true" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_dt" stored="false" type="tdate" multiValued="false" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_dtm" stored="false" type="tdate" multiValued="true" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_dts" stored="true" type="tdate" multiValued="false" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_dtms" stored="true" type="tdate" multiValued="true" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_textv" stored="false" termVectors="true" type="text" multiValued="true" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_textsv" stored="true" termVectors="true" type="text" multiValued="true" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_et" stored="false" termVectors="true" type="tdouble" multiValued="false" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_etm" stored="false" termVectors="true" type="tdouble" multiValued="true" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_ets" stored="true" termVectors="true" type="tdouble" multiValued="false" indexed="true"/>
<!-- *** This dynamicField is used by Sunspot! *** -->
<dynamicField name="*_etms" stored="true" termVectors="true" type="tdouble" multiValued="true" indexed="true"/>
</fields>
<!-- Field to use to determine and enforce document uniqueness.
Unless this field is marked with required="false", it will be a required field
-->
<uniqueKey>id</uniqueKey>
<!-- field for the QueryParser to use when an explicit fieldname is absent -->
<defaultSearchField>text</defaultSearchField>
<!-- SolrQueryParser configuration: defaultOperator="AND|OR" -->
<solrQueryParser defaultOperator="AND"/>
<!-- copyField commands copy one field to another at the time a document
is added to the index. It's used either to index the same field differently,
or to add multiple fields to the same field for easier/faster searching. -->
<!-- <copyField source="text" dest="complex" /> -->
</schema>
| {
"pile_set_name": "Github"
} |
glabel func_80B00F64
/* 02CB4 80B00F64 27BDFFE8 */ addiu $sp, $sp, 0xFFE8 ## $sp = FFFFFFE8
/* 02CB8 80B00F68 AFBF0014 */ sw $ra, 0x0014($sp)
/* 02CBC 80B00F6C AFA40018 */ sw $a0, 0x0018($sp)
/* 02CC0 80B00F70 AFA5001C */ sw $a1, 0x001C($sp)
/* 02CC4 80B00F74 0C042F6F */ jal func_8010BDBC
/* 02CC8 80B00F78 24A420D8 */ addiu $a0, $a1, 0x20D8 ## $a0 = 000020D8
/* 02CCC 80B00F7C 24010004 */ addiu $at, $zero, 0x0004 ## $at = 00000004
/* 02CD0 80B00F80 5441001D */ bnel $v0, $at, .L80B00FF8
/* 02CD4 80B00F84 8FBF0014 */ lw $ra, 0x0014($sp)
/* 02CD8 80B00F88 0C041AF2 */ jal func_80106BC8
/* 02CDC 80B00F8C 8FA4001C */ lw $a0, 0x001C($sp)
/* 02CE0 80B00F90 10400018 */ beq $v0, $zero, .L80B00FF4
/* 02CE4 80B00F94 8FAE001C */ lw $t6, 0x001C($sp)
/* 02CE8 80B00F98 3C020001 */ lui $v0, 0x0001 ## $v0 = 00010000
/* 02CEC 80B00F9C 004E1021 */ addu $v0, $v0, $t6
/* 02CF0 80B00FA0 904204BD */ lbu $v0, 0x04BD($v0) ## 000104BD
/* 02CF4 80B00FA4 24010001 */ addiu $at, $zero, 0x0001 ## $at = 00000001
/* 02CF8 80B00FA8 8FAF001C */ lw $t7, 0x001C($sp)
/* 02CFC 80B00FAC 50400006 */ beql $v0, $zero, .L80B00FC8
/* 02D00 80B00FB0 8DE21C44 */ lw $v0, 0x1C44($t7) ## 00001C44
/* 02D04 80B00FB4 1041000C */ beq $v0, $at, .L80B00FE8
/* 02D08 80B00FB8 8FAB0018 */ lw $t3, 0x0018($sp)
/* 02D0C 80B00FBC 1000000E */ beq $zero, $zero, .L80B00FF8
/* 02D10 80B00FC0 8FBF0014 */ lw $ra, 0x0014($sp)
/* 02D14 80B00FC4 8DE21C44 */ lw $v0, 0x1C44($t7) ## 00001C44
.L80B00FC8:
/* 02D18 80B00FC8 3C0880B0 */ lui $t0, %hi(func_80B00A54) ## $t0 = 80B00000
/* 02D1C 80B00FCC 25080A54 */ addiu $t0, $t0, %lo(func_80B00A54) ## $t0 = 80B00A54
/* 02D20 80B00FD0 90580692 */ lbu $t8, 0x0692($v0) ## 00010692
/* 02D24 80B00FD4 37190020 */ ori $t9, $t8, 0x0020 ## $t9 = 00000020
/* 02D28 80B00FD8 A0590692 */ sb $t9, 0x0692($v0) ## 00010692
/* 02D2C 80B00FDC 8FA90018 */ lw $t1, 0x0018($sp)
/* 02D30 80B00FE0 10000004 */ beq $zero, $zero, .L80B00FF4
/* 02D34 80B00FE4 AD280274 */ sw $t0, 0x0274($t1) ## 00000274
.L80B00FE8:
/* 02D38 80B00FE8 3C0A80B0 */ lui $t2, %hi(func_80B011CC) ## $t2 = 80B00000
/* 02D3C 80B00FEC 254A11CC */ addiu $t2, $t2, %lo(func_80B011CC) ## $t2 = 80B011CC
/* 02D40 80B00FF0 AD6A0274 */ sw $t2, 0x0274($t3) ## 00000274
.L80B00FF4:
/* 02D44 80B00FF4 8FBF0014 */ lw $ra, 0x0014($sp)
.L80B00FF8:
/* 02D48 80B00FF8 27BD0018 */ addiu $sp, $sp, 0x0018 ## $sp = 00000000
/* 02D4C 80B00FFC 03E00008 */ jr $ra
/* 02D50 80B01000 00000000 */ nop
| {
"pile_set_name": "Github"
} |
/*
Copyright 2016 Goldman Sachs.
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.gs.fw.common.mithra;
import com.gs.fw.common.mithra.finder.AggregateSqlQuery;
import com.gs.fw.common.mithra.finder.Operation;
import java.util.Map;
import java.util.Set;
import java.io.Serializable;
public interface HavingOperation extends Serializable
{
public HavingOperation and(HavingOperation op);
public HavingOperation or(HavingOperation op);
public void zGenerateSql(AggregateSqlQuery query);
public MithraObjectPortal getResultObjectPortal();
public void zAddMissingAggregateAttributes(Set<MithraAggregateAttribute> aggregateAttributes, Map<String, MithraAggregateAttribute> nameToAttributeMap);
public boolean zMatches(AggregateData aggregateData, Map<com.gs.fw.common.mithra.MithraAggregateAttribute, String> attributeToNameMap);
public void zGenerateMapperSql(AggregateSqlQuery aggregateSqlQuery);
public Operation zCreateMappedOperation();
}
| {
"pile_set_name": "Github"
} |
// RUN: %clang_cc1 -x c++ -std=c++14 -fsyntax-only -verify %s
template <int I, int J, int K>
void car() {
int __attribute__((address_space(I))) __attribute__((address_space(J))) * Y; // expected-error {{multiple address spaces specified for type}}
int *__attribute__((address_space(I))) __attribute__((address_space(J))) * Z; // expected-error {{multiple address spaces specified for type}}
__attribute__((address_space(I))) int local; // expected-error {{automatic variable qualified with an address space}}
__attribute__((address_space(J))) int array[5]; // expected-error {{automatic variable qualified with an address space}}
__attribute__((address_space(I))) int arrarr[5][5]; // expected-error {{automatic variable qualified with an address space}}
__attribute__((address_space(J))) * x; // expected-error {{C++ requires a type specifier for all declarations}}
__attribute__((address_space(I))) float *B;
typedef __attribute__((address_space(J))) int AS2Int;
struct HasASFields {
AS2Int typedef_as_field; // expected-error {{field may not be qualified with an address space}}
};
struct _st {
int x, y;
} s __attribute((address_space(I))) = {1, 1};
}
template <int I>
struct HasASTemplateFields {
__attribute__((address_space(I))) int as_field; // expected-error {{field may not be qualified with an address space}}
};
template <int I, int J>
void foo(__attribute__((address_space(I))) float *a, // expected-note {{candidate template ignored: substitution failure [with I = 1, J = 2]: parameter may not be qualified with an address space}}
__attribute__((address_space(J))) float b) {
*a = 5.0f + b;
}
template void foo<1, 2>(float *, float); // expected-error {{explicit instantiation of 'foo' does not refer to a function template, variable template, member function, member class, or static data member}}
template <int I>
void neg() {
__attribute__((address_space(I))) int *bounds; // expected-error {{address space is negative}}
}
template <long int I>
void tooBig() {
__attribute__((address_space(I))) int *bounds; // expected-error {{address space is larger than the maximum supported (8388598)}}
}
template <long int I>
void correct() {
__attribute__((address_space(I))) int *bounds;
}
template <int I, int J>
char *cmp(__attribute__((address_space(I))) char *x, __attribute__((address_space(J))) char *y) {
return x < y ? x : y; // expected-error {{comparison of distinct pointer types ('__attribute__((address_space(1))) char *' and '__attribute__((address_space(2))) char *')}}
}
typedef void ft(void);
template <int I>
struct fooFunction {
__attribute__((address_space(I))) void **const base = 0;
void *get_0(void) {
return base[0]; // expected-error {{cannot initialize return object of type 'void *' with an lvalue of type '__attribute__((address_space(1))) void *}}
}
__attribute__((address_space(I))) ft qf; // expected-error {{function type may not be qualified with an address space}}
__attribute__((address_space(I))) char *test3_val;
void test3(void) {
extern void test3_helper(char *p); // expected-note {{passing argument to parameter 'p' here}}
test3_helper(test3_val); // expected-error {{cannot initialize a parameter of type 'char *' with an lvalue of type '__attribute__((address_space(1))) char *'}}
}
};
template <typename T, int N>
int GetAddressSpaceValue(T __attribute__((address_space(N))) * p) {
return N;
}
template <unsigned A> int __attribute__((address_space(A))) *same_template();
template <unsigned B> int __attribute__((address_space(B))) *same_template();
void test_same_template() { (void) same_template<0>(); }
template <unsigned A> int __attribute__((address_space(A))) *different_template(); // expected-note {{candidate function [with A = 0]}}
template <unsigned B> int __attribute__((address_space(B+1))) *different_template(); // expected-note {{candidate function [with B = 0]}}
void test_different_template() { (void) different_template<0>(); } // expected-error {{call to 'different_template' is ambiguous}}
template <typename T> struct partial_spec_deduce_as;
template <typename T, unsigned AS>
struct partial_spec_deduce_as <__attribute__((address_space(AS))) T *> {
static const unsigned value = AS;
};
int main() {
int __attribute__((address_space(1))) * p1;
int p = GetAddressSpaceValue(p1);
car<1, 2, 3>(); // expected-note {{in instantiation of function template specialization 'car<1, 2, 3>' requested here}}
HasASTemplateFields<1> HASTF;
neg<-1>(); // expected-note {{in instantiation of function template specialization 'neg<-1>' requested here}}
correct<0x7FFFF6>();
tooBig<8388650>(); // expected-note {{in instantiation of function template specialization 'tooBig<8388650>' requested here}}
__attribute__((address_space(1))) char *x;
__attribute__((address_space(2))) char *y;
cmp<1, 2>(x, y); // expected-note {{in instantiation of function template specialization 'cmp<1, 2>' requested here}}
fooFunction<1> ff;
ff.get_0(); // expected-note {{in instantiation of member function 'fooFunction<1>::get_0' requested here}}
ff.qf();
ff.test3(); // expected-note {{in instantiation of member function 'fooFunction<1>::test3' requested here}}
static_assert(partial_spec_deduce_as<int __attribute__((address_space(3))) *>::value == 3, "address space value has been incorrectly deduced");
return 0;
}
| {
"pile_set_name": "Github"
} |
{
"name": "e-tiller",
"author": "fofa",
"version": "0.1.0",
"matches": [
{
"search": "body",
"text": "reader/view_abstract.aspx"
}
]
} | {
"pile_set_name": "Github"
} |
# docker image for fpm-gobgp
DOCKER_FPM_GOBGP = docker-fpm-gobgp.gz
$(DOCKER_FPM_GOBGP)_PATH = $(DOCKERS_PATH)/docker-fpm-gobgp
$(DOCKER_FPM_GOBGP)_DEPENDS += $(GOBGP)
$(DOCKER_FPM_GOBGP)_LOAD_DOCKERS += $(DOCKER_FPM_QUAGGA)
SONIC_DOCKER_IMAGES += $(DOCKER_FPM_GOBGP)
$(DOCKER_FPM_GOBGP)_CONTAINER_NAME = bgp
$(DOCKER_FPM_GOBGP)_RUN_OPT += --privileged -t
$(DOCKER_FPM_GOBGP)_RUN_OPT += -v /etc/sonic:/etc/sonic:ro
$(DOCKER_FPM_GOBPG)_FILES += $(SUPERVISOR_PROC_EXIT_LISTENER_SCRIPT)
| {
"pile_set_name": "Github"
} |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Mathematical models."""
# pylint: disable=line-too-long, too-many-lines, too-many-arguments, invalid-name
import numpy as np
from astropy import units as u
from astropy.units import Quantity, UnitsError
from astropy.utils.decorators import deprecated
from .core import (Fittable1DModel, Fittable2DModel)
from .parameters import Parameter, InputParameterError
from .utils import ellipse_extent
__all__ = ['AiryDisk2D', 'Moffat1D', 'Moffat2D', 'Box1D', 'Box2D', 'Const1D',
'Const2D', 'Ellipse2D', 'Disk2D', 'Gaussian1D', 'Gaussian2D',
'Linear1D', 'Lorentz1D', 'RickerWavelet1D', 'RickerWavelet2D',
'RedshiftScaleFactor', 'Multiply', 'Planar2D', 'Scale',
'Sersic1D', 'Sersic2D', 'Shift', 'Sine1D', 'Trapezoid1D',
'TrapezoidDisk2D', 'Ring2D', 'Voigt1D', 'KingProjectedAnalytic1D',
'Exponential1D', 'Logarithmic1D']
TWOPI = 2 * np.pi
FLOAT_EPSILON = float(np.finfo(np.float32).tiny)
# Note that we define this here rather than using the value defined in
# astropy.stats to avoid importing astropy.stats every time astropy.modeling
# is loaded.
GAUSSIAN_SIGMA_TO_FWHM = 2.0 * np.sqrt(2.0 * np.log(2.0))
class Gaussian1D(Fittable1DModel):
"""
One dimensional Gaussian model.
Parameters
----------
amplitude : float
Amplitude of the Gaussian.
mean : float
Mean of the Gaussian.
stddev : float
Standard deviation of the Gaussian.
Notes
-----
Model formula:
.. math:: f(x) = A e^{- \\frac{\\left(x - x_{0}\\right)^{2}}{2 \\sigma^{2}}}
Examples
--------
>>> from astropy.modeling import models
>>> def tie_center(model):
... mean = 50 * model.stddev
... return mean
>>> tied_parameters = {'mean': tie_center}
Specify that 'mean' is a tied parameter in one of two ways:
>>> g1 = models.Gaussian1D(amplitude=10, mean=5, stddev=.3,
... tied=tied_parameters)
or
>>> g1 = models.Gaussian1D(amplitude=10, mean=5, stddev=.3)
>>> g1.mean.tied
False
>>> g1.mean.tied = tie_center
>>> g1.mean.tied
<function tie_center at 0x...>
Fixed parameters:
>>> g1 = models.Gaussian1D(amplitude=10, mean=5, stddev=.3,
... fixed={'stddev': True})
>>> g1.stddev.fixed
True
or
>>> g1 = models.Gaussian1D(amplitude=10, mean=5, stddev=.3)
>>> g1.stddev.fixed
False
>>> g1.stddev.fixed = True
>>> g1.stddev.fixed
True
.. plot::
:include-source:
import numpy as np
import matplotlib.pyplot as plt
from astropy.modeling.models import Gaussian1D
plt.figure()
s1 = Gaussian1D()
r = np.arange(-5, 5, .01)
for factor in range(1, 4):
s1.amplitude = factor
plt.plot(r, s1(r), color=str(0.25 * factor), lw=2)
plt.axis([-5, 5, -1, 4])
plt.show()
See Also
--------
Gaussian2D, Box1D, Moffat1D, Lorentz1D
"""
amplitude = Parameter(default=1)
mean = Parameter(default=0)
# Ensure stddev makes sense if its bounds are not explicitly set.
# stddev must be non-zero and positive.
stddev = Parameter(default=1, bounds=(FLOAT_EPSILON, None))
def bounding_box(self, factor=5.5):
"""
Tuple defining the default ``bounding_box`` limits,
``(x_low, x_high)``
Parameters
----------
factor : float
The multiple of `stddev` used to define the limits.
The default is 5.5, corresponding to a relative error < 1e-7.
Examples
--------
>>> from astropy.modeling.models import Gaussian1D
>>> model = Gaussian1D(mean=0, stddev=2)
>>> model.bounding_box
(-11.0, 11.0)
This range can be set directly (see: `Model.bounding_box
<astropy.modeling.Model.bounding_box>`) or by using a different factor,
like:
>>> model.bounding_box = model.bounding_box(factor=2)
>>> model.bounding_box
(-4.0, 4.0)
"""
x0 = self.mean
dx = factor * self.stddev
return (x0 - dx, x0 + dx)
@property
def fwhm(self):
"""Gaussian full width at half maximum."""
return self.stddev * GAUSSIAN_SIGMA_TO_FWHM
@staticmethod
def evaluate(x, amplitude, mean, stddev):
"""
Gaussian1D model function.
"""
return amplitude * np.exp(- 0.5 * (x - mean) ** 2 / stddev ** 2)
@staticmethod
def fit_deriv(x, amplitude, mean, stddev):
"""
Gaussian1D model function derivatives.
"""
d_amplitude = np.exp(-0.5 / stddev ** 2 * (x - mean) ** 2)
d_mean = amplitude * d_amplitude * (x - mean) / stddev ** 2
d_stddev = amplitude * d_amplitude * (x - mean) ** 2 / stddev ** 3
return [d_amplitude, d_mean, d_stddev]
@property
def input_units(self):
if self.mean.unit is None:
return None
return {self.inputs[0]: self.mean.unit}
def _parameter_units_for_data_units(self, inputs_unit, outputs_unit):
return {'mean': inputs_unit[self.inputs[0]],
'stddev': inputs_unit[self.inputs[0]],
'amplitude': outputs_unit[self.outputs[0]]}
class Gaussian2D(Fittable2DModel):
r"""
Two dimensional Gaussian model.
Parameters
----------
amplitude : float
Amplitude of the Gaussian.
x_mean : float
Mean of the Gaussian in x.
y_mean : float
Mean of the Gaussian in y.
x_stddev : float or None
Standard deviation of the Gaussian in x before rotating by theta. Must
be None if a covariance matrix (``cov_matrix``) is provided. If no
``cov_matrix`` is given, ``None`` means the default value (1).
y_stddev : float or None
Standard deviation of the Gaussian in y before rotating by theta. Must
be None if a covariance matrix (``cov_matrix``) is provided. If no
``cov_matrix`` is given, ``None`` means the default value (1).
theta : float, optional
Rotation angle in radians. The rotation angle increases
counterclockwise. Must be None if a covariance matrix (``cov_matrix``)
is provided. If no ``cov_matrix`` is given, ``None`` means the default
value (0).
cov_matrix : ndarray, optional
A 2x2 covariance matrix. If specified, overrides the ``x_stddev``,
``y_stddev``, and ``theta`` defaults.
Notes
-----
Model formula:
.. math::
f(x, y) = A e^{-a\left(x - x_{0}\right)^{2} -b\left(x - x_{0}\right)
\left(y - y_{0}\right) -c\left(y - y_{0}\right)^{2}}
Using the following definitions:
.. math::
a = \left(\frac{\cos^{2}{\left (\theta \right )}}{2 \sigma_{x}^{2}} +
\frac{\sin^{2}{\left (\theta \right )}}{2 \sigma_{y}^{2}}\right)
b = \left(\frac{\sin{\left (2 \theta \right )}}{2 \sigma_{x}^{2}} -
\frac{\sin{\left (2 \theta \right )}}{2 \sigma_{y}^{2}}\right)
c = \left(\frac{\sin^{2}{\left (\theta \right )}}{2 \sigma_{x}^{2}} +
\frac{\cos^{2}{\left (\theta \right )}}{2 \sigma_{y}^{2}}\right)
If using a ``cov_matrix``, the model is of the form:
.. math::
f(x, y) = A e^{-0.5 \left(\vec{x} - \vec{x}_{0}\right)^{T} \Sigma^{-1} \left(\vec{x} - \vec{x}_{0}\right)}
where :math:`\vec{x} = [x, y]`, :math:`\vec{x}_{0} = [x_{0}, y_{0}]`,
and :math:`\Sigma` is the covariance matrix:
.. math::
\Sigma = \left(\begin{array}{ccc}
\sigma_x^2 & \rho \sigma_x \sigma_y \\
\rho \sigma_x \sigma_y & \sigma_y^2
\end{array}\right)
:math:`\rho` is the correlation between ``x`` and ``y``, which should
be between -1 and +1. Positive correlation corresponds to a
``theta`` in the range 0 to 90 degrees. Negative correlation
corresponds to a ``theta`` in the range of 0 to -90 degrees.
See [1]_ for more details about the 2D Gaussian function.
See Also
--------
Gaussian1D, Box2D, Moffat2D
References
----------
.. [1] https://en.wikipedia.org/wiki/Gaussian_function
"""
amplitude = Parameter(default=1)
x_mean = Parameter(default=0)
y_mean = Parameter(default=0)
x_stddev = Parameter(default=1)
y_stddev = Parameter(default=1)
theta = Parameter(default=0.0)
def __init__(self, amplitude=amplitude.default, x_mean=x_mean.default,
y_mean=y_mean.default, x_stddev=None, y_stddev=None,
theta=None, cov_matrix=None, **kwargs):
if cov_matrix is None:
if x_stddev is None:
x_stddev = self.__class__.x_stddev.default
if y_stddev is None:
y_stddev = self.__class__.y_stddev.default
if theta is None:
theta = self.__class__.theta.default
else:
if x_stddev is not None or y_stddev is not None or theta is not None:
raise InputParameterError("Cannot specify both cov_matrix and "
"x/y_stddev/theta")
# Compute principle coordinate system transformation
cov_matrix = np.array(cov_matrix)
if cov_matrix.shape != (2, 2):
raise ValueError("Covariance matrix must be 2x2")
eig_vals, eig_vecs = np.linalg.eig(cov_matrix)
x_stddev, y_stddev = np.sqrt(eig_vals)
y_vec = eig_vecs[:, 0]
theta = np.arctan2(y_vec[1], y_vec[0])
# Ensure stddev makes sense if its bounds are not explicitly set.
# stddev must be non-zero and positive.
# TODO: Investigate why setting this in Parameter above causes
# convolution tests to hang.
kwargs.setdefault('bounds', {})
kwargs['bounds'].setdefault('x_stddev', (FLOAT_EPSILON, None))
kwargs['bounds'].setdefault('y_stddev', (FLOAT_EPSILON, None))
super().__init__(
amplitude=amplitude, x_mean=x_mean, y_mean=y_mean,
x_stddev=x_stddev, y_stddev=y_stddev, theta=theta, **kwargs)
@property
def x_fwhm(self):
"""Gaussian full width at half maximum in X."""
return self.x_stddev * GAUSSIAN_SIGMA_TO_FWHM
@property
def y_fwhm(self):
"""Gaussian full width at half maximum in Y."""
return self.y_stddev * GAUSSIAN_SIGMA_TO_FWHM
def bounding_box(self, factor=5.5):
"""
Tuple defining the default ``bounding_box`` limits in each dimension,
``((y_low, y_high), (x_low, x_high))``
The default offset from the mean is 5.5-sigma, corresponding
to a relative error < 1e-7. The limits are adjusted for rotation.
Parameters
----------
factor : float, optional
The multiple of `x_stddev` and `y_stddev` used to define the limits.
The default is 5.5.
Examples
--------
>>> from astropy.modeling.models import Gaussian2D
>>> model = Gaussian2D(x_mean=0, y_mean=0, x_stddev=1, y_stddev=2)
>>> model.bounding_box
((-11.0, 11.0), (-5.5, 5.5))
This range can be set directly (see: `Model.bounding_box
<astropy.modeling.Model.bounding_box>`) or by using a different factor
like:
>>> model.bounding_box = model.bounding_box(factor=2)
>>> model.bounding_box
((-4.0, 4.0), (-2.0, 2.0))
"""
a = factor * self.x_stddev
b = factor * self.y_stddev
theta = self.theta.value
dx, dy = ellipse_extent(a, b, theta)
return ((self.y_mean - dy, self.y_mean + dy),
(self.x_mean - dx, self.x_mean + dx))
@staticmethod
def evaluate(x, y, amplitude, x_mean, y_mean, x_stddev, y_stddev, theta):
"""Two dimensional Gaussian function"""
cost2 = np.cos(theta) ** 2
sint2 = np.sin(theta) ** 2
sin2t = np.sin(2. * theta)
xstd2 = x_stddev ** 2
ystd2 = y_stddev ** 2
xdiff = x - x_mean
ydiff = y - y_mean
a = 0.5 * ((cost2 / xstd2) + (sint2 / ystd2))
b = 0.5 * ((sin2t / xstd2) - (sin2t / ystd2))
c = 0.5 * ((sint2 / xstd2) + (cost2 / ystd2))
return amplitude * np.exp(-((a * xdiff ** 2) + (b * xdiff * ydiff) +
(c * ydiff ** 2)))
@staticmethod
def fit_deriv(x, y, amplitude, x_mean, y_mean, x_stddev, y_stddev, theta):
"""Two dimensional Gaussian function derivative with respect to parameters"""
cost = np.cos(theta)
sint = np.sin(theta)
cost2 = np.cos(theta) ** 2
sint2 = np.sin(theta) ** 2
cos2t = np.cos(2. * theta)
sin2t = np.sin(2. * theta)
xstd2 = x_stddev ** 2
ystd2 = y_stddev ** 2
xstd3 = x_stddev ** 3
ystd3 = y_stddev ** 3
xdiff = x - x_mean
ydiff = y - y_mean
xdiff2 = xdiff ** 2
ydiff2 = ydiff ** 2
a = 0.5 * ((cost2 / xstd2) + (sint2 / ystd2))
b = 0.5 * ((sin2t / xstd2) - (sin2t / ystd2))
c = 0.5 * ((sint2 / xstd2) + (cost2 / ystd2))
g = amplitude * np.exp(-((a * xdiff2) + (b * xdiff * ydiff) +
(c * ydiff2)))
da_dtheta = (sint * cost * ((1. / ystd2) - (1. / xstd2)))
da_dx_stddev = -cost2 / xstd3
da_dy_stddev = -sint2 / ystd3
db_dtheta = (cos2t / xstd2) - (cos2t / ystd2)
db_dx_stddev = -sin2t / xstd3
db_dy_stddev = sin2t / ystd3
dc_dtheta = -da_dtheta
dc_dx_stddev = -sint2 / xstd3
dc_dy_stddev = -cost2 / ystd3
dg_dA = g / amplitude
dg_dx_mean = g * ((2. * a * xdiff) + (b * ydiff))
dg_dy_mean = g * ((b * xdiff) + (2. * c * ydiff))
dg_dx_stddev = g * (-(da_dx_stddev * xdiff2 +
db_dx_stddev * xdiff * ydiff +
dc_dx_stddev * ydiff2))
dg_dy_stddev = g * (-(da_dy_stddev * xdiff2 +
db_dy_stddev * xdiff * ydiff +
dc_dy_stddev * ydiff2))
dg_dtheta = g * (-(da_dtheta * xdiff2 +
db_dtheta * xdiff * ydiff +
dc_dtheta * ydiff2))
return [dg_dA, dg_dx_mean, dg_dy_mean, dg_dx_stddev, dg_dy_stddev,
dg_dtheta]
@property
def input_units(self):
if self.x_mean.unit is None and self.y_mean.unit is None:
return None
return {self.inputs[0]: self.x_mean.unit,
self.inputs[1]: self.y_mean.unit}
def _parameter_units_for_data_units(self, inputs_unit, outputs_unit):
# Note that here we need to make sure that x and y are in the same
# units otherwise this can lead to issues since rotation is not well
# defined.
if inputs_unit[self.inputs[0]] != inputs_unit[self.inputs[1]]:
raise UnitsError("Units of 'x' and 'y' inputs should match")
return {'x_mean': inputs_unit[self.inputs[0]],
'y_mean': inputs_unit[self.inputs[0]],
'x_stddev': inputs_unit[self.inputs[0]],
'y_stddev': inputs_unit[self.inputs[0]],
'theta': u.rad,
'amplitude': outputs_unit[self.outputs[0]]}
class Shift(Fittable1DModel):
"""
Shift a coordinate.
Parameters
----------
offset : float
Offset to add to a coordinate.
"""
offset = Parameter(default=0)
linear = True
@property
def input_units(self):
if self.offset.unit is None:
return None
return {self.inputs[0]: self.offset.unit}
@property
def inverse(self):
"""One dimensional inverse Shift model function"""
inv = self.copy()
inv.offset *= -1
return inv
@staticmethod
def evaluate(x, offset):
"""One dimensional Shift model function"""
return x + offset
@staticmethod
def sum_of_implicit_terms(x):
"""Evaluate the implicit term (x) of one dimensional Shift model"""
return x
@staticmethod
def fit_deriv(x, *params):
"""One dimensional Shift model derivative with respect to parameter"""
d_offset = np.ones_like(x)
return [d_offset]
def _parameter_units_for_data_units(self, inputs_unit, outputs_unit):
return {'offset': outputs_unit[self.outputs[0]]}
class Scale(Fittable1DModel):
"""
Multiply a model by a dimensionless factor.
Parameters
----------
factor : float
Factor by which to scale a coordinate.
Notes
-----
If ``factor`` is a `~astropy.units.Quantity` then the units will be
stripped before the scaling operation.
"""
factor = Parameter(default=1)
linear = True
fittable = True
_input_units_strict = True
_input_units_allow_dimensionless = True
@property
def input_units(self):
if self.factor.unit is None:
return None
return {self.inputs[0]: self.factor.unit}
@property
def inverse(self):
"""One dimensional inverse Scale model function"""
inv = self.copy()
inv.factor = 1 / self.factor
return inv
@staticmethod
def evaluate(x, factor):
"""One dimensional Scale model function"""
if isinstance(factor, u.Quantity):
factor = factor.value
return factor * x
@staticmethod
def fit_deriv(x, *params):
"""One dimensional Scale model derivative with respect to parameter"""
d_factor = x
return [d_factor]
def _parameter_units_for_data_units(self, inputs_unit, outputs_unit):
return {'factor': outputs_unit[self.outputs[0]]}
class Multiply(Fittable1DModel):
"""
Multiply a model by a quantity or number.
Parameters
----------
factor : float
Factor by which to multiply a coordinate.
"""
factor = Parameter(default=1)
linear = True
fittable = True
@property
def inverse(self):
"""One dimensional inverse multiply model function"""
inv = self.copy()
inv.factor = 1 / self.factor
return inv
@staticmethod
def evaluate(x, factor):
"""One dimensional multiply model function"""
return factor * x
@staticmethod
def fit_deriv(x, *params):
"""One dimensional multiply model derivative with respect to parameter"""
d_factor = x
return [d_factor]
def _parameter_units_for_data_units(self, inputs_unit, outputs_unit):
return {'factor': outputs_unit[self.outputs[0]]}
class RedshiftScaleFactor(Fittable1DModel):
"""
One dimensional redshift scale factor model.
Parameters
----------
z : float
Redshift value.
Notes
-----
Model formula:
.. math:: f(x) = x (1 + z)
"""
z = Parameter(description='redshift', default=0)
@staticmethod
def evaluate(x, z):
"""One dimensional RedshiftScaleFactor model function"""
return (1 + z) * x
@staticmethod
def fit_deriv(x, z):
"""One dimensional RedshiftScaleFactor model derivative"""
d_z = x
return [d_z]
@property
def inverse(self):
"""Inverse RedshiftScaleFactor model"""
inv = self.copy()
inv.z = 1.0 / (1.0 + self.z) - 1.0
return inv
class Sersic1D(Fittable1DModel):
r"""
One dimensional Sersic surface brightness profile.
Parameters
----------
amplitude : float
Surface brightness at r_eff.
r_eff : float
Effective (half-light) radius
n : float
Sersic Index.
See Also
--------
Gaussian1D, Moffat1D, Lorentz1D
Notes
-----
Model formula:
.. math::
I(r)=I_e\exp\left\{-b_n\left[\left(\frac{r}{r_{e}}\right)^{(1/n)}-1\right]\right\}
The constant :math:`b_n` is defined such that :math:`r_e` contains half the total
luminosity, and can be solved for numerically.
.. math::
\Gamma(2n) = 2\gamma (b_n,2n)
Examples
--------
.. plot::
:include-source:
import numpy as np
from astropy.modeling.models import Sersic1D
import matplotlib.pyplot as plt
plt.figure()
plt.subplot(111, xscale='log', yscale='log')
s1 = Sersic1D(amplitude=1, r_eff=5)
r=np.arange(0, 100, .01)
for n in range(1, 10):
s1.n = n
plt.plot(r, s1(r), color=str(float(n) / 15))
plt.axis([1e-1, 30, 1e-2, 1e3])
plt.xlabel('log Radius')
plt.ylabel('log Surface Brightness')
plt.text(.25, 1.5, 'n=1')
plt.text(.25, 300, 'n=10')
plt.xticks([])
plt.yticks([])
plt.show()
References
----------
.. [1] http://ned.ipac.caltech.edu/level5/March05/Graham/Graham2.html
"""
amplitude = Parameter(default=1)
r_eff = Parameter(default=1)
n = Parameter(default=4)
_gammaincinv = None
@classmethod
def evaluate(cls, r, amplitude, r_eff, n):
"""One dimensional Sersic profile function."""
if cls._gammaincinv is None:
try:
from scipy.special import gammaincinv
cls._gammaincinv = gammaincinv
except ValueError:
raise ImportError('Sersic1D model requires scipy > 0.11.')
return (amplitude * np.exp(
-cls._gammaincinv(2 * n, 0.5) * ((r / r_eff) ** (1 / n) - 1)))
@property
def input_units(self):
if self.r_eff.unit is None:
return None
return {self.inputs[0]: self.r_eff.unit}
def _parameter_units_for_data_units(self, inputs_unit, outputs_unit):
return {'r_eff': inputs_unit[self.inputs[0]],
'amplitude': outputs_unit[self.outputs[0]]}
class Sine1D(Fittable1DModel):
"""
One dimensional Sine model.
Parameters
----------
amplitude : float
Oscillation amplitude
frequency : float
Oscillation frequency
phase : float
Oscillation phase
See Also
--------
Const1D, Linear1D
Notes
-----
Model formula:
.. math:: f(x) = A \\sin(2 \\pi f x + 2 \\pi p)
Examples
--------
.. plot::
:include-source:
import numpy as np
import matplotlib.pyplot as plt
from astropy.modeling.models import Sine1D
plt.figure()
s1 = Sine1D(amplitude=1, frequency=.25)
r=np.arange(0, 10, .01)
for amplitude in range(1,4):
s1.amplitude = amplitude
plt.plot(r, s1(r), color=str(0.25 * amplitude), lw=2)
plt.axis([0, 10, -5, 5])
plt.show()
"""
amplitude = Parameter(default=1)
frequency = Parameter(default=1)
phase = Parameter(default=0)
@staticmethod
def evaluate(x, amplitude, frequency, phase):
"""One dimensional Sine model function"""
# Note: If frequency and x are quantities, they should normally have
# inverse units, so that argument ends up being dimensionless. However,
# np.sin of a dimensionless quantity will crash, so we remove the
# quantity-ness from argument in this case (another option would be to
# multiply by * u.rad but this would be slower overall).
argument = TWOPI * (frequency * x + phase)
if isinstance(argument, Quantity):
argument = argument.value
return amplitude * np.sin(argument)
@staticmethod
def fit_deriv(x, amplitude, frequency, phase):
"""One dimensional Sine model derivative"""
d_amplitude = np.sin(TWOPI * frequency * x + TWOPI * phase)
d_frequency = (TWOPI * x * amplitude *
np.cos(TWOPI * frequency * x + TWOPI * phase))
d_phase = (TWOPI * amplitude *
np.cos(TWOPI * frequency * x + TWOPI * phase))
return [d_amplitude, d_frequency, d_phase]
@property
def input_units(self):
if self.frequency.unit is None:
return None
return {self.inputs[0]: 1. / self.frequency.unit}
def _parameter_units_for_data_units(self, inputs_unit, outputs_unit):
return {'frequency': inputs_unit[self.inputs[0]] ** -1,
'amplitude': outputs_unit[self.outputs[0]]}
class Linear1D(Fittable1DModel):
"""
One dimensional Line model.
Parameters
----------
slope : float
Slope of the straight line
intercept : float
Intercept of the straight line
See Also
--------
Const1D
Notes
-----
Model formula:
.. math:: f(x) = a x + b
"""
slope = Parameter(default=1)
intercept = Parameter(default=0)
linear = True
@staticmethod
def evaluate(x, slope, intercept):
"""One dimensional Line model function"""
return slope * x + intercept
@staticmethod
def fit_deriv(x, *params):
"""One dimensional Line model derivative with respect to parameters"""
d_slope = x
d_intercept = np.ones_like(x)
return [d_slope, d_intercept]
@property
def inverse(self):
new_slope = self.slope ** -1
new_intercept = -self.intercept / self.slope
return self.__class__(slope=new_slope, intercept=new_intercept)
@property
def input_units(self):
if self.intercept.unit is None and self.slope.unit is None:
return None
return {self.inputs[0]: self.intercept.unit / self.slope.unit}
def _parameter_units_for_data_units(self, inputs_unit, outputs_unit):
return {'intercept': outputs_unit[self.outputs[0]],
'slope': outputs_unit[self.outputs[0]] / inputs_unit[self.inputs[0]]}
class Planar2D(Fittable2DModel):
"""
Two dimensional Plane model.
Parameters
----------
slope_x : float
Slope of the straight line in X
slope_y : float
Slope of the straight line in Y
intercept : float
Z-intercept of the straight line
Notes
-----
Model formula:
.. math:: f(x, y) = a x + b y + c
"""
slope_x = Parameter(default=1)
slope_y = Parameter(default=1)
intercept = Parameter(default=0)
linear = True
@staticmethod
def evaluate(x, y, slope_x, slope_y, intercept):
"""Two dimensional Plane model function"""
return slope_x * x + slope_y * y + intercept
@staticmethod
def fit_deriv(x, y, *params):
"""Two dimensional Plane model derivative with respect to parameters"""
d_slope_x = x
d_slope_y = y
d_intercept = np.ones_like(x)
return [d_slope_x, d_slope_y, d_intercept]
def _parameter_units_for_data_units(self, inputs_unit, outputs_unit):
return {'intercept': outputs_unit['z'],
'slope_x': outputs_unit['z'] / inputs_unit['x'],
'slope_y': outputs_unit['z'] / inputs_unit['y']}
class Lorentz1D(Fittable1DModel):
"""
One dimensional Lorentzian model.
Parameters
----------
amplitude : float
Peak value
x_0 : float
Position of the peak
fwhm : float
Full width at half maximum (FWHM)
See Also
--------
Gaussian1D, Box1D, RickerWavelet1D
Notes
-----
Model formula:
.. math::
f(x) = \\frac{A \\gamma^{2}}{\\gamma^{2} + \\left(x - x_{0}\\right)^{2}}
where :math:`\\gamma` is half of given FWHM.
Examples
--------
.. plot::
:include-source:
import numpy as np
import matplotlib.pyplot as plt
from astropy.modeling.models import Lorentz1D
plt.figure()
s1 = Lorentz1D()
r = np.arange(-5, 5, .01)
for factor in range(1, 4):
s1.amplitude = factor
plt.plot(r, s1(r), color=str(0.25 * factor), lw=2)
plt.axis([-5, 5, -1, 4])
plt.show()
"""
amplitude = Parameter(default=1)
x_0 = Parameter(default=0)
fwhm = Parameter(default=1)
@staticmethod
def evaluate(x, amplitude, x_0, fwhm):
"""One dimensional Lorentzian model function"""
return (amplitude * ((fwhm / 2.) ** 2) / ((x - x_0) ** 2 +
(fwhm / 2.) ** 2))
@staticmethod
def fit_deriv(x, amplitude, x_0, fwhm):
"""One dimensional Lorentzian model derivative with respect to parameters"""
d_amplitude = fwhm ** 2 / (fwhm ** 2 + (x - x_0) ** 2)
d_x_0 = (amplitude * d_amplitude * (2 * x - 2 * x_0) /
(fwhm ** 2 + (x - x_0) ** 2))
d_fwhm = 2 * amplitude * d_amplitude / fwhm * (1 - d_amplitude)
return [d_amplitude, d_x_0, d_fwhm]
def bounding_box(self, factor=25):
"""Tuple defining the default ``bounding_box`` limits,
``(x_low, x_high)``.
Parameters
----------
factor : float
The multiple of FWHM used to define the limits.
Default is chosen to include most (99%) of the
area under the curve, while still showing the
central feature of interest.
"""
x0 = self.x_0
dx = factor * self.fwhm
return (x0 - dx, x0 + dx)
@property
def input_units(self):
if self.x_0.unit is None:
return None
return {self.inputs[0]: self.x_0.unit}
def _parameter_units_for_data_units(self, inputs_unit, outputs_unit):
return {'x_0': inputs_unit[self.inputs[0]],
'fwhm': inputs_unit[self.inputs[0]],
'amplitude': outputs_unit[self.outputs[0]]}
class Voigt1D(Fittable1DModel):
"""
One dimensional model for the Voigt profile.
Parameters
----------
x_0 : float
Position of the peak
amplitude_L : float
The Lorentzian amplitude
fwhm_L : float
The Lorentzian full width at half maximum
fwhm_G : float
The Gaussian full width at half maximum
See Also
--------
Gaussian1D, Lorentz1D
Notes
-----
Algorithm for the computation taken from
McLean, A. B., Mitchell, C. E. J. & Swanston, D. M. Implementation of an
efficient analytical approximation to the Voigt function for photoemission
lineshape analysis. Journal of Electron Spectroscopy and Related Phenomena
69, 125-132 (1994)
Examples
--------
.. plot::
:include-source:
import numpy as np
from astropy.modeling.models import Voigt1D
import matplotlib.pyplot as plt
plt.figure()
x = np.arange(0, 10, 0.01)
v1 = Voigt1D(x_0=5, amplitude_L=10, fwhm_L=0.5, fwhm_G=0.9)
plt.plot(x, v1(x))
plt.show()
"""
x_0 = Parameter(default=0)
amplitude_L = Parameter(default=1)
fwhm_L = Parameter(default=2/np.pi)
fwhm_G = Parameter(default=np.log(2))
_abcd = np.array([
[-1.2150, -1.3509, -1.2150, -1.3509], # A
[1.2359, 0.3786, -1.2359, -0.3786], # B
[-0.3085, 0.5906, -0.3085, 0.5906], # C
[0.0210, -1.1858, -0.0210, 1.1858]]) # D
@classmethod
def evaluate(cls, x, x_0, amplitude_L, fwhm_L, fwhm_G):
A, B, C, D = cls._abcd
sqrt_ln2 = np.sqrt(np.log(2))
X = (x - x_0) * 2 * sqrt_ln2 / fwhm_G
X = np.atleast_1d(X)[..., np.newaxis]
Y = fwhm_L * sqrt_ln2 / fwhm_G
Y = np.atleast_1d(Y)[..., np.newaxis]
V = np.sum((C * (Y - A) + D * (X - B))/((Y - A) ** 2 + (X - B) ** 2), axis=-1)
return (fwhm_L * amplitude_L * np.sqrt(np.pi) * sqrt_ln2 / fwhm_G) * V
@classmethod
def fit_deriv(cls, x, x_0, amplitude_L, fwhm_L, fwhm_G):
A, B, C, D = cls._abcd
sqrt_ln2 = np.sqrt(np.log(2))
X = (x - x_0) * 2 * sqrt_ln2 / fwhm_G
X = np.atleast_1d(X)[:, np.newaxis]
Y = fwhm_L * sqrt_ln2 / fwhm_G
Y = np.atleast_1d(Y)[:, np.newaxis]
constant = fwhm_L * amplitude_L * np.sqrt(np.pi) * sqrt_ln2 / fwhm_G
alpha = C * (Y - A) + D * (X - B)
beta = (Y - A) ** 2 + (X - B) ** 2
V = np.sum((alpha / beta), axis=-1)
dVdx = np.sum((D/beta - 2 * (X - B) * alpha / np.square(beta)), axis=-1)
dVdy = np.sum((C/beta - 2 * (Y - A) * alpha / np.square(beta)), axis=-1)
dyda = [-constant * dVdx * 2 * sqrt_ln2 / fwhm_G,
constant * V / amplitude_L,
constant * (V / fwhm_L + dVdy * sqrt_ln2 / fwhm_G),
-constant * (V + (sqrt_ln2 / fwhm_G) * (2 * (x - x_0) *
dVdx + fwhm_L * dVdy)) / fwhm_G]
return dyda
@property
def input_units(self):
if self.x_0.unit is None:
return None
return {self.inputs[0]: self.x_0.unit}
def _parameter_units_for_data_units(self, inputs_unit, outputs_unit):
return {'x_0': inputs_unit[self.inputs[0]],
'fwhm_L': inputs_unit[self.inputs[0]],
'fwhm_G': inputs_unit[self.inputs[0]],
'amplitude_L': outputs_unit[self.outputs[0]]}
class Const1D(Fittable1DModel):
"""
One dimensional Constant model.
Parameters
----------
amplitude : float
Value of the constant function
See Also
--------
Const2D
Notes
-----
Model formula:
.. math:: f(x) = A
Examples
--------
.. plot::
:include-source:
import numpy as np
import matplotlib.pyplot as plt
from astropy.modeling.models import Const1D
plt.figure()
s1 = Const1D()
r = np.arange(-5, 5, .01)
for factor in range(1, 4):
s1.amplitude = factor
plt.plot(r, s1(r), color=str(0.25 * factor), lw=2)
plt.axis([-5, 5, -1, 4])
plt.show()
"""
amplitude = Parameter(default=1)
linear = True
@staticmethod
def evaluate(x, amplitude):
"""One dimensional Constant model function"""
if amplitude.size == 1:
# This is slightly faster than using ones_like and multiplying
x = np.empty_like(x, subok=False)
x.fill(amplitude.item())
else:
# This case is less likely but could occur if the amplitude
# parameter is given an array-like value
x = amplitude * np.ones_like(x, subok=False)
if isinstance(amplitude, Quantity):
return Quantity(x, unit=amplitude.unit, copy=False)
return x
@staticmethod
def fit_deriv(x, amplitude):
"""One dimensional Constant model derivative with respect to parameters"""
d_amplitude = np.ones_like(x)
return [d_amplitude]
@property
def input_units(self):
return None
def _parameter_units_for_data_units(self, inputs_unit, outputs_unit):
return {'amplitude': outputs_unit[self.outputs[0]]}
class Const2D(Fittable2DModel):
"""
Two dimensional Constant model.
Parameters
----------
amplitude : float
Value of the constant function
See Also
--------
Const1D
Notes
-----
Model formula:
.. math:: f(x, y) = A
"""
amplitude = Parameter(default=1)
linear = True
@staticmethod
def evaluate(x, y, amplitude):
"""Two dimensional Constant model function"""
if amplitude.size == 1:
# This is slightly faster than using ones_like and multiplying
x = np.empty_like(x, subok=False)
x.fill(amplitude.item())
else:
# This case is less likely but could occur if the amplitude
# parameter is given an array-like value
x = amplitude * np.ones_like(x, subok=False)
if isinstance(amplitude, Quantity):
return Quantity(x, unit=amplitude.unit, copy=False)
return x
@property
def input_units(self):
return None
def _parameter_units_for_data_units(self, inputs_unit, outputs_unit):
return {'amplitude': outputs_unit[self.outputs[0]]}
class Ellipse2D(Fittable2DModel):
"""
A 2D Ellipse model.
Parameters
----------
amplitude : float
Value of the ellipse.
x_0 : float
x position of the center of the disk.
y_0 : float
y position of the center of the disk.
a : float
The length of the semimajor axis.
b : float
The length of the semiminor axis.
theta : float
The rotation angle in radians of the semimajor axis. The
rotation angle increases counterclockwise from the positive x
axis.
See Also
--------
Disk2D, Box2D
Notes
-----
Model formula:
.. math::
f(x, y) = \\left \\{
\\begin{array}{ll}
\\mathrm{amplitude} & : \\left[\\frac{(x - x_0) \\cos
\\theta + (y - y_0) \\sin \\theta}{a}\\right]^2 +
\\left[\\frac{-(x - x_0) \\sin \\theta + (y - y_0)
\\cos \\theta}{b}\\right]^2 \\leq 1 \\\\
0 & : \\mathrm{otherwise}
\\end{array}
\\right.
Examples
--------
.. plot::
:include-source:
import numpy as np
from astropy.modeling.models import Ellipse2D
from astropy.coordinates import Angle
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
x0, y0 = 25, 25
a, b = 20, 10
theta = Angle(30, 'deg')
e = Ellipse2D(amplitude=100., x_0=x0, y_0=y0, a=a, b=b,
theta=theta.radian)
y, x = np.mgrid[0:50, 0:50]
fig, ax = plt.subplots(1, 1)
ax.imshow(e(x, y), origin='lower', interpolation='none', cmap='Greys_r')
e2 = mpatches.Ellipse((x0, y0), 2*a, 2*b, theta.degree, edgecolor='red',
facecolor='none')
ax.add_patch(e2)
plt.show()
"""
amplitude = Parameter(default=1)
x_0 = Parameter(default=0)
y_0 = Parameter(default=0)
a = Parameter(default=1)
b = Parameter(default=1)
theta = Parameter(default=0)
@staticmethod
def evaluate(x, y, amplitude, x_0, y_0, a, b, theta):
"""Two dimensional Ellipse model function."""
xx = x - x_0
yy = y - y_0
cost = np.cos(theta)
sint = np.sin(theta)
numerator1 = (xx * cost) + (yy * sint)
numerator2 = -(xx * sint) + (yy * cost)
in_ellipse = (((numerator1 / a) ** 2 + (numerator2 / b) ** 2) <= 1.)
result = np.select([in_ellipse], [amplitude])
if isinstance(amplitude, Quantity):
return Quantity(result, unit=amplitude.unit, copy=False)
return result
@property
def bounding_box(self):
"""
Tuple defining the default ``bounding_box`` limits.
``((y_low, y_high), (x_low, x_high))``
"""
a = self.a
b = self.b
theta = self.theta.value
dx, dy = ellipse_extent(a, b, theta)
return ((self.y_0 - dy, self.y_0 + dy),
(self.x_0 - dx, self.x_0 + dx))
@property
def input_units(self):
if self.x_0.unit is None:
return None
return {self.inputs[0]: self.x_0.unit,
self.inputs[1]: self.y_0.unit}
def _parameter_units_for_data_units(self, inputs_unit, outputs_unit):
# Note that here we need to make sure that x and y are in the same
# units otherwise this can lead to issues since rotation is not well
# defined.
if inputs_unit[self.inputs[0]] != inputs_unit[self.inputs[1]]:
raise UnitsError("Units of 'x' and 'y' inputs should match")
return {'x_0': inputs_unit[self.inputs[0]],
'y_0': inputs_unit[self.inputs[0]],
'a': inputs_unit[self.inputs[0]],
'b': inputs_unit[self.inputs[0]],
'theta': u.rad,
'amplitude': outputs_unit[self.outputs[0]]}
class Disk2D(Fittable2DModel):
"""
Two dimensional radial symmetric Disk model.
Parameters
----------
amplitude : float
Value of the disk function
x_0 : float
x position center of the disk
y_0 : float
y position center of the disk
R_0 : float
Radius of the disk
See Also
--------
Box2D, TrapezoidDisk2D
Notes
-----
Model formula:
.. math::
f(r) = \\left \\{
\\begin{array}{ll}
A & : r \\leq R_0 \\\\
0 & : r > R_0
\\end{array}
\\right.
"""
amplitude = Parameter(default=1)
x_0 = Parameter(default=0)
y_0 = Parameter(default=0)
R_0 = Parameter(default=1)
@staticmethod
def evaluate(x, y, amplitude, x_0, y_0, R_0):
"""Two dimensional Disk model function"""
rr = (x - x_0) ** 2 + (y - y_0) ** 2
result = np.select([rr <= R_0 ** 2], [amplitude])
if isinstance(amplitude, Quantity):
return Quantity(result, unit=amplitude.unit, copy=False)
return result
@property
def bounding_box(self):
"""
Tuple defining the default ``bounding_box`` limits.
``((y_low, y_high), (x_low, x_high))``
"""
return ((self.y_0 - self.R_0, self.y_0 + self.R_0),
(self.x_0 - self.R_0, self.x_0 + self.R_0))
@property
def input_units(self):
if self.x_0.unit is None and self.y_0.unit is None:
return None
return {self.inputs[0]: self.x_0.unit,
self.inputs[1]: self.y_0.unit}
def _parameter_units_for_data_units(self, inputs_unit, outputs_unit):
# Note that here we need to make sure that x and y are in the same
# units otherwise this can lead to issues since rotation is not well
# defined.
if inputs_unit[self.inputs[0]] != inputs_unit[self.inputs[1]]:
raise UnitsError("Units of 'x' and 'y' inputs should match")
return {'x_0': inputs_unit[self.inputs[0]],
'y_0': inputs_unit[self.inputs[0]],
'R_0': inputs_unit[self.inputs[0]],
'amplitude': outputs_unit[self.outputs[0]]}
class Ring2D(Fittable2DModel):
"""
Two dimensional radial symmetric Ring model.
Parameters
----------
amplitude : float
Value of the disk function
x_0 : float
x position center of the disk
y_0 : float
y position center of the disk
r_in : float
Inner radius of the ring
width : float
Width of the ring.
r_out : float
Outer Radius of the ring. Can be specified instead of width.
See Also
--------
Disk2D, TrapezoidDisk2D
Notes
-----
Model formula:
.. math::
f(r) = \\left \\{
\\begin{array}{ll}
A & : r_{in} \\leq r \\leq r_{out} \\\\
0 & : \\text{else}
\\end{array}
\\right.
Where :math:`r_{out} = r_{in} + r_{width}`.
"""
amplitude = Parameter(default=1)
x_0 = Parameter(default=0)
y_0 = Parameter(default=0)
r_in = Parameter(default=1)
width = Parameter(default=1)
def __init__(self, amplitude=amplitude.default, x_0=x_0.default,
y_0=y_0.default, r_in=r_in.default, width=width.default,
r_out=None, **kwargs):
# If outer radius explicitly given, it overrides default width.
if r_out is not None:
if width != self.width.default:
raise InputParameterError(
"Cannot specify both width and outer radius separately.")
width = r_out - r_in
elif width is None:
width = self.width.default
super().__init__(
amplitude=amplitude, x_0=x_0, y_0=y_0, r_in=r_in, width=width,
**kwargs)
@staticmethod
def evaluate(x, y, amplitude, x_0, y_0, r_in, width):
"""Two dimensional Ring model function."""
rr = (x - x_0) ** 2 + (y - y_0) ** 2
r_range = np.logical_and(rr >= r_in ** 2, rr <= (r_in + width) ** 2)
result = np.select([r_range], [amplitude])
if isinstance(amplitude, Quantity):
return Quantity(result, unit=amplitude.unit, copy=False)
return result
@property
def bounding_box(self):
"""
Tuple defining the default ``bounding_box``.
``((y_low, y_high), (x_low, x_high))``
"""
dr = self.r_in + self.width
return ((self.y_0 - dr, self.y_0 + dr),
(self.x_0 - dr, self.x_0 + dr))
@property
def input_units(self):
if self.x_0.unit is None:
return None
return {self.inputs[0]: self.x_0.unit,
self.inputs[1]: self.y_0.unit}
def _parameter_units_for_data_units(self, inputs_unit, outputs_unit):
# Note that here we need to make sure that x and y are in the same
# units otherwise this can lead to issues since rotation is not well
# defined.
if inputs_unit[self.inputs[0]] != inputs_unit[self.inputs[1]]:
raise UnitsError("Units of 'x' and 'y' inputs should match")
return {'x_0': inputs_unit[self.inputs[0]],
'y_0': inputs_unit[self.inputs[0]],
'r_in': inputs_unit[self.inputs[0]],
'width': inputs_unit[self.inputs[0]],
'amplitude': outputs_unit[self.outputs[0]]}
class Box1D(Fittable1DModel):
"""
One dimensional Box model.
Parameters
----------
amplitude : float
Amplitude A
x_0 : float
Position of the center of the box function
width : float
Width of the box
See Also
--------
Box2D, TrapezoidDisk2D
Notes
-----
Model formula:
.. math::
f(x) = \\left \\{
\\begin{array}{ll}
A & : x_0 - w/2 \\leq x \\leq x_0 + w/2 \\\\
0 & : \\text{else}
\\end{array}
\\right.
Examples
--------
.. plot::
:include-source:
import numpy as np
import matplotlib.pyplot as plt
from astropy.modeling.models import Box1D
plt.figure()
s1 = Box1D()
r = np.arange(-5, 5, .01)
for factor in range(1, 4):
s1.amplitude = factor
s1.width = factor
plt.plot(r, s1(r), color=str(0.25 * factor), lw=2)
plt.axis([-5, 5, -1, 4])
plt.show()
"""
amplitude = Parameter(default=1)
x_0 = Parameter(default=0)
width = Parameter(default=1)
@staticmethod
def evaluate(x, amplitude, x_0, width):
"""One dimensional Box model function"""
inside = np.logical_and(x >= x_0 - width / 2., x <= x_0 + width / 2.)
return np.select([inside], [amplitude], 0)
@property
def bounding_box(self):
"""
Tuple defining the default ``bounding_box`` limits.
``(x_low, x_high))``
"""
dx = self.width / 2
return (self.x_0 - dx, self.x_0 + dx)
@property
def input_units(self):
if self.x_0.unit is None:
return None
return {self.inputs[0]: self.x_0.unit}
@property
def return_units(self):
if self.amplitude.unit is None:
return None
return {self.outputs[0]: self.amplitude.unit}
def _parameter_units_for_data_units(self, inputs_unit, outputs_unit):
return {'x_0': inputs_unit[self.inputs[0]],
'width': inputs_unit[self.inputs[0]],
'amplitude': outputs_unit[self.outputs[0]]}
class Box2D(Fittable2DModel):
"""
Two dimensional Box model.
Parameters
----------
amplitude : float
Amplitude A
x_0 : float
x position of the center of the box function
x_width : float
Width in x direction of the box
y_0 : float
y position of the center of the box function
y_width : float
Width in y direction of the box
See Also
--------
Box1D, Gaussian2D, Moffat2D
Notes
-----
Model formula:
.. math::
f(x, y) = \\left \\{
\\begin{array}{ll}
A : & x_0 - w_x/2 \\leq x \\leq x_0 + w_x/2 \\text{ and} \\\\
& y_0 - w_y/2 \\leq y \\leq y_0 + w_y/2 \\\\
0 : & \\text{else}
\\end{array}
\\right.
"""
amplitude = Parameter(default=1)
x_0 = Parameter(default=0)
y_0 = Parameter(default=0)
x_width = Parameter(default=1)
y_width = Parameter(default=1)
@staticmethod
def evaluate(x, y, amplitude, x_0, y_0, x_width, y_width):
"""Two dimensional Box model function"""
x_range = np.logical_and(x >= x_0 - x_width / 2.,
x <= x_0 + x_width / 2.)
y_range = np.logical_and(y >= y_0 - y_width / 2.,
y <= y_0 + y_width / 2.)
result = np.select([np.logical_and(x_range, y_range)], [amplitude], 0)
if isinstance(amplitude, Quantity):
return Quantity(result, unit=amplitude.unit, copy=False)
return result
@property
def bounding_box(self):
"""
Tuple defining the default ``bounding_box``.
``((y_low, y_high), (x_low, x_high))``
"""
dx = self.x_width / 2
dy = self.y_width / 2
return ((self.y_0 - dy, self.y_0 + dy),
(self.x_0 - dx, self.x_0 + dx))
@property
def input_units(self):
if self.x_0.unit is None:
return None
return {self.inputs[0]: self.x_0.unit,
self.inputs[1]: self.y_0.unit}
def _parameter_units_for_data_units(self, inputs_unit, outputs_unit):
return {'x_0': inputs_unit[self.inputs[0]],
'y_0': inputs_unit[self.inputs[1]],
'x_width': inputs_unit[self.inputs[0]],
'y_width': inputs_unit[self.inputs[1]],
'amplitude': outputs_unit[self.outputs[0]]}
class Trapezoid1D(Fittable1DModel):
"""
One dimensional Trapezoid model.
Parameters
----------
amplitude : float
Amplitude of the trapezoid
x_0 : float
Center position of the trapezoid
width : float
Width of the constant part of the trapezoid.
slope : float
Slope of the tails of the trapezoid
See Also
--------
Box1D, Gaussian1D, Moffat1D
Examples
--------
.. plot::
:include-source:
import numpy as np
import matplotlib.pyplot as plt
from astropy.modeling.models import Trapezoid1D
plt.figure()
s1 = Trapezoid1D()
r = np.arange(-5, 5, .01)
for factor in range(1, 4):
s1.amplitude = factor
s1.width = factor
plt.plot(r, s1(r), color=str(0.25 * factor), lw=2)
plt.axis([-5, 5, -1, 4])
plt.show()
"""
amplitude = Parameter(default=1)
x_0 = Parameter(default=0)
width = Parameter(default=1)
slope = Parameter(default=1)
@staticmethod
def evaluate(x, amplitude, x_0, width, slope):
"""One dimensional Trapezoid model function"""
# Compute the four points where the trapezoid changes slope
# x1 <= x2 <= x3 <= x4
x2 = x_0 - width / 2.
x3 = x_0 + width / 2.
x1 = x2 - amplitude / slope
x4 = x3 + amplitude / slope
# Compute model values in pieces between the change points
range_a = np.logical_and(x >= x1, x < x2)
range_b = np.logical_and(x >= x2, x < x3)
range_c = np.logical_and(x >= x3, x < x4)
val_a = slope * (x - x1)
val_b = amplitude
val_c = slope * (x4 - x)
result = np.select([range_a, range_b, range_c], [val_a, val_b, val_c])
if isinstance(amplitude, Quantity):
return Quantity(result, unit=amplitude.unit, copy=False)
return result
@property
def bounding_box(self):
"""
Tuple defining the default ``bounding_box`` limits.
``(x_low, x_high))``
"""
dx = self.width / 2 + self.amplitude / self.slope
return (self.x_0 - dx, self.x_0 + dx)
@property
def input_units(self):
if self.x_0.unit is None:
return None
return {self.inputs[0]: self.x_0.unit}
def _parameter_units_for_data_units(self, inputs_unit, outputs_unit):
return {'x_0': inputs_unit[self.inputs[0]],
'width': inputs_unit[self.inputs[0]],
'slope': outputs_unit[self.outputs[0]] / inputs_unit[self.inputs[0]],
'amplitude': outputs_unit[self.outputs[0]]}
class TrapezoidDisk2D(Fittable2DModel):
"""
Two dimensional circular Trapezoid model.
Parameters
----------
amplitude : float
Amplitude of the trapezoid
x_0 : float
x position of the center of the trapezoid
y_0 : float
y position of the center of the trapezoid
R_0 : float
Radius of the constant part of the trapezoid.
slope : float
Slope of the tails of the trapezoid in x direction.
See Also
--------
Disk2D, Box2D
"""
amplitude = Parameter(default=1)
x_0 = Parameter(default=0)
y_0 = Parameter(default=0)
R_0 = Parameter(default=1)
slope = Parameter(default=1)
@staticmethod
def evaluate(x, y, amplitude, x_0, y_0, R_0, slope):
"""Two dimensional Trapezoid Disk model function"""
r = np.sqrt((x - x_0) ** 2 + (y - y_0) ** 2)
range_1 = r <= R_0
range_2 = np.logical_and(r > R_0, r <= R_0 + amplitude / slope)
val_1 = amplitude
val_2 = amplitude + slope * (R_0 - r)
result = np.select([range_1, range_2], [val_1, val_2])
if isinstance(amplitude, Quantity):
return Quantity(result, unit=amplitude.unit, copy=False)
return result
@property
def bounding_box(self):
"""
Tuple defining the default ``bounding_box``.
``((y_low, y_high), (x_low, x_high))``
"""
dr = self.R_0 + self.amplitude / self.slope
return ((self.y_0 - dr, self.y_0 + dr),
(self.x_0 - dr, self.x_0 + dr))
@property
def input_units(self):
if self.x_0.unit is None and self.y_0.unit is None:
return None
return {self.inputs[0]: self.x_0.unit,
self.inputs[1]: self.y_0.unit}
def _parameter_units_for_data_units(self, inputs_unit, outputs_unit):
# Note that here we need to make sure that x and y are in the same
# units otherwise this can lead to issues since rotation is not well
# defined.
if inputs_unit['x'] != inputs_unit['y']:
raise UnitsError("Units of 'x' and 'y' inputs should match")
return {'x_0': inputs_unit[self.inputs[0]],
'y_0': inputs_unit[self.inputs[0]],
'R_0': inputs_unit[self.inputs[0]],
'slope': outputs_unit[self.outputs[0]] / inputs_unit[self.inputs[0]],
'amplitude': outputs_unit[self.outputs[0]]}
class RickerWavelet1D(Fittable1DModel):
"""
One dimensional Ricker Wavelet model (sometimes known as a "Mexican Hat"
model).
.. note::
See https://github.com/astropy/astropy/pull/9445 for discussions
related to renaming of this model.
Parameters
----------
amplitude : float
Amplitude
x_0 : float
Position of the peak
sigma : float
Width of the Ricker wavelet
See Also
--------
RickerWavelet2D, Box1D, Gaussian1D, Trapezoid1D
Notes
-----
Model formula:
.. math::
f(x) = {A \\left(1 - \\frac{\\left(x - x_{0}\\right)^{2}}{\\sigma^{2}}\\right)
e^{- \\frac{\\left(x - x_{0}\\right)^{2}}{2 \\sigma^{2}}}}
Examples
--------
.. plot::
:include-source:
import numpy as np
import matplotlib.pyplot as plt
from astropy.modeling.models import RickerWavelet1D
plt.figure()
s1 = RickerWavelet1D()
r = np.arange(-5, 5, .01)
for factor in range(1, 4):
s1.amplitude = factor
s1.width = factor
plt.plot(r, s1(r), color=str(0.25 * factor), lw=2)
plt.axis([-5, 5, -2, 4])
plt.show()
"""
amplitude = Parameter(default=1)
x_0 = Parameter(default=0)
sigma = Parameter(default=1)
@staticmethod
def evaluate(x, amplitude, x_0, sigma):
"""One dimensional Ricker Wavelet model function"""
xx_ww = (x - x_0) ** 2 / (2 * sigma ** 2)
return amplitude * (1 - 2 * xx_ww) * np.exp(-xx_ww)
def bounding_box(self, factor=10.0):
"""Tuple defining the default ``bounding_box`` limits,
``(x_low, x_high)``.
Parameters
----------
factor : float
The multiple of sigma used to define the limits.
"""
x0 = self.x_0
dx = factor * self.sigma
return (x0 - dx, x0 + dx)
@property
def input_units(self):
if self.x_0.unit is None:
return None
return {self.inputs[0]: self.x_0.unit}
def _parameter_units_for_data_units(self, inputs_unit, outputs_unit):
return {'x_0': inputs_unit[self.inputs[0]],
'sigma': inputs_unit[self.inputs[0]],
'amplitude': outputs_unit[self.outputs[0]]}
class RickerWavelet2D(Fittable2DModel):
"""
Two dimensional Ricker Wavelet model (sometimes known as a "Mexican Hat"
model).
.. note::
See https://github.com/astropy/astropy/pull/9445 for discussions
related to renaming of this model.
Parameters
----------
amplitude : float
Amplitude
x_0 : float
x position of the peak
y_0 : float
y position of the peak
sigma : float
Width of the Ricker wavelet
See Also
--------
RickerWavelet1D, Gaussian2D
Notes
-----
Model formula:
.. math::
f(x, y) = A \\left(1 - \\frac{\\left(x - x_{0}\\right)^{2}
+ \\left(y - y_{0}\\right)^{2}}{\\sigma^{2}}\\right)
e^{\\frac{- \\left(x - x_{0}\\right)^{2}
- \\left(y - y_{0}\\right)^{2}}{2 \\sigma^{2}}}
"""
amplitude = Parameter(default=1)
x_0 = Parameter(default=0)
y_0 = Parameter(default=0)
sigma = Parameter(default=1)
@staticmethod
def evaluate(x, y, amplitude, x_0, y_0, sigma):
"""Two dimensional Ricker Wavelet model function"""
rr_ww = ((x - x_0) ** 2 + (y - y_0) ** 2) / (2 * sigma ** 2)
return amplitude * (1 - rr_ww) * np.exp(- rr_ww)
@property
def input_units(self):
if self.x_0.unit is None:
return None
return {self.inputs[0]: self.x_0.unit,
self.inputs[1]: self.y_0.unit}
def _parameter_units_for_data_units(self, inputs_unit, outputs_unit):
# Note that here we need to make sure that x and y are in the same
# units otherwise this can lead to issues since rotation is not well
# defined.
if inputs_unit[self.inputs[0]] != inputs_unit[self.inputs[1]]:
raise UnitsError("Units of 'x' and 'y' inputs should match")
return {'x_0': inputs_unit[self.inputs[0]],
'y_0': inputs_unit[self.inputs[0]],
'sigma': inputs_unit[self.inputs[0]],
'amplitude': outputs_unit[self.outputs[0]]}
class AiryDisk2D(Fittable2DModel):
"""
Two dimensional Airy disk model.
Parameters
----------
amplitude : float
Amplitude of the Airy function.
x_0 : float
x position of the maximum of the Airy function.
y_0 : float
y position of the maximum of the Airy function.
radius : float
The radius of the Airy disk (radius of the first zero).
See Also
--------
Box2D, TrapezoidDisk2D, Gaussian2D
Notes
-----
Model formula:
.. math:: f(r) = A \\left[\\frac{2 J_1(\\frac{\\pi r}{R/R_z})}{\\frac{\\pi r}{R/R_z}}\\right]^2
Where :math:`J_1` is the first order Bessel function of the first
kind, :math:`r` is radial distance from the maximum of the Airy
function (:math:`r = \\sqrt{(x - x_0)^2 + (y - y_0)^2}`), :math:`R`
is the input ``radius`` parameter, and :math:`R_z =
1.2196698912665045`).
For an optical system, the radius of the first zero represents the
limiting angular resolution and is approximately 1.22 * lambda / D,
where lambda is the wavelength of the light and D is the diameter of
the aperture.
See [1]_ for more details about the Airy disk.
References
----------
.. [1] https://en.wikipedia.org/wiki/Airy_disk
"""
amplitude = Parameter(default=1)
x_0 = Parameter(default=0)
y_0 = Parameter(default=0)
radius = Parameter(default=1)
_rz = None
_j1 = None
@classmethod
def evaluate(cls, x, y, amplitude, x_0, y_0, radius):
"""Two dimensional Airy model function"""
if cls._rz is None:
try:
from scipy.special import j1, jn_zeros
cls._rz = jn_zeros(1, 1)[0] / np.pi
cls._j1 = j1
except ValueError:
raise ImportError('AiryDisk2D model requires scipy > 0.11.')
r = np.sqrt((x - x_0) ** 2 + (y - y_0) ** 2) / (radius / cls._rz)
if isinstance(r, Quantity):
# scipy function cannot handle Quantity, so turn into array.
r = r.to_value(u.dimensionless_unscaled)
# Since r can be zero, we have to take care to treat that case
# separately so as not to raise a numpy warning
z = np.ones(r.shape)
rt = np.pi * r[r > 0]
z[r > 0] = (2.0 * cls._j1(rt) / rt) ** 2
if isinstance(amplitude, Quantity):
# make z quantity too, otherwise in-place multiplication fails.
z = Quantity(z, u.dimensionless_unscaled, copy=False)
z *= amplitude
return z
@property
def input_units(self):
if self.x_0.unit is None:
return None
return {self.inputs[0]: self.x_0.unit,
self.inputs[1]: self.y_0.unit}
def _parameter_units_for_data_units(self, inputs_unit, outputs_unit):
# Note that here we need to make sure that x and y are in the same
# units otherwise this can lead to issues since rotation is not well
# defined.
if inputs_unit[self.inputs[0]] != inputs_unit[self.inputs[1]]:
raise UnitsError("Units of 'x' and 'y' inputs should match")
return {'x_0': inputs_unit[self.inputs[0]],
'y_0': inputs_unit[self.inputs[0]],
'radius': inputs_unit[self.inputs[0]],
'amplitude': outputs_unit[self.outputs[0]]}
class Moffat1D(Fittable1DModel):
"""
One dimensional Moffat model.
Parameters
----------
amplitude : float
Amplitude of the model.
x_0 : float
x position of the maximum of the Moffat model.
gamma : float
Core width of the Moffat model.
alpha : float
Power index of the Moffat model.
See Also
--------
Gaussian1D, Box1D
Notes
-----
Model formula:
.. math::
f(x) = A \\left(1 + \\frac{\\left(x - x_{0}\\right)^{2}}{\\gamma^{2}}\\right)^{- \\alpha}
Examples
--------
.. plot::
:include-source:
import numpy as np
import matplotlib.pyplot as plt
from astropy.modeling.models import Moffat1D
plt.figure()
s1 = Moffat1D()
r = np.arange(-5, 5, .01)
for factor in range(1, 4):
s1.amplitude = factor
s1.width = factor
plt.plot(r, s1(r), color=str(0.25 * factor), lw=2)
plt.axis([-5, 5, -1, 4])
plt.show()
"""
amplitude = Parameter(default=1)
x_0 = Parameter(default=0)
gamma = Parameter(default=1)
alpha = Parameter(default=1)
@property
def fwhm(self):
"""
Moffat full width at half maximum.
Derivation of the formula is available in
`this notebook by Yoonsoo Bach <https://nbviewer.jupyter.org/github/ysbach/AO_2017/blob/master/04_Ground_Based_Concept.ipynb#1.2.-Moffat>`_.
"""
return 2.0 * np.abs(self.gamma) * np.sqrt(2.0 ** (1.0 / self.alpha) - 1.0)
@staticmethod
def evaluate(x, amplitude, x_0, gamma, alpha):
"""One dimensional Moffat model function"""
return amplitude * (1 + ((x - x_0) / gamma) ** 2) ** (-alpha)
@staticmethod
def fit_deriv(x, amplitude, x_0, gamma, alpha):
"""One dimensional Moffat model derivative with respect to parameters"""
fac = (1 + (x - x_0) ** 2 / gamma ** 2)
d_A = fac ** (-alpha)
d_x_0 = (2 * amplitude * alpha * (x - x_0) * d_A / (fac * gamma ** 2))
d_gamma = (2 * amplitude * alpha * (x - x_0) ** 2 * d_A /
(fac * gamma ** 3))
d_alpha = -amplitude * d_A * np.log(fac)
return [d_A, d_x_0, d_gamma, d_alpha]
@property
def input_units(self):
if self.x_0.unit is None:
return None
return {self.inputs[0]: self.x_0.unit}
def _parameter_units_for_data_units(self, inputs_unit, outputs_unit):
return {'x_0': inputs_unit[self.inputs[0]],
'gamma': inputs_unit[self.inputs[0]],
'amplitude': outputs_unit[self.outputs[0]]}
class Moffat2D(Fittable2DModel):
"""
Two dimensional Moffat model.
Parameters
----------
amplitude : float
Amplitude of the model.
x_0 : float
x position of the maximum of the Moffat model.
y_0 : float
y position of the maximum of the Moffat model.
gamma : float
Core width of the Moffat model.
alpha : float
Power index of the Moffat model.
See Also
--------
Gaussian2D, Box2D
Notes
-----
Model formula:
.. math::
f(x, y) = A \\left(1 + \\frac{\\left(x - x_{0}\\right)^{2} +
\\left(y - y_{0}\\right)^{2}}{\\gamma^{2}}\\right)^{- \\alpha}
"""
amplitude = Parameter(default=1)
x_0 = Parameter(default=0)
y_0 = Parameter(default=0)
gamma = Parameter(default=1)
alpha = Parameter(default=1)
@property
def fwhm(self):
"""
Moffat full width at half maximum.
Derivation of the formula is available in
`this notebook by Yoonsoo Bach <https://nbviewer.jupyter.org/github/ysbach/AO_2017/blob/master/04_Ground_Based_Concept.ipynb#1.2.-Moffat>`_.
"""
return 2.0 * np.abs(self.gamma) * np.sqrt(2.0 ** (1.0 / self.alpha) - 1.0)
@staticmethod
def evaluate(x, y, amplitude, x_0, y_0, gamma, alpha):
"""Two dimensional Moffat model function"""
rr_gg = ((x - x_0) ** 2 + (y - y_0) ** 2) / gamma ** 2
return amplitude * (1 + rr_gg) ** (-alpha)
@staticmethod
def fit_deriv(x, y, amplitude, x_0, y_0, gamma, alpha):
"""Two dimensional Moffat model derivative with respect to parameters"""
rr_gg = ((x - x_0) ** 2 + (y - y_0) ** 2) / gamma ** 2
d_A = (1 + rr_gg) ** (-alpha)
d_x_0 = (2 * amplitude * alpha * d_A * (x - x_0) /
(gamma ** 2 * (1 + rr_gg)))
d_y_0 = (2 * amplitude * alpha * d_A * (y - y_0) /
(gamma ** 2 * (1 + rr_gg)))
d_alpha = -amplitude * d_A * np.log(1 + rr_gg)
d_gamma = (2 * amplitude * alpha * d_A * rr_gg /
(gamma ** 3 * (1 + rr_gg)))
return [d_A, d_x_0, d_y_0, d_gamma, d_alpha]
@property
def input_units(self):
if self.x_0.unit is None:
return None
else:
return {self.inputs[0]: self.x_0.unit,
self.inputs[1]: self.y_0.unit}
def _parameter_units_for_data_units(self, inputs_unit, outputs_unit):
# Note that here we need to make sure that x and y are in the same
# units otherwise this can lead to issues since rotation is not well
# defined.
if inputs_unit[self.inputs[0]] != inputs_unit[self.inputs[1]]:
raise UnitsError("Units of 'x' and 'y' inputs should match")
return {'x_0': inputs_unit[self.inputs[0]],
'y_0': inputs_unit[self.inputs[0]],
'gamma': inputs_unit[self.inputs[0]],
'amplitude': outputs_unit[self.outputs[0]]}
class Sersic2D(Fittable2DModel):
r"""
Two dimensional Sersic surface brightness profile.
Parameters
----------
amplitude : float
Surface brightness at r_eff.
r_eff : float
Effective (half-light) radius
n : float
Sersic Index.
x_0 : float, optional
x position of the center.
y_0 : float, optional
y position of the center.
ellip : float, optional
Ellipticity.
theta : float, optional
Rotation angle in radians, counterclockwise from
the positive x-axis.
See Also
--------
Gaussian2D, Moffat2D
Notes
-----
Model formula:
.. math::
I(x,y) = I(r) = I_e\exp\left\{-b_n\left[\left(\frac{r}{r_{e}}\right)^{(1/n)}-1\right]\right\}
The constant :math:`b_n` is defined such that :math:`r_e` contains half the total
luminosity, and can be solved for numerically.
.. math::
\Gamma(2n) = 2\gamma (2n,b_n)
Examples
--------
.. plot::
:include-source:
import numpy as np
from astropy.modeling.models import Sersic2D
import matplotlib.pyplot as plt
x,y = np.meshgrid(np.arange(100), np.arange(100))
mod = Sersic2D(amplitude = 1, r_eff = 25, n=4, x_0=50, y_0=50,
ellip=.5, theta=-1)
img = mod(x, y)
log_img = np.log10(img)
plt.figure()
plt.imshow(log_img, origin='lower', interpolation='nearest',
vmin=-1, vmax=2)
plt.xlabel('x')
plt.ylabel('y')
cbar = plt.colorbar()
cbar.set_label('Log Brightness', rotation=270, labelpad=25)
cbar.set_ticks([-1, 0, 1, 2], update_ticks=True)
plt.show()
References
----------
.. [1] http://ned.ipac.caltech.edu/level5/March05/Graham/Graham2.html
"""
amplitude = Parameter(default=1)
r_eff = Parameter(default=1)
n = Parameter(default=4)
x_0 = Parameter(default=0)
y_0 = Parameter(default=0)
ellip = Parameter(default=0)
theta = Parameter(default=0)
_gammaincinv = None
@classmethod
def evaluate(cls, x, y, amplitude, r_eff, n, x_0, y_0, ellip, theta):
"""Two dimensional Sersic profile function."""
if cls._gammaincinv is None:
try:
from scipy.special import gammaincinv
cls._gammaincinv = gammaincinv
except ValueError:
raise ImportError('Sersic2D model requires scipy > 0.11.')
bn = cls._gammaincinv(2. * n, 0.5)
a, b = r_eff, (1 - ellip) * r_eff
cos_theta, sin_theta = np.cos(theta), np.sin(theta)
x_maj = (x - x_0) * cos_theta + (y - y_0) * sin_theta
x_min = -(x - x_0) * sin_theta + (y - y_0) * cos_theta
z = np.sqrt((x_maj / a) ** 2 + (x_min / b) ** 2)
return amplitude * np.exp(-bn * (z ** (1 / n) - 1))
@property
def input_units(self):
if self.x_0.unit is None:
return None
return {self.inputs[0]: self.x_0.unit,
self.inputs[1]: self.y_0.unit}
def _parameter_units_for_data_units(self, inputs_unit, outputs_unit):
# Note that here we need to make sure that x and y are in the same
# units otherwise this can lead to issues since rotation is not well
# defined.
if inputs_unit[self.inputs[0]] != inputs_unit[self.inputs[1]]:
raise UnitsError("Units of 'x' and 'y' inputs should match")
return {'x_0': inputs_unit[self.inputs[0]],
'y_0': inputs_unit[self.inputs[0]],
'r_eff': inputs_unit[self.inputs[0]],
'theta': u.rad,
'amplitude': outputs_unit[self.outputs[0]]}
class KingProjectedAnalytic1D(Fittable1DModel):
"""
Projected (surface density) analytic King Model.
Parameters
----------
amplitude : float
Amplitude or scaling factor.
r_core : float
Core radius (f(r_c) ~ 0.5 f_0)
r_tide : float
Tidal radius.
Notes
-----
This model approximates a King model with an analytic function. The derivation of this
equation can be found in King '62 (equation 14). This is just an approximation of the
full model and the parameters derived from this model should be taken with caution.
It usually works for models with a concentration (c = log10(r_t/r_c) paramter < 2.
Model formula:
.. math::
f(x) = A r_c^2 \\left(\\frac{1}{\\sqrt{(x^2 + r_c^2)}} -
\\frac{1}{\\sqrt{(r_t^2 + r_c^2)}}\\right)^2
Examples
--------
.. plot::
:include-source:
import numpy as np
from astropy.modeling.models import KingProjectedAnalytic1D
import matplotlib.pyplot as plt
plt.figure()
rt_list = [1, 2, 5, 10, 20]
for rt in rt_list:
r = np.linspace(0.1, rt, 100)
mod = KingProjectedAnalytic1D(amplitude = 1, r_core = 1., r_tide = rt)
sig = mod(r)
plt.loglog(r, sig/sig[0], label='c ~ {:0.2f}'.format(mod.concentration))
plt.xlabel("r")
plt.ylabel(r"$\\sigma/\\sigma_0$")
plt.legend()
plt.show()
References
----------
.. [1] http://articles.adsabs.harvard.edu/pdf/1962AJ.....67..471K
"""
amplitude = Parameter(default=1, bounds=(FLOAT_EPSILON, None))
r_core = Parameter(default=1, bounds=(FLOAT_EPSILON, None))
r_tide = Parameter(default=2, bounds=(FLOAT_EPSILON, None))
@property
def concentration(self):
"""Concentration parameter of the king model"""
return np.log10(np.abs(self.r_tide/self.r_core))
@staticmethod
def evaluate(x, amplitude, r_core, r_tide):
"""
Analytic King model function.
"""
result = amplitude * r_core ** 2 * (1/np.sqrt(x ** 2 + r_core ** 2) -
1/np.sqrt(r_tide ** 2 + r_core ** 2)) ** 2
# Set invalid r values to 0
bounds = (x >= r_tide) | (x < 0)
result[bounds] = result[bounds] * 0.
return result
@staticmethod
def fit_deriv(x, amplitude, r_core, r_tide):
"""
Analytic King model function derivatives.
"""
d_amplitude = r_core ** 2 * (1/np.sqrt(x ** 2 + r_core ** 2) -
1/np.sqrt(r_tide ** 2 + r_core ** 2)) ** 2
d_r_core = 2 * amplitude * r_core ** 2 * (r_core/(r_core ** 2 + r_tide ** 2) ** (3/2) -
r_core/(r_core ** 2 + x ** 2) ** (3/2)) * \
(1./np.sqrt(r_core ** 2 + x ** 2) - 1./np.sqrt(r_core ** 2 + r_tide ** 2)) + \
2 * amplitude * r_core * (1./np.sqrt(r_core ** 2 + x ** 2) -
1./np.sqrt(r_core ** 2 + r_tide ** 2)) ** 2
d_r_tide = (2 * amplitude * r_core ** 2 * r_tide *
(1./np.sqrt(r_core ** 2 + x ** 2) -
1./np.sqrt(r_core ** 2 + r_tide ** 2)))/(r_core ** 2 + r_tide ** 2) ** (3/2)
# Set invalid r values to 0
bounds = (x >= r_tide) | (x < 0)
d_amplitude[bounds] = d_amplitude[bounds]*0
d_r_core[bounds] = d_r_core[bounds]*0
d_r_tide[bounds] = d_r_tide[bounds]*0
return [d_amplitude, d_r_core, d_r_tide]
@property
def bounding_box(self):
"""
Tuple defining the default ``bounding_box`` limits.
The model is not defined for r > r_tide.
``(r_low, r_high)``
"""
return (0 * self.r_tide, 1 * self.r_tide)
@property
def input_units(self):
if self.r_core.unit is None:
return None
return {self.inputs[0]: self.r_core.unit}
def _parameter_units_for_data_units(self, inputs_unit, outputs_unit):
return {'r_core': inputs_unit[self.inputs[0]],
'r_tide': inputs_unit[self.inputs[0]],
'amplitude': outputs_unit[self.outputs[0]]}
class Logarithmic1D(Fittable1DModel):
"""
One dimensional logarithmic model.
Parameters
----------
amplitude : float, optional
tau : float, optional
See Also
--------
Exponential1D, Gaussian1D
"""
amplitude = Parameter(default=1)
tau = Parameter(default=1)
@staticmethod
def evaluate(x, amplitude, tau):
return amplitude * np.log(x / tau)
@staticmethod
def fit_deriv(x, amplitude, tau):
d_amplitude = np.log(x / tau)
d_tau = np.zeros(x.shape) - (amplitude / tau)
return [d_amplitude, d_tau]
@property
def inverse(self):
new_amplitude = self.tau
new_tau = self.amplitude
return Exponential1D(amplitude=new_amplitude, tau=new_tau)
@tau.validator
def tau(self, val):
if val == 0:
raise ValueError("0 is not an allowed value for tau")
@property
def input_units(self):
if self.tau.unit is None:
return None
return {self.inputs[0]: self.tau.unit}
def _parameter_units_for_data_units(self, inputs_unit, outputs_unit):
return {'tau': inputs_unit[self.inputs[0]],
'amplitude': outputs_unit[self.outputs[0]]}
class Exponential1D(Fittable1DModel):
"""
One dimensional exponential model.
Parameters
----------
amplitude : float, optional
tau : float, optional
See Also
--------
Logarithmic1D, Gaussian1D
"""
amplitude = Parameter(default=1)
tau = Parameter(default=1)
@staticmethod
def evaluate(x, amplitude, tau):
return amplitude * np.exp(x / tau)
@staticmethod
def fit_deriv(x, amplitude, tau):
''' Derivative with respect to parameters'''
d_amplitude = np.exp(x / tau)
d_tau = -amplitude * (x / tau**2) * np.exp(x / tau)
return [d_amplitude, d_tau]
@property
def inverse(self):
new_amplitude = self.tau
new_tau = self.amplitude
return Logarithmic1D(amplitude=new_amplitude, tau=new_tau)
@tau.validator
def tau(self, val):
''' tau cannot be 0'''
if val == 0:
raise ValueError("0 is not an allowed value for tau")
@property
def input_units(self):
if self.tau.unit is None:
return None
return {self.inputs[0]: self.tau.unit}
def _parameter_units_for_data_units(self, inputs_unit, outputs_unit):
return {'tau': inputs_unit[self.inputs[0]],
'amplitude': outputs_unit[self.outputs[0]]}
@deprecated('4.0', alternative='RickerWavelet1D')
class MexicanHat1D(RickerWavelet1D):
""" Deprecated."""
@deprecated('4.0', alternative='RickerWavelet2D')
class MexicanHat2D(RickerWavelet2D):
""" Deprecated."""
| {
"pile_set_name": "Github"
} |
/*
KeePass Password Safe - The Open-Source Password Manager
Copyright (C) 2003-2020 Dominik Reichl <[email protected]>
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.
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.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using KeePass.App;
using KeePass.App.Configuration;
using KeePass.Native;
using KeePass.Resources;
using KeePass.UI;
using KeePass.Util;
using KeePass.Util.MultipleValues;
using KeePass.Util.Spr;
using KeePassLib;
using KeePassLib.Collections;
using KeePassLib.Cryptography;
using KeePassLib.Cryptography.PasswordGenerator;
using KeePassLib.Delegates;
using KeePassLib.Security;
using KeePassLib.Utility;
using NativeLib = KeePassLib.Native.NativeLib;
namespace KeePass.Forms
{
public enum PwEditMode
{
Invalid = 0,
AddNewEntry,
EditExistingEntry,
ViewReadOnlyEntry
}
public partial class PwEntryForm : Form
{
private PwEditMode m_pwEditMode = PwEditMode.Invalid;
private PwDatabase m_pwDatabase = null;
private bool m_bShowAdvancedByDefault = false;
private bool m_bSelectFullTitle = false;
private PwEntry m_pwEntry = null;
private PwEntry m_pwInitialEntry = null;
private ProtectedStringDictionary m_vStrings = null;
private ProtectedBinaryDictionary m_vBinaries = null;
private AutoTypeConfig m_atConfig = null;
private PwObjectList<PwEntry> m_vHistory = null;
private Color m_clrForeground = Color.Empty;
private Color m_clrBackground = Color.Empty;
private StringDictionaryEx m_sdCustomData = null;
private PwIcon m_pwEntryIcon = PwIcon.Key;
private PwUuid m_pwCustomIconID = PwUuid.Zero;
private ImageList m_ilIcons = null;
private List<PwUuid> m_lOrgCustomIconIDs = new List<PwUuid>();
private bool m_bTouchedOnce = false;
private bool m_bInitializing = true;
private bool m_bForceClosing = false;
private bool m_bUrlOverrideWarning = false;
private PwInputControlGroup m_icgPassword = new PwInputControlGroup();
private ExpiryControlGroup m_cgExpiry = new ExpiryControlGroup();
private RichTextBoxContextMenu m_ctxNotes = new RichTextBoxContextMenu();
private Image m_imgTools = null;
private Image m_imgGenPw = null;
private Image m_imgStdExpire = null;
private Image m_imgColorFg = null;
private Image m_imgColorBg = null;
private List<Image> m_lOverrideUrlIcons = new List<Image>();
private CustomContextMenuStripEx m_ctxBinOpen = null;
private DynamicMenu m_dynBinOpen = null;
private readonly string DeriveFromPrevious = "(" +
KPRes.GenPwBasedOnPrevious + ")";
private readonly string AutoGenProfile = "(" +
KPRes.AutoGeneratedPasswordSettings + ")";
private DynamicMenu m_dynGenProfiles;
private const PwIcon m_pwObjectProtected = PwIcon.PaperLocked;
private const PwIcon m_pwObjectPlainText = PwIcon.PaperNew;
private const PwCompareOptions m_cmpOpt = (PwCompareOptions.NullEmptyEquivStd |
PwCompareOptions.IgnoreTimes);
private enum ListSelRestore
{
None = 0,
ByIndex,
ByRef
}
public event EventHandler<CancellableOperationEventArgs> EntrySaving;
public event EventHandler EntrySaved;
public PwEditMode EditModeEx
{
get { return m_pwEditMode; }
}
public bool HasModifiedEntry
{
get
{
if((m_pwEntry == null) || (m_pwInitialEntry == null))
{
Debug.Assert(false);
return true;
}
return !m_pwEntry.EqualsEntry(m_pwInitialEntry, m_cmpOpt,
MemProtCmpMode.CustomOnly);
}
}
public PwEntry EntryRef { get { return m_pwEntry; } }
public ProtectedStringDictionary EntryStrings { get { return m_vStrings; } }
public ProtectedBinaryDictionary EntryBinaries { get { return m_vBinaries; } }
public ContextMenuStrip ToolsContextMenu
{
get { return m_ctxTools; }
}
public ContextMenuStrip DefaultTimesContextMenu
{
get { return m_ctxDefaultTimes; }
}
public ContextMenuStrip ListOperationsContextMenu
{
get { return m_ctxListOperations; }
}
public ContextMenuStrip PasswordGeneratorContextMenu
{
get { return m_ctxPwGen; }
}
public ContextMenuStrip StandardStringMovementContextMenu
{
get { return m_ctxStrMoveToStandard; }
}
public ContextMenuStrip AttachmentsContextMenu
{
get { return m_ctxBinAttach; }
}
private bool m_bInitSwitchToHistory = false;
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[DefaultValue(false)]
internal bool InitSwitchToHistoryTab
{
// get { return m_bInitSwitchToHistory; } // Internal, uncalled
set { m_bInitSwitchToHistory = value; }
}
private MultipleValuesEntryContext m_mvec = null;
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[DefaultValue((object)null)]
public MultipleValuesEntryContext MultipleValuesEntryContext
{
get { return m_mvec; }
set { m_mvec = value; }
}
public PwEntryForm()
{
InitializeComponent();
SecureTextBoxEx.InitEx(ref m_tbPassword);
SecureTextBoxEx.InitEx(ref m_tbRepeatPassword);
Program.Translation.ApplyTo(this);
Program.Translation.ApplyTo("KeePass.Forms.PwEntryForm.m_ctxTools", m_ctxTools.Items);
Program.Translation.ApplyTo("KeePass.Forms.PwEntryForm.m_ctxDefaultTimes", m_ctxDefaultTimes.Items);
Program.Translation.ApplyTo("KeePass.Forms.PwEntryForm.m_ctxListOperations", m_ctxListOperations.Items);
Program.Translation.ApplyTo("KeePass.Forms.PwEntryForm.m_ctxPwGen", m_ctxPwGen.Items);
Program.Translation.ApplyTo("KeePass.Forms.PwEntryForm.m_ctxStrMoveToStandard", m_ctxStrMoveToStandard.Items);
Program.Translation.ApplyTo("KeePass.Forms.PwEntryForm.m_ctxBinAttach", m_ctxBinAttach.Items);
}
public void InitEx(PwEntry pwEntry, PwEditMode pwMode, PwDatabase pwDatabase,
ImageList ilIcons, bool bShowAdvancedByDefault, bool bSelectFullTitle)
{
Debug.Assert(pwEntry != null); if(pwEntry == null) throw new ArgumentNullException("pwEntry");
Debug.Assert(pwMode != PwEditMode.Invalid); if(pwMode == PwEditMode.Invalid) throw new ArgumentException();
Debug.Assert(ilIcons != null); if(ilIcons == null) throw new ArgumentNullException("ilIcons");
m_pwEntry = pwEntry;
m_pwEditMode = pwMode;
m_pwDatabase = pwDatabase;
m_ilIcons = ilIcons;
m_bShowAdvancedByDefault = bShowAdvancedByDefault;
m_bSelectFullTitle = bSelectFullTitle;
m_vStrings = m_pwEntry.Strings.CloneDeep();
NormalizeStrings(m_vStrings, pwDatabase);
m_vBinaries = m_pwEntry.Binaries.CloneDeep();
m_atConfig = m_pwEntry.AutoType.CloneDeep();
m_vHistory = m_pwEntry.History.CloneDeep();
m_lOrgCustomIconIDs.Clear();
if(m_pwDatabase != null)
{
foreach(PwCustomIcon ci in m_pwDatabase.CustomIcons)
m_lOrgCustomIconIDs.Add(ci.Uuid);
}
}
private void InitEntryTab()
{
m_pwEntryIcon = m_pwEntry.IconId;
m_pwCustomIconID = m_pwEntry.CustomIconUuid;
// The user may have deleted the custom icon (using the
// icon dialog accessible through the entry dialog and
// then opening a history entry)
if(!m_pwCustomIconID.Equals(PwUuid.Zero) &&
(m_pwDatabase.GetCustomIconIndex(m_pwCustomIconID) >= 0))
{
// int nInx = (int)PwIcon.Count + m_pwDatabase.GetCustomIconIndex(m_pwCustomIconID);
// if((nInx > -1) && (nInx < m_ilIcons.Images.Count))
// m_btnIcon.Image = m_ilIcons.Images[nInx];
// else m_btnIcon.Image = m_ilIcons.Images[(int)m_pwEntryIcon];
Image imgCustom = DpiUtil.GetIcon(m_pwDatabase, m_pwCustomIconID);
// m_btnIcon.Image = (imgCustom ?? m_ilIcons.Images[(int)m_pwEntryIcon]);
UIUtil.SetButtonImage(m_btnIcon, (imgCustom ?? m_ilIcons.Images[
(int)m_pwEntryIcon]), true);
}
else
{
// m_btnIcon.Image = m_ilIcons.Images[(int)m_pwEntryIcon];
UIUtil.SetButtonImage(m_btnIcon, m_ilIcons.Images[
(int)m_pwEntryIcon], true);
}
bool bHideInitial = m_cbHidePassword.Checked;
m_icgPassword.Attach(m_tbPassword, m_cbHidePassword, m_lblPasswordRepeat,
m_tbRepeatPassword, m_lblQuality, m_pbQuality, m_lblQualityInfo,
m_ttRect, this, bHideInitial, false);
m_icgPassword.ContextDatabase = m_pwDatabase;
m_icgPassword.ContextEntry = m_pwEntry;
m_icgPassword.IsSprVariant = true;
if(m_pwEntry.Expires)
{
m_dtExpireDateTime.Value = TimeUtil.ToLocal(m_pwEntry.ExpiryTime, true);
UIUtil.SetChecked(m_cbExpires, true);
}
else // Does not expire
{
m_dtExpireDateTime.Value = DateTime.Now.Date;
UIUtil.SetChecked(m_cbExpires, false);
}
m_cgExpiry.Attach(m_cbExpires, m_dtExpireDateTime);
if(m_pwEditMode == PwEditMode.ViewReadOnlyEntry)
{
m_tbTitle.ReadOnly = m_tbUserName.ReadOnly = m_tbPassword.ReadOnly =
m_tbRepeatPassword.ReadOnly = m_tbUrl.ReadOnly =
m_rtNotes.ReadOnly = true;
UIUtil.SetEnabledFast(false, m_btnIcon, m_btnGenPw, m_cbExpires,
m_dtExpireDateTime, m_btnStandardExpires);
// m_rtNotes.SelectAll();
// m_rtNotes.BackColor = m_rtNotes.SelectionBackColor =
// AppDefs.ColorControlDisabled;
// m_rtNotes.DeselectAll();
UIUtil.SetEnabledFast(false, m_ctxToolsUrlSelApp, m_ctxToolsUrlSelDoc,
m_ctxToolsFieldRefs, m_ctxToolsFieldRefsInTitle,
m_ctxToolsFieldRefsInUserName, m_ctxToolsFieldRefsInPassword,
m_ctxToolsFieldRefsInUrl, m_ctxToolsFieldRefsInNotes);
m_btnOK.Enabled = false;
}
// Show URL in blue, if it's black in the current visual theme
if(UIUtil.ColorsEqual(m_tbUrl.ForeColor, Color.Black))
m_tbUrl.ForeColor = Color.Blue;
}
private void InitAdvancedTab()
{
m_lvStrings.SmallImageList = m_ilIcons;
// m_lvBinaries.SmallImageList = m_ilIcons;
int nWidth = m_lvStrings.ClientSize.Width / 2;
m_lvStrings.Columns.Add(KPRes.FieldName, nWidth);
m_lvStrings.Columns.Add(KPRes.FieldValue, nWidth);
nWidth = m_lvBinaries.ClientSize.Width / 2;
m_lvBinaries.Columns.Add(KPRes.Attachments, nWidth);
m_lvBinaries.Columns.Add(KPRes.Size, nWidth, HorizontalAlignment.Right);
if(m_pwEditMode == PwEditMode.ViewReadOnlyEntry)
{
m_btnStrAdd.Enabled = false;
m_btnStrEdit.Text = KPRes.ViewCmd;
m_lvBinaries.LabelEdit = false;
}
if((m_pwEditMode == PwEditMode.ViewReadOnlyEntry) || (m_mvec != null))
m_btnBinAdd.Enabled = false;
}
// Public for plugins
public void UpdateEntryStrings(bool bGuiToInternal, bool bSetRepeatPw)
{
UpdateEntryStrings(bGuiToInternal, bSetRepeatPw, false);
}
public void UpdateEntryStrings(bool bGuiToInternal, bool bSetRepeatPw,
bool bUpdateState)
{
if(bGuiToInternal)
{
m_vStrings.Set(PwDefs.TitleField, new ProtectedString(
m_pwDatabase.MemoryProtection.ProtectTitle, m_tbTitle.Text));
m_vStrings.Set(PwDefs.UserNameField, new ProtectedString(
m_pwDatabase.MemoryProtection.ProtectUserName, m_tbUserName.Text));
m_vStrings.Set(PwDefs.PasswordField, m_tbPassword.TextEx.WithProtection(
m_pwDatabase.MemoryProtection.ProtectPassword));
m_vStrings.Set(PwDefs.UrlField, new ProtectedString(
m_pwDatabase.MemoryProtection.ProtectUrl, m_tbUrl.Text));
m_vStrings.Set(PwDefs.NotesField, new ProtectedString(
m_pwDatabase.MemoryProtection.ProtectNotes, m_rtNotes.Text));
NormalizeStrings(m_vStrings, m_pwDatabase);
}
else // Internal to GUI
{
m_tbTitle.Text = m_vStrings.ReadSafe(PwDefs.TitleField);
m_tbUserName.Text = m_vStrings.ReadSafe(PwDefs.UserNameField);
ProtectedString ps = m_vStrings.GetSafe(PwDefs.PasswordField);
m_icgPassword.SetPassword(ps, bSetRepeatPw);
m_tbUrl.Text = m_vStrings.ReadSafe(PwDefs.UrlField);
m_rtNotes.Text = m_vStrings.ReadSafe(PwDefs.NotesField);
ProtectedString psCue = MultipleValuesEx.CueProtectedString;
UIScrollInfo s = UIUtil.GetScrollInfo(m_lvStrings, true);
m_lvStrings.BeginUpdate();
m_lvStrings.Items.Clear();
foreach(KeyValuePair<string, ProtectedString> kvp in m_vStrings)
{
if(PwDefs.IsStandardField(kvp.Key)) continue;
bool bProt = kvp.Value.IsProtected;
PwIcon pwIcon = (bProt ? m_pwObjectProtected : m_pwObjectPlainText);
ListViewItem lvi = m_lvStrings.Items.Add(kvp.Key, (int)pwIcon);
if((m_mvec != null) && kvp.Value.Equals(psCue, false))
{
lvi.SubItems.Add(MultipleValuesEx.CueString);
MultipleValuesEx.ConfigureText(lvi, 1);
}
else if(bProt)
lvi.SubItems.Add(PwDefs.HiddenPassword);
else
lvi.SubItems.Add(StrUtil.MultiToSingleLine(
kvp.Value.ReadString()));
}
UIUtil.Scroll(m_lvStrings, s, false);
m_lvStrings.EndUpdate();
}
if(bUpdateState) EnableControlsEx();
}
// Public for plugins
public void UpdateEntryBinaries(bool bGuiToInternal)
{
UpdateEntryBinaries(bGuiToInternal, false, null);
}
public void UpdateEntryBinaries(bool bGuiToInternal, bool bUpdateState)
{
UpdateEntryBinaries(bGuiToInternal, bUpdateState, null);
}
public void UpdateEntryBinaries(bool bGuiToInternal, bool bUpdateState,
string strFocusItem)
{
if(bGuiToInternal) { }
else // Internal to GUI
{
UIScrollInfo s = UIUtil.GetScrollInfo(m_lvBinaries, true);
m_lvBinaries.BeginUpdate();
m_lvBinaries.Items.Clear();
foreach(KeyValuePair<string, ProtectedBinary> kvpBin in m_vBinaries)
{
// PwIcon pwIcon = (kvpBin.Value.IsProtected ?
// m_pwObjectProtected : m_pwObjectPlainText);
ListViewItem lvi = m_lvBinaries.Items.Add(kvpBin.Key); // , (int)pwIcon);
lvi.SubItems.Add(StrUtil.FormatDataSizeKB(kvpBin.Value.Length));
}
FileIcons.UpdateImages(m_lvBinaries, null);
UIUtil.Scroll(m_lvBinaries, s, false);
if(strFocusItem != null)
{
ListViewItem lvi = m_lvBinaries.FindItemWithText(strFocusItem,
false, 0, false);
if(lvi != null)
{
m_lvBinaries.EnsureVisible(lvi.Index);
UIUtil.SetFocusedItem(m_lvBinaries, lvi, true);
}
else { Debug.Assert(false); }
}
m_lvBinaries.EndUpdate();
}
if(bUpdateState) EnableControlsEx();
}
private void InitPropertiesTab()
{
m_clrForeground = m_pwEntry.ForegroundColor;
m_clrBackground = m_pwEntry.BackgroundColor;
if(!UIUtil.ColorsEqual(m_clrForeground, Color.Empty))
UIUtil.OverwriteButtonImage(m_btnPickFgColor, ref m_imgColorFg,
UIUtil.CreateColorBitmap24(m_btnPickFgColor, m_clrForeground));
if(!UIUtil.ColorsEqual(m_clrBackground, Color.Empty))
UIUtil.OverwriteButtonImage(m_btnPickBgColor, ref m_imgColorBg,
UIUtil.CreateColorBitmap24(m_btnPickBgColor, m_clrBackground));
UIUtil.SetChecked(m_cbCustomForegroundColor, !UIUtil.ColorsEqual(
m_clrForeground, Color.Empty));
UIUtil.SetChecked(m_cbCustomBackgroundColor, !UIUtil.ColorsEqual(
m_clrBackground, Color.Empty));
m_tbTags.Text = StrUtil.TagsToString(m_pwEntry.Tags, true);
// https://sourceforge.net/p/keepass/discussion/329220/thread/f98dece5/
if(Program.Translation.Properties.RightToLeft)
m_cmbOverrideUrl.RightToLeft = RightToLeft.No;
m_cmbOverrideUrl.Text = m_pwEntry.OverrideUrl;
m_sdCustomData = m_pwEntry.CustomData.CloneDeep();
UIUtil.StrDictListInit(m_lvCustomData);
UIUtil.StrDictListUpdate(m_lvCustomData, m_sdCustomData, (m_mvec != null));
#if DEBUG
m_lvCustomData.KeyDown += delegate(object sender, KeyEventArgs e)
{
if(e.KeyData == (Keys.Control | Keys.F5))
{
UIUtil.SetHandled(e, true);
m_sdCustomData.Set("Example_Constant", "Constant value");
m_sdCustomData.Set("Example_Random", Program.GlobalRandom.Next().ToString());
UIUtil.StrDictListUpdate(m_lvCustomData, m_sdCustomData, (m_mvec != null));
}
};
m_lvCustomData.KeyUp += delegate(object sender, KeyEventArgs e)
{
if(e.KeyData == (Keys.Control | Keys.F5))
UIUtil.SetHandled(e, true);
};
#endif
m_tbUuid.Text = m_pwEntry.Uuid.ToHexString() + ", " +
Convert.ToBase64String(m_pwEntry.Uuid.UuidBytes);
if(m_pwEditMode == PwEditMode.ViewReadOnlyEntry)
{
m_cbCustomForegroundColor.Enabled = false;
m_cbCustomBackgroundColor.Enabled = false;
m_tbTags.ReadOnly = true;
m_cmbOverrideUrl.Enabled = false;
}
}
private void InitAutoTypeTab()
{
UIUtil.SetChecked(m_cbAutoTypeEnabled, m_atConfig.Enabled);
UIUtil.SetChecked(m_cbAutoTypeObfuscation, (m_atConfig.ObfuscationOptions !=
AutoTypeObfuscationOptions.None));
string strDefaultSeq = m_atConfig.DefaultSequence;
if(strDefaultSeq.Length > 0) m_rbAutoTypeOverride.Checked = true;
else m_rbAutoTypeSeqInherit.Checked = true;
if(strDefaultSeq.Length == 0)
{
PwGroup pg = m_pwEntry.ParentGroup;
if(pg != null)
{
strDefaultSeq = pg.GetAutoTypeSequenceInherited();
if(strDefaultSeq.Length == 0)
{
if(PwDefs.IsTanEntry(m_pwEntry))
strDefaultSeq = PwDefs.DefaultAutoTypeSequenceTan;
else
strDefaultSeq = PwDefs.DefaultAutoTypeSequence;
}
}
}
m_tbDefaultAutoTypeSeq.Text = strDefaultSeq;
m_lvAutoType.SmallImageList = m_ilIcons;
int nWidth = m_lvAutoType.ClientRectangle.Width / 2;
m_lvAutoType.Columns.Add(KPRes.TargetWindow, nWidth);
m_lvAutoType.Columns.Add(KPRes.Sequence, nWidth);
UpdateAutoTypeList(ListSelRestore.None, null, false);
if(m_pwEditMode == PwEditMode.ViewReadOnlyEntry)
m_cbAutoTypeEnabled.Enabled = false;
}
private void UpdateAutoTypeList(ListSelRestore r, AutoTypeAssociation aToSel,
bool bUpdateState)
{
UIScrollInfo uiScroll = UIUtil.GetScrollInfo(m_lvAutoType, true);
int s = m_lvAutoType.SelectedIndices.Count;
int[] vSel = null;
List<AutoTypeAssociation> lSel = new List<AutoTypeAssociation>();
if(aToSel != null) lSel.Add(aToSel);
if((r == ListSelRestore.ByIndex) && (s > 0))
{
vSel = new int[s];
m_lvAutoType.SelectedIndices.CopyTo(vSel, 0);
}
else if(r == ListSelRestore.ByRef)
{
foreach(ListViewItem lviSel in m_lvAutoType.SelectedItems)
{
AutoTypeAssociation a = (lviSel.Tag as AutoTypeAssociation);
if(a == null) { Debug.Assert(false); }
else lSel.Add(a);
}
}
m_lvAutoType.BeginUpdate();
m_lvAutoType.Items.Clear();
string strDefault = "(" + KPRes.Default + ")";
foreach(AutoTypeAssociation a in m_atConfig.Associations)
{
ListViewItem lvi = m_lvAutoType.Items.Add(a.WindowName, (int)PwIcon.List);
lvi.SubItems.Add((a.Sequence.Length > 0) ? a.Sequence : strDefault);
lvi.Tag = a;
foreach(AutoTypeAssociation aSel in lSel)
{
if(object.ReferenceEquals(a, aSel)) lvi.Selected = true;
}
}
if(vSel != null)
{
foreach(int iSel in vSel)
m_lvAutoType.Items[iSel].Selected = true;
}
UIUtil.Scroll(m_lvAutoType, uiScroll, true);
m_lvAutoType.EndUpdate();
if(bUpdateState) EnableControlsEx();
}
private void InitHistoryTab()
{
m_lblCreatedData.Text = TimeUtil.ToDisplayString(m_pwEntry.CreationTime);
m_lblModifiedData.Text = TimeUtil.ToDisplayString(m_pwEntry.LastModificationTime);
m_lvHistory.SmallImageList = m_ilIcons;
m_lvHistory.Columns.Add(KPRes.Version);
m_lvHistory.Columns.Add(KPRes.Title);
m_lvHistory.Columns.Add(KPRes.UserName);
m_lvHistory.Columns.Add(KPRes.Size, 72, HorizontalAlignment.Right);
UpdateHistoryList(false);
if((m_pwEditMode == PwEditMode.ViewReadOnlyEntry) || (m_mvec != null))
{
m_lblPrev.Enabled = false;
m_lvHistory.Enabled = false;
}
}
private void UpdateHistoryList(bool bUpdateState)
{
UIScrollInfo s = UIUtil.GetScrollInfo(m_lvHistory, true);
ImageList ilIcons = m_lvHistory.SmallImageList;
int ci = ((ilIcons != null) ? ilIcons.Images.Count : 0);
m_lvHistory.BeginUpdate();
m_lvHistory.Items.Clear();
foreach(PwEntry pe in m_vHistory)
{
ListViewItem lvi = m_lvHistory.Items.Add(TimeUtil.ToDisplayString(
pe.LastModificationTime));
int idxIcon = (int)pe.IconId;
PwUuid pu = pe.CustomIconUuid;
if(!pu.Equals(PwUuid.Zero))
{
// The user may have deleted the custom icon (using
// the icon dialog accessible through this entry
// dialog); continuing to show the deleted custom
// icon would be confusing
int idxNew = m_pwDatabase.GetCustomIconIndex(pu);
if(idxNew >= 0) // Icon not deleted
{
int idxOrg = m_lOrgCustomIconIDs.IndexOf(pu);
if(idxOrg >= 0) idxIcon = (int)PwIcon.Count + idxOrg;
else { Debug.Assert(false); }
}
}
if(idxIcon < ci) lvi.ImageIndex = idxIcon;
else { Debug.Assert(false); }
lvi.SubItems.Add(pe.Strings.ReadSafe(PwDefs.TitleField));
lvi.SubItems.Add(pe.Strings.ReadSafe(PwDefs.UserNameField));
lvi.SubItems.Add(StrUtil.FormatDataSizeKB(pe.GetSize()));
}
UIUtil.Scroll(m_lvHistory, s, true);
m_lvHistory.EndUpdate();
if(bUpdateState) EnableControlsEx();
}
private void ResizeColumnHeaders()
{
UIUtil.ResizeColumns(m_lvStrings, true);
UIUtil.ResizeColumns(m_lvBinaries, new int[] { 4, 1 }, true);
UIUtil.ResizeColumns(m_lvAutoType, true);
UIUtil.ResizeColumns(m_lvHistory, new int[] { 21, 20, 18, 11 }, true);
}
private void OnFormLoad(object sender, EventArgs e)
{
if(m_pwEntry == null) { Debug.Assert(false); throw new InvalidOperationException(); }
if(m_pwEditMode == PwEditMode.Invalid) { Debug.Assert(false); throw new InvalidOperationException(); }
if(m_pwDatabase == null) { Debug.Assert(false); throw new InvalidOperationException(); }
if(m_ilIcons == null) { Debug.Assert(false); throw new InvalidOperationException(); }
m_bInitializing = true;
// If there is an intermediate form, the custom icons
// in the image list may be outdated
Form fTop = GlobalWindowManager.TopWindow;
Debug.Assert(fTop != this); // Before adding ourself
if((fTop != null) && (fTop != Program.MainForm))
m_lOrgCustomIconIDs.Clear();
GlobalWindowManager.AddWindow(this);
GlobalWindowManager.CustomizeControl(m_ctxPwGen);
GlobalWindowManager.CustomizeControl(m_ctxStrMoveToStandard);
GlobalWindowManager.CustomizeControl(m_ctxBinAttach);
GlobalWindowManager.CustomizeControl(m_ctxTools);
m_pwInitialEntry = m_pwEntry.CloneDeep();
NormalizeStrings(m_pwInitialEntry.Strings, m_pwDatabase);
UIUtil.ConfigureToolTip(m_ttRect);
m_ttRect.SetToolTip(m_btnIcon, KPRes.SelectIcon);
// m_ttRect.SetToolTip(m_cbHidePassword, KPRes.TogglePasswordAsterisks);
m_ttRect.SetToolTip(m_btnGenPw, KPRes.GeneratePassword);
m_ttRect.SetToolTip(m_btnStandardExpires, KPRes.StandardExpireSelect);
UIUtil.ConfigureToolTip(m_ttBalloon);
m_ttBalloon.SetToolTip(m_tbRepeatPassword, KPRes.PasswordRepeatHint);
m_dynGenProfiles = new DynamicMenu(m_ctxPwGen.Items);
m_dynGenProfiles.MenuClick += this.OnProfilesDynamicMenuClick;
m_ctxNotes.Attach(m_rtNotes, this);
m_ctxBinOpen = new CustomContextMenuStripEx();
m_ctxBinOpen.Opening += this.OnCtxBinOpenOpening;
m_dynBinOpen = new DynamicMenu(m_ctxBinOpen.Items);
m_dynBinOpen.MenuClick += this.OnDynBinOpen;
m_btnBinOpen.SplitDropDownMenu = m_ctxBinOpen;
GlobalWindowManager.CustomizeControl(m_ctxBinOpen);
string strTitle = string.Empty, strDesc = string.Empty;
switch(m_pwEditMode)
{
case PwEditMode.AddNewEntry:
strTitle = KPRes.AddEntry;
strDesc = KPRes.AddEntryDesc;
break;
case PwEditMode.EditExistingEntry:
if(m_mvec != null)
{
strTitle = KPRes.EditEntries + " (" +
m_mvec.Entries.Length.ToString() + ")";
strDesc = KPRes.EditEntriesDesc;
}
else
{
strTitle = KPRes.EditEntry;
strDesc = KPRes.EditEntryDesc;
}
break;
case PwEditMode.ViewReadOnlyEntry:
strTitle = KPRes.ViewEntryReadOnly;
strDesc = KPRes.ViewEntryDesc;
break;
default:
Debug.Assert(false);
break;
}
BannerFactory.CreateBannerEx(this, m_bannerImage,
KeePass.Properties.Resources.B48x48_KGPG_Sign, strTitle, strDesc);
this.Icon = AppIcons.Default;
this.Text = strTitle;
// m_btnTools.Text += " \u23F7 \u25BC \u25BE \u2BC6 \uD83D\uDF83";
// m_btnTools.Width += DpiUtil.ScaleIntX(60);
m_imgGenPw = UIUtil.CreateDropDownImage(Properties.Resources.B16x16_Key_New);
m_imgStdExpire = UIUtil.CreateDropDownImage(Properties.Resources.B16x16_History);
Image imgOrg = Properties.Resources.B16x16_Package_Settings;
Image imgSc = UIUtil.SetButtonImage(m_btnTools, imgOrg, true);
if(!object.ReferenceEquals(imgOrg, imgSc))
m_imgTools = imgSc; // Only dispose scaled image
imgSc = UIUtil.SetButtonImage(m_btnGenPw, m_imgGenPw, true);
UIUtil.OverwriteIfNotEqual(ref m_imgGenPw, imgSc);
imgSc = UIUtil.SetButtonImage(m_btnStandardExpires, m_imgStdExpire, true);
UIUtil.OverwriteIfNotEqual(ref m_imgStdExpire, imgSc);
// UIUtil.SetExplorerTheme(m_lvStrings, true);
// UIUtil.SetExplorerTheme(m_lvBinaries, true);
// UIUtil.SetExplorerTheme(m_lvCustomData, true);
// UIUtil.SetExplorerTheme(m_lvAutoType, true);
// UIUtil.SetExplorerTheme(m_lvHistory, true);
UIUtil.PrepareStandardMultilineControl(m_rtNotes, true, true);
bool bForceHide = !AppPolicy.Current.UnhidePasswords;
if(Program.Config.UI.Hiding.SeparateHidingSettings)
m_cbHidePassword.Checked = (Program.Config.UI.Hiding.HideInEntryWindow || bForceHide);
else
{
AceColumn colPw = Program.Config.MainWindow.FindColumn(AceColumnType.Password);
m_cbHidePassword.Checked = (((colPw != null) ? colPw.HideWithAsterisks :
true) || bForceHide);
}
InitEntryTab();
InitAdvancedTab();
InitPropertiesTab();
InitAutoTypeTab();
InitHistoryTab();
UpdateEntryStrings(false, true, false);
UpdateEntryBinaries(false, false);
CustomizeForScreenReader();
if(m_mvec != null)
{
MultipleValuesEx.ConfigureText(m_tbTitle, true);
MultipleValuesEx.ConfigureText(m_tbUserName, true);
MultipleValuesEx.ConfigureText(m_tbPassword, true);
MultipleValuesEx.ConfigureText(m_tbRepeatPassword, true);
MultipleValuesEx.ConfigureText(m_tbUrl, true);
MultipleValuesEx.ConfigureText(m_rtNotes, true);
if(m_mvec.MultiExpiry)
MultipleValuesEx.ConfigureState(m_cbExpires, true);
UIUtil.SetEnabledFast(false, m_grpAttachments, m_lvBinaries);
if(m_mvec.MultiFgColor)
MultipleValuesEx.ConfigureState(m_cbCustomForegroundColor, true);
if(m_mvec.MultiBgColor)
MultipleValuesEx.ConfigureState(m_cbCustomBackgroundColor, true);
MultipleValuesEx.ConfigureText(m_tbTags, true);
MultipleValuesEx.ConfigureText(m_cmbOverrideUrl, true);
m_tbUuid.Text = MultipleValuesEx.CueString;
UIUtil.SetEnabledFast(false, m_lblUuid, m_tbUuid);
if(m_mvec.MultiAutoTypeEnabled)
MultipleValuesEx.ConfigureState(m_cbAutoTypeEnabled, true);
MultipleValuesEx.ConfigureText(m_tbDefaultAutoTypeSeq, true);
if(m_mvec.MultiAutoTypeObf)
MultipleValuesEx.ConfigureState(m_cbAutoTypeObfuscation, true);
m_lblCreatedData.Text = MultipleValuesEx.CueString;
UIUtil.SetEnabledFast(false, m_lblCreated, m_lblCreatedData);
m_lblModifiedData.Text = MultipleValuesEx.CueString;
UIUtil.SetEnabledFast(false, m_lblModified, m_lblModifiedData);
}
m_bInitializing = false;
if(m_bInitSwitchToHistory) // Before 'Advanced' tab switch
m_tabMain.SelectedTab = m_tabHistory;
else if(m_bShowAdvancedByDefault)
m_tabMain.SelectedTab = m_tabAdvanced;
ResizeColumnHeaders();
EnableControlsEx();
ThreadPool.QueueUserWorkItem(delegate(object state)
{
try
{
InitUserNameSuggestions();
InitOverridesBox();
string[] vSeq = m_pwDatabase.RootGroup.GetAutoTypeSequences(true);
// Do not append, because long suggestions hide the start
UIUtil.EnableAutoCompletion(m_tbDefaultAutoTypeSeq,
false, vSeq); // Invokes
}
catch(Exception) { Debug.Assert(false); }
});
if(MonoWorkarounds.IsRequired(2140)) Application.DoEvents();
if(m_pwEditMode == PwEditMode.ViewReadOnlyEntry)
UIUtil.SetFocus(m_btnCancel, this);
else
{
if(m_bSelectFullTitle) m_tbTitle.Select(0, m_tbTitle.TextLength);
else m_tbTitle.Select(0, 0);
UIUtil.SetFocus(m_tbTitle, this);
}
}
private void CustomizeForScreenReader()
{
if(!Program.Config.UI.OptimizeForScreenReader) return;
m_btnIcon.Text = KPRes.PickIcon;
m_cbHidePassword.Text = KPRes.HideUsingAsterisks;
m_btnGenPw.Text = m_ttRect.GetToolTip(m_btnGenPw);
m_btnStandardExpires.Text = m_ttRect.GetToolTip(m_btnStandardExpires);
m_btnPickFgColor.Text = KPRes.SelectColor;
m_btnPickBgColor.Text = KPRes.SelectColor;
m_btnAutoTypeUp.Text = "\u2191"; // Upwards arrow
m_btnAutoTypeDown.Text = "\u2193"; // Downwards arrow
}
private void EnableControlsEx()
{
if(m_bInitializing) return;
bool bEdit = (m_pwEditMode != PwEditMode.ViewReadOnlyEntry);
bool bMulti = (m_mvec != null);
int nStringsSel = m_lvStrings.SelectedIndices.Count;
int nBinSel = m_lvBinaries.SelectedIndices.Count;
int nAutoTypeSel = m_lvAutoType.SelectedIndices.Count;
int nHistorySel = m_lvHistory.SelectedIndices.Count;
bool bAutoType = (m_cbAutoTypeEnabled.CheckState != CheckState.Unchecked);
bool bAutoTypeCustomEdit = (bEdit && !bMulti && bAutoType);
m_btnStrEdit.Enabled = (nStringsSel == 1); // Supports read-only
m_btnStrDelete.Enabled = (bEdit && (nStringsSel >= 1));
m_btnStrMove.Enabled = (bEdit && !bMulti && (nStringsSel == 1));
UIUtil.SetEnabledFast((bEdit && !bMulti && (nStringsSel == 1)),
m_menuListCtxMoveStandardTitle, m_menuListCtxMoveStandardUser,
m_menuListCtxMoveStandardPassword, m_menuListCtxMoveStandardURL,
m_menuListCtxMoveStandardNotes);
m_btnBinDelete.Enabled = (bEdit && (nBinSel >= 1));
m_btnBinOpen.Enabled = (nBinSel == 1);
m_btnBinSave.Enabled = (nBinSel >= 1);
m_btnPickFgColor.Enabled = (bEdit &&
(m_cbCustomForegroundColor.CheckState == CheckState.Checked));
m_btnPickBgColor.Enabled = (bEdit &&
(m_cbCustomBackgroundColor.CheckState == CheckState.Checked));
bool bUrlEmpty = (m_tbUrl.TextLength == 0);
bool bUrlOverrideEmpty = (m_cmbOverrideUrl.Text.Length == 0);
bool bWarn = (bUrlEmpty && !bUrlOverrideEmpty);
if(bWarn != m_bUrlOverrideWarning)
{
if(bWarn) m_cmbOverrideUrl.BackColor = AppDefs.ColorEditError;
else m_cmbOverrideUrl.ResetBackColor();
try
{
m_ttBalloon.SetToolTip(m_cmbOverrideUrl, (bWarn ?
KPRes.UrlFieldEmptyFirstTab : string.Empty));
}
catch(Exception) { Debug.Assert(false); }
m_bUrlOverrideWarning = bWarn;
}
m_btnCDDel.Enabled = (bEdit && (m_lvCustomData.SelectedIndices.Count > 0));
UIUtil.SetEnabledFast((bEdit && bAutoType), m_rbAutoTypeSeqInherit,
m_rbAutoTypeOverride);
UIUtil.SetEnabledFast((bEdit && bAutoType && m_rbAutoTypeOverride.Checked),
m_tbDefaultAutoTypeSeq, m_btnAutoTypeEditDefault);
UIUtil.SetEnabledFast((!bMulti && bAutoType), m_lblCustomAutoType,
m_lvAutoType);
m_btnAutoTypeAdd.Enabled = bAutoTypeCustomEdit;
m_btnAutoTypeEdit.Enabled = (bAutoTypeCustomEdit && (nAutoTypeSel == 1));
UIUtil.SetEnabledFast((bAutoTypeCustomEdit && (nAutoTypeSel >= 1)),
m_btnAutoTypeDelete, m_btnAutoTypeUp, m_btnAutoTypeDown);
m_cbAutoTypeObfuscation.Enabled = (bEdit && bAutoType);
int nListCtxSel = nStringsSel + nAutoTypeSel;
m_menuListCtxCopyFieldValue.Enabled = (nListCtxSel != 0);
UIUtil.SetEnabledFast((bEdit && !bMulti && (nHistorySel == 1)),
m_btnHistoryView, m_btnHistoryRestore);
m_btnHistoryDelete.Enabled = (bEdit && !bMulti && (nHistorySel >= 1));
}
private bool SaveEntry(PwEntry peTarget, bool bValidate)
{
if(m_pwEditMode == PwEditMode.ViewReadOnlyEntry) return true;
if(bValidate && !m_icgPassword.ValidateData(true)) return false;
bool bPri = object.ReferenceEquals(peTarget, m_pwEntry);
if((this.EntrySaving != null) && bPri)
{
CancellableOperationEventArgs eaCancel = new CancellableOperationEventArgs();
this.EntrySaving(this, eaCancel);
if(eaCancel.Cancel) return false;
}
peTarget.History = m_vHistory; // Must be called before CreateBackup()
bool bCreateBackup = (m_pwEditMode != PwEditMode.AddNewEntry);
if(bCreateBackup) peTarget.CreateBackup(null);
peTarget.IconId = m_pwEntryIcon;
peTarget.CustomIconUuid = m_pwCustomIconID;
if(m_cbCustomForegroundColor.Checked)
peTarget.ForegroundColor = m_clrForeground;
else peTarget.ForegroundColor = Color.Empty;
if(m_cbCustomBackgroundColor.Checked)
peTarget.BackgroundColor = m_clrBackground;
else peTarget.BackgroundColor = Color.Empty;
peTarget.OverrideUrl = m_cmbOverrideUrl.Text;
List<string> vNewTags = StrUtil.StringToTags(m_tbTags.Text);
peTarget.Tags.Clear();
foreach(string strTag in vNewTags) peTarget.AddTag(strTag);
peTarget.Expires = m_cgExpiry.Checked;
if(peTarget.Expires) peTarget.ExpiryTime = m_cgExpiry.Value;
UpdateEntryStrings(true, false, false);
peTarget.Strings = m_vStrings;
peTarget.Binaries = m_vBinaries;
peTarget.CustomData = m_sdCustomData;
m_atConfig.Enabled = m_cbAutoTypeEnabled.Checked;
m_atConfig.ObfuscationOptions = (m_cbAutoTypeObfuscation.Checked ?
AutoTypeObfuscationOptions.UseClipboard :
AutoTypeObfuscationOptions.None);
SaveDefaultSeq();
peTarget.AutoType = m_atConfig;
peTarget.Touch(true, false); // Touch *after* backup
if(bPri) m_bTouchedOnce = true;
bool bUndoBackup = false;
PwCompareOptions cmpOpt = m_cmpOpt;
if(bCreateBackup) cmpOpt |= PwCompareOptions.IgnoreLastBackup;
if(peTarget.EqualsEntry(m_pwInitialEntry, cmpOpt, MemProtCmpMode.CustomOnly))
{
// No modifications at all => restore last mod time and undo backup
peTarget.LastModificationTime = m_pwInitialEntry.LastModificationTime;
bUndoBackup = bCreateBackup;
}
else if(bCreateBackup)
{
// If only history items have been modified (deleted) => undo
// backup, but without restoring the last mod time
PwCompareOptions cmpOptNH = (m_cmpOpt | PwCompareOptions.IgnoreHistory);
if(peTarget.EqualsEntry(m_pwInitialEntry, cmpOptNH, MemProtCmpMode.CustomOnly))
bUndoBackup = true;
}
if(bUndoBackup) peTarget.History.RemoveAt(peTarget.History.UCount - 1);
peTarget.MaintainBackups(m_pwDatabase);
if(m_mvec != null)
{
m_mvec.MultiExpiry = (m_cbExpires.CheckState == CheckState.Indeterminate);
m_mvec.MultiFgColor = (m_cbCustomForegroundColor.CheckState == CheckState.Indeterminate);
m_mvec.MultiBgColor = (m_cbCustomBackgroundColor.CheckState == CheckState.Indeterminate);
m_mvec.MultiAutoTypeEnabled = (m_cbAutoTypeEnabled.CheckState == CheckState.Indeterminate);
m_mvec.MultiAutoTypeObf = (m_cbAutoTypeObfuscation.CheckState == CheckState.Indeterminate);
}
if((this.EntrySaved != null) && bPri)
this.EntrySaved(this, EventArgs.Empty);
return true;
}
private void SaveDefaultSeq()
{
if(m_rbAutoTypeSeqInherit.Checked)
m_atConfig.DefaultSequence = string.Empty;
else if(m_rbAutoTypeOverride.Checked)
m_atConfig.DefaultSequence = m_tbDefaultAutoTypeSeq.Text;
else { Debug.Assert(false); }
}
private void OnBtnOK(object sender, EventArgs e)
{
if(SaveEntry(m_pwEntry, true)) m_bForceClosing = true;
else this.DialogResult = DialogResult.None;
}
private void OnBtnCancel(object sender, EventArgs e)
{
m_bForceClosing = true;
try
{
ushort usEsc = NativeMethods.GetAsyncKeyState((int)Keys.Escape);
if((usEsc & 0x8000) != 0) m_bForceClosing = false;
}
catch(Exception) { Debug.Assert(NativeLib.IsUnix()); }
}
private void CleanUpEx()
{
m_dynGenProfiles.MenuClick -= this.OnProfilesDynamicMenuClick;
m_dynGenProfiles.Clear();
m_btnBinOpen.SplitDropDownMenu = null;
m_dynBinOpen.MenuClick -= this.OnDynBinOpen;
m_dynBinOpen.Clear();
m_ctxBinOpen.Opening -= this.OnCtxBinOpenOpening;
m_ctxBinOpen.Dispose();
if(m_pwEditMode != PwEditMode.ViewReadOnlyEntry)
Program.Config.UI.Hiding.HideInEntryWindow = m_cbHidePassword.Checked;
m_ctxNotes.Detach();
m_icgPassword.Release();
m_cgExpiry.Release();
m_cmbOverrideUrl.OrderedImageList = null;
foreach(Image img in m_lOverrideUrlIcons)
{
if(img != null) img.Dispose();
}
m_lOverrideUrlIcons.Clear();
// Detach event handlers
m_lvStrings.SmallImageList = null;
// m_lvBinaries.SmallImageList = null;
FileIcons.ReleaseImages(m_lvBinaries);
m_lvAutoType.SmallImageList = null;
m_lvHistory.SmallImageList = null;
if(m_imgTools != null) // Only dispose scaled image
UIUtil.DisposeButtonImage(m_btnTools, ref m_imgTools);
UIUtil.DisposeButtonImage(m_btnGenPw, ref m_imgGenPw);
UIUtil.DisposeButtonImage(m_btnStandardExpires, ref m_imgStdExpire);
UIUtil.DisposeButtonImage(m_btnPickFgColor, ref m_imgColorFg);
UIUtil.DisposeButtonImage(m_btnPickBgColor, ref m_imgColorBg);
}
private void OnBtnStrAdd(object sender, EventArgs e)
{
UpdateEntryStrings(true, false, false);
EditStringForm esf = new EditStringForm();
esf.InitEx(m_vStrings, null, null, m_pwDatabase);
if(UIUtil.ShowDialogAndDestroy(esf) == DialogResult.OK)
{
UpdateEntryStrings(false, false, true);
ResizeColumnHeaders();
}
}
private void OnBtnStrEdit(object sender, EventArgs e)
{
ListView.SelectedListViewItemCollection vSel = m_lvStrings.SelectedItems;
if(vSel.Count <= 0) return;
UpdateEntryStrings(true, false, false);
string strName = vSel[0].Text;
ProtectedString psValue = m_vStrings.Get(strName);
if(psValue == null) { Debug.Assert(false); return; }
EditStringForm esf = new EditStringForm();
esf.InitEx(m_vStrings, strName, psValue, m_pwDatabase);
esf.ReadOnlyEx = (m_pwEditMode == PwEditMode.ViewReadOnlyEntry);
esf.MultipleValuesEntryContext = m_mvec;
if(UIUtil.ShowDialogAndDestroy(esf) == DialogResult.OK)
UpdateEntryStrings(false, false, true);
}
private void OnBtnStrDelete(object sender, EventArgs e)
{
UpdateEntryStrings(true, false, false);
ListView.SelectedListViewItemCollection lvsc = m_lvStrings.SelectedItems;
foreach(ListViewItem lvi in lvsc)
{
if(!m_vStrings.Remove(lvi.Text)) { Debug.Assert(false); }
}
if(lvsc.Count > 0)
{
UpdateEntryStrings(false, false, true);
ResizeColumnHeaders();
}
}
private void OnBtnBinAdd(object sender, EventArgs e)
{
m_ctxBinAttach.ShowEx(m_btnBinAdd);
}
private void OnBtnBinDelete(object sender, EventArgs e)
{
UpdateEntryBinaries(true, false);
ListView.SelectedListViewItemCollection lvsc = m_lvBinaries.SelectedItems;
foreach(ListViewItem lvi in lvsc)
{
if(!m_vBinaries.Remove(lvi.Text)) { Debug.Assert(false); }
}
if(lvsc.Count > 0)
{
UpdateEntryBinaries(false, true);
ResizeColumnHeaders();
}
}
private void OnBtnBinSave(object sender, EventArgs e)
{
ListView.SelectedListViewItemCollection lvsc = m_lvBinaries.SelectedItems;
int nSelCount = lvsc.Count;
if(nSelCount == 0) { Debug.Assert(false); return; }
if(nSelCount == 1)
{
SaveFileDialogEx sfd = UIUtil.CreateSaveFileDialog(KPRes.AttachmentSave,
UrlUtil.GetSafeFileName(lvsc[0].Text), UIUtil.CreateFileTypeFilter(
null, null, true), 1, null, AppDefs.FileDialogContext.Attachments);
if(sfd.ShowDialog() == DialogResult.OK)
SaveAttachmentTo(lvsc[0], sfd.FileName, false);
}
else // nSelCount > 1
{
FolderBrowserDialog fbd = UIUtil.CreateFolderBrowserDialog(KPRes.AttachmentsSave);
if(fbd.ShowDialog() == DialogResult.OK)
{
string strRootPath = UrlUtil.EnsureTerminatingSeparator(
fbd.SelectedPath, false);
foreach(ListViewItem lvi in lvsc)
SaveAttachmentTo(lvi, strRootPath + UrlUtil.GetSafeFileName(
lvi.Text), true);
}
fbd.Dispose();
}
}
private void SaveAttachmentTo(ListViewItem lvi, string strFile,
bool bConfirmOverwrite)
{
if(lvi == null) { Debug.Assert(false); return; }
if(string.IsNullOrEmpty(strFile)) { Debug.Assert(false); return; }
if(bConfirmOverwrite && File.Exists(strFile))
{
string strMsg = KPRes.FileExistsAlready + MessageService.NewLine +
strFile + MessageService.NewParagraph +
KPRes.OverwriteExistingFileQuestion;
if(!MessageService.AskYesNo(strMsg)) return;
}
ProtectedBinary pb = m_vBinaries.Get(lvi.Text);
if(pb == null) { Debug.Assert(false); return; }
byte[] pbData = pb.ReadData();
try { File.WriteAllBytes(strFile, pbData); }
catch(Exception exWrite)
{
MessageService.ShowWarning(strFile, exWrite);
}
if(pb.IsProtected) MemUtil.ZeroByteArray(pbData);
}
private void OnBtnAutoTypeAdd(object sender, EventArgs e)
{
EditAutoTypeItemForm dlg = new EditAutoTypeItemForm();
dlg.InitEx(m_atConfig, -1, false, m_tbDefaultAutoTypeSeq.Text, m_vStrings);
if(UIUtil.ShowDialogAndDestroy(dlg) == DialogResult.OK)
{
AutoTypeAssociation a = null;
if(m_atConfig.AssociationsCount > 0)
a = m_atConfig.GetAt(m_atConfig.AssociationsCount - 1);
else { Debug.Assert(false); }
UpdateAutoTypeList(ListSelRestore.None, a, true);
ResizeColumnHeaders();
}
}
private void OnBtnAutoTypeEdit(object sender, EventArgs e)
{
ListView.SelectedIndexCollection lvsic = m_lvAutoType.SelectedIndices;
if(lvsic.Count != 1) { Debug.Assert(false); return; }
EditAutoTypeItemForm dlg = new EditAutoTypeItemForm();
dlg.InitEx(m_atConfig, lvsic[0], false, m_tbDefaultAutoTypeSeq.Text,
m_vStrings);
if(UIUtil.ShowDialogAndDestroy(dlg) == DialogResult.OK)
UpdateAutoTypeList(ListSelRestore.ByIndex, null, true);
}
private void OnBtnAutoTypeDelete(object sender, EventArgs e)
{
for(int i = m_lvAutoType.Items.Count - 1; i >= 0; --i)
{
if(m_lvAutoType.Items[i].Selected)
m_atConfig.RemoveAt(i);
}
UpdateAutoTypeList(ListSelRestore.None, null, true);
ResizeColumnHeaders();
}
private void OnBtnHistoryView(object sender, EventArgs e)
{
Debug.Assert(m_vHistory.UCount == m_lvHistory.Items.Count);
ListView.SelectedIndexCollection lvsic = m_lvHistory.SelectedIndices;
if(lvsic.Count != 1) { Debug.Assert(false); return; }
PwEntry pe = m_vHistory.GetAt((uint)lvsic[0]);
if(pe == null) { Debug.Assert(false); return; }
PwEntryForm pwf = new PwEntryForm();
pwf.InitEx(pe, PwEditMode.ViewReadOnlyEntry, m_pwDatabase,
m_ilIcons, false, false);
UIUtil.ShowDialogAndDestroy(pwf);
}
private void OnBtnHistoryDelete(object sender, EventArgs e)
{
Debug.Assert(m_vHistory.UCount == m_lvHistory.Items.Count);
ListView.SelectedIndexCollection lvsic = m_lvHistory.SelectedIndices;
int n = lvsic.Count; // Getting Count sends a message
if(n == 0) return;
// LVSIC: one access by index requires O(n) time, thus copy
// all to an array (which requires O(1) for each element)
int[] v = new int[n];
lvsic.CopyTo(v, 0);
for(int i = 0; i < n; ++i)
m_vHistory.RemoveAt((uint)v[n - i - 1]);
UpdateHistoryList(true);
ResizeColumnHeaders();
}
private void OnBtnHistoryRestore(object sender, EventArgs e)
{
Debug.Assert(m_vHistory.UCount == m_lvHistory.Items.Count);
ListView.SelectedIndexCollection lvsic = m_lvHistory.SelectedIndices;
if(lvsic.Count != 1) { Debug.Assert(false); return; }
m_pwEntry.RestoreFromBackup((uint)lvsic[0], m_pwDatabase);
m_pwEntry.Touch(true, false);
m_bTouchedOnce = true;
this.DialogResult = DialogResult.OK; // Doesn't invoke OnBtnOK
}
private void OnHistorySelectedIndexChanged(object sender, EventArgs e)
{
EnableControlsEx();
}
private void OnStringsSelectedIndexChanged(object sender, EventArgs e)
{
EnableControlsEx();
}
private void OnBinariesSelectedIndexChanged(object sender, EventArgs e)
{
EnableControlsEx();
}
private void SetExpireIn(int nYears, int nMonths, int nDays)
{
DateTime dt = DateTime.Now; // Not UTC
if((nYears != 0) || (nMonths != 0) || (nDays != 0))
{
dt = dt.Date; // Remove time part
dt = dt.AddYears(nYears);
dt = dt.AddMonths(nMonths);
dt = dt.AddDays(nDays);
DateTime dtPrev = TimeUtil.ToLocal(m_cgExpiry.Value, false);
dt = dt.AddHours(dtPrev.Hour);
dt = dt.AddMinutes(dtPrev.Minute);
dt = dt.AddSeconds(dtPrev.Second);
}
// else do not change the time part of dt
m_cgExpiry.Checked = true;
m_cgExpiry.Value = dt;
EnableControlsEx();
}
private void OnMenuExpireNow(object sender, EventArgs e)
{
SetExpireIn(0, 0, 0);
}
private void OnMenuExpire1Week(object sender, EventArgs e)
{
SetExpireIn(0, 0, 7);
}
private void OnMenuExpire2Weeks(object sender, EventArgs e)
{
SetExpireIn(0, 0, 14);
}
private void OnMenuExpire1Month(object sender, EventArgs e)
{
SetExpireIn(0, 1, 0);
}
private void OnMenuExpire3Months(object sender, EventArgs e)
{
SetExpireIn(0, 3, 0);
}
private void OnMenuExpire6Months(object sender, EventArgs e)
{
SetExpireIn(0, 6, 0);
}
private void OnMenuExpire1Year(object sender, EventArgs e)
{
SetExpireIn(1, 0, 0);
}
private void OnBtnStandardExpiresClick(object sender, EventArgs e)
{
m_ctxDefaultTimes.ShowEx(m_btnStandardExpires);
}
private void OnCtxCopyFieldValue(object sender, EventArgs e)
{
ListView.SelectedListViewItemCollection lvsc;
if(m_lvStrings.Focused)
{
lvsc = m_lvStrings.SelectedItems;
if((lvsc != null) && (lvsc.Count > 0))
{
string strName = lvsc[0].Text;
ClipboardUtil.Copy(m_vStrings.ReadSafe(strName), true, true,
null, m_pwDatabase, this.Handle);
}
}
else if(m_lvAutoType.Focused)
{
lvsc = m_lvAutoType.SelectedItems;
if((lvsc != null) && (lvsc.Count > 0))
ClipboardUtil.Copy(lvsc[0].SubItems[1].Text, false, true,
null, null, this.Handle);
}
else { Debug.Assert(false); }
}
private void OnBtnPickIcon(object sender, EventArgs e)
{
IconPickerForm ipf = new IconPickerForm();
ipf.InitEx(m_ilIcons, (uint)PwIcon.Count, m_pwDatabase,
(uint)m_pwEntryIcon, m_pwCustomIconID);
if(ipf.ShowDialog() == DialogResult.OK)
{
if(!ipf.ChosenCustomIconUuid.Equals(PwUuid.Zero)) // Custom icon
{
m_pwCustomIconID = ipf.ChosenCustomIconUuid;
UIUtil.SetButtonImage(m_btnIcon, DpiUtil.GetIcon(
m_pwDatabase, m_pwCustomIconID), true);
}
else // Standard icon
{
m_pwEntryIcon = (PwIcon)ipf.ChosenIconId;
m_pwCustomIconID = PwUuid.Zero;
UIUtil.SetButtonImage(m_btnIcon, m_ilIcons.Images[
(int)m_pwEntryIcon], true);
}
}
UIUtil.DestroyForm(ipf);
UpdateHistoryList(true); // User may have deleted a custom icon
}
private void OnAutoTypeSeqInheritCheckedChanged(object sender, EventArgs e)
{
EnableControlsEx();
}
private void OnAutoTypeEnableCheckedChanged(object sender, EventArgs e)
{
EnableControlsEx();
}
private void OnBtnAutoTypeEditDefault(object sender, EventArgs e)
{
SaveDefaultSeq();
EditAutoTypeItemForm ef = new EditAutoTypeItemForm();
ef.InitEx(m_atConfig, -1, true, m_tbDefaultAutoTypeSeq.Text, m_vStrings);
if(UIUtil.ShowDialogAndDestroy(ef) == DialogResult.OK)
m_tbDefaultAutoTypeSeq.Text = m_atConfig.DefaultSequence;
}
private void OnCtxMoveToTitle(object sender, EventArgs e)
{
MoveSelectedStringTo(PwDefs.TitleField);
}
private void OnCtxMoveToUserName(object sender, EventArgs e)
{
MoveSelectedStringTo(PwDefs.UserNameField);
}
private void OnCtxMoveToPassword(object sender, EventArgs e)
{
MoveSelectedStringTo(PwDefs.PasswordField);
}
private void OnCtxMoveToURL(object sender, EventArgs e)
{
MoveSelectedStringTo(PwDefs.UrlField);
}
private void OnCtxMoveToNotes(object sender, EventArgs e)
{
MoveSelectedStringTo(PwDefs.NotesField);
}
private void MoveSelectedStringTo(string strFieldTo)
{
ListView.SelectedListViewItemCollection lvsic = m_lvStrings.SelectedItems;
if(lvsic.Count != 1) { Debug.Assert(false); return; }
string strFieldFrom = lvsic[0].Text;
string strValue = m_vStrings.ReadSafe(strFieldFrom);
if(PwDefs.IsStandardField(strFieldTo) && (strFieldTo != PwDefs.NotesField))
strValue = StrUtil.MultiToSingleLine(strValue).Trim();
if(strFieldTo == PwDefs.TitleField)
{
if((m_tbTitle.TextLength > 0) && (strValue.Length > 0))
strValue = ", " + strValue;
m_tbTitle.Text += strValue;
}
else if(strFieldTo == PwDefs.UserNameField)
{
if((m_tbUserName.TextLength > 0) && (strValue.Length > 0))
strValue = ", " + strValue;
m_tbUserName.Text += strValue;
}
else if(strFieldTo == PwDefs.PasswordField)
{
ProtectedString psP = m_icgPassword.GetPasswordEx();
if(!psP.IsEmpty && (strValue.Length > 0)) psP += ", ";
psP += strValue;
ProtectedString psR = m_icgPassword.GetRepeatEx();
if(!psR.IsEmpty && (strValue.Length > 0)) psR += ", ";
psR += strValue;
m_icgPassword.SetPasswords(psP, psR);
}
else if(strFieldTo == PwDefs.UrlField)
{
if((m_tbUrl.TextLength > 0) && (strValue.Length > 0))
strValue = ", " + strValue;
m_tbUrl.Text += strValue;
}
else if(strFieldTo == PwDefs.NotesField)
{
if((m_rtNotes.TextLength > 0) && (strValue.Length > 0))
strValue = MessageService.NewParagraph + strValue;
m_rtNotes.Text += strValue;
}
else { Debug.Assert(false); }
UpdateEntryStrings(true, false, false);
m_vStrings.Remove(strFieldFrom);
UpdateEntryStrings(false, false, true);
}
private void OnBtnStrMove(object sender, EventArgs e)
{
m_ctxStrMoveToStandard.ShowEx(m_btnStrMove);
}
private void OnAutoTypeSelectedIndexChanged(object sender, EventArgs e)
{
EnableControlsEx();
}
private void OnAutoTypeItemActivate(object sender, EventArgs e)
{
if(m_btnAutoTypeEdit.Enabled) OnBtnAutoTypeEdit(sender, e);
}
private void OnStringsItemActivate(object sender, EventArgs e)
{
OnBtnStrEdit(sender, e);
}
private void OnPwGenOpen(object sender, EventArgs e)
{
PwProfile opt = null;
ProtectedString ps = m_icgPassword.GetPasswordEx();
if(!ps.IsEmpty && !IsPasswordMultipleValues())
opt = PwProfile.DeriveFromPassword(ps);
PwGeneratorForm pgf = new PwGeneratorForm();
pgf.InitEx(opt, true, false);
if(pgf.ShowDialog() == DialogResult.OK)
{
byte[] pbEntropy = EntropyForm.CollectEntropyIfEnabled(pgf.SelectedProfile);
ProtectedString psNew = PwGeneratorUtil.GenerateAcceptable(
pgf.SelectedProfile, pbEntropy, m_pwEntry, m_pwDatabase, true);
m_icgPassword.SetPassword(psNew, true);
}
UIUtil.DestroyForm(pgf);
EnableControlsEx();
}
private void OnProfilesDynamicMenuClick(object sender, DynamicMenuEventArgs e)
{
string strProfile = (e.Tag as string);
if(strProfile == null) { Debug.Assert(false); return; }
PwProfile pwp = null;
if(strProfile == DeriveFromPrevious)
{
ProtectedString psCur = m_icgPassword.GetPasswordEx();
pwp = PwProfile.DeriveFromPassword(psCur);
}
else if(strProfile == AutoGenProfile)
pwp = Program.Config.PasswordGenerator.AutoGeneratedPasswordsProfile;
else
{
foreach(PwProfile pwgo in PwGeneratorUtil.GetAllProfiles(false))
{
if(pwgo.Name == strProfile)
{
pwp = pwgo;
break;
}
}
}
if(pwp != null)
{
ProtectedString psNew = PwGeneratorUtil.GenerateAcceptable(
pwp, null, m_pwEntry, m_pwDatabase, true);
m_icgPassword.SetPassword(psNew, true);
}
else { Debug.Assert(false); }
}
private bool IsPasswordMultipleValues()
{
if(m_mvec == null) return false;
ProtectedString ps = m_icgPassword.GetPasswordEx();
return ps.Equals(MultipleValuesEx.CueProtectedString, false);
}
private void OnPwGenClick(object sender, EventArgs e)
{
m_dynGenProfiles.Clear();
m_dynGenProfiles.AddSeparator();
List<char> lAvailKeys = new List<char>(PwCharSet.MenuAccels);
ToolStripMenuItem tsmiDerive = DynAddProfile(DeriveFromPrevious,
Properties.Resources.B16x16_CompFile, lAvailKeys);
if(IsPasswordMultipleValues()) tsmiDerive.Enabled = false;
DynAddProfile(AutoGenProfile, Properties.Resources.B16x16_FileNew, lAvailKeys);
bool bHideBuiltIn = ((Program.Config.UI.UIFlags &
(ulong)AceUIFlags.HideBuiltInPwGenPrfInEntryDlg) != 0);
List<KeyValuePair<string, Image>> l = new List<KeyValuePair<string, Image>>();
foreach(PwProfile pwgo in PwGeneratorUtil.GetAllProfiles(true))
{
if((pwgo.Name != DeriveFromPrevious) && (pwgo.Name != AutoGenProfile))
{
if(bHideBuiltIn && PwGeneratorUtil.IsBuiltInProfile(pwgo.Name))
continue;
l.Add(new KeyValuePair<string, Image>(pwgo.Name,
Properties.Resources.B16x16_KOrganizer));
}
}
if(l.Count > 0) m_dynGenProfiles.AddSeparator();
foreach(KeyValuePair<string, Image> kvp in l)
DynAddProfile(kvp.Key, kvp.Value, lAvailKeys);
m_ctxPwGen.ShowEx(m_btnGenPw);
}
private ToolStripMenuItem DynAddProfile(string strProfile, Image img,
List<char> lAvailKeys)
{
string strText = StrUtil.EncodeMenuText(strProfile);
strText = StrUtil.AddAccelerator(strText, lAvailKeys);
return m_dynGenProfiles.AddItem(strText, img, strProfile);
}
private void OnPickForegroundColor(object sender, EventArgs e)
{
Color? clr = UIUtil.ShowColorDialog(m_clrForeground);
if(clr.HasValue)
{
m_clrForeground = clr.Value;
UIUtil.OverwriteButtonImage(m_btnPickFgColor, ref m_imgColorFg,
UIUtil.CreateColorBitmap24(m_btnPickFgColor, m_clrForeground));
}
}
private void OnPickBackgroundColor(object sender, EventArgs e)
{
Color? clr = UIUtil.ShowColorDialog(m_clrBackground);
if(clr.HasValue)
{
m_clrBackground = clr.Value;
UIUtil.OverwriteButtonImage(m_btnPickBgColor, ref m_imgColorBg,
UIUtil.CreateColorBitmap24(m_btnPickBgColor, m_clrBackground));
}
}
private void OnCustomForegroundColorCheckedChanged(object sender, EventArgs e)
{
EnableControlsEx();
}
private void OnCustomBackgroundColorCheckedChanged(object sender, EventArgs e)
{
EnableControlsEx();
}
private void OnFormClosed(object sender, FormClosedEventArgs e)
{
GlobalWindowManager.RemoveWindow(this);
}
private void OnAutoTypeObfuscationLink(object sender, LinkLabelLinkClickedEventArgs e)
{
if(e.Button == MouseButtons.Left)
AppHelp.ShowHelp(AppDefs.HelpTopics.AutoTypeObfuscation, null);
}
private void OnAutoTypeObfuscationCheckedChanged(object sender, EventArgs e)
{
if(m_bInitializing) return;
if(m_cbAutoTypeObfuscation.CheckState != CheckState.Checked) return;
if((Program.Config.UI.UIFlags & (ulong)AceUIFlags.HideAutoTypeObfInfo) != 0)
return;
MessageService.ShowInfo(KPRes.AutoTypeObfuscationHint,
KPRes.DocumentationHint);
}
private bool GetSelBin(out string strDataItem, out ProtectedBinary pb)
{
strDataItem = null;
pb = null;
ListView.SelectedListViewItemCollection lvsic = m_lvBinaries.SelectedItems;
if((lvsic == null) || (lvsic.Count != 1)) return false; // No assert
strDataItem = lvsic[0].Text;
pb = m_vBinaries.Get(strDataItem);
if(pb == null) { Debug.Assert(false); return false; }
return true;
}
private void OpenSelBin(BinaryDataOpenOptions optBase)
{
string strDataItem;
ProtectedBinary pb;
if(!GetSelBin(out strDataItem, out pb)) return;
BinaryDataOpenOptions opt = ((optBase != null) ? optBase.CloneDeep() :
new BinaryDataOpenOptions());
if(m_pwEditMode == PwEditMode.ViewReadOnlyEntry)
{
if(optBase == null)
opt.Handler = BinaryDataHandler.InternalViewer;
opt.ReadOnly = true;
}
ProtectedBinary pbMod = BinaryDataUtil.Open(strDataItem, pb, opt);
if(pbMod != null)
{
m_vBinaries.Set(strDataItem, pbMod);
UpdateEntryBinaries(false, true, strDataItem); // Update size
}
}
private void OnBtnBinOpen(object sender, EventArgs e)
{
OpenSelBin(null);
}
private void OnDynBinOpen(object sender, DynamicMenuEventArgs e)
{
if(e == null) { Debug.Assert(false); return; }
BinaryDataOpenOptions opt = (e.Tag as BinaryDataOpenOptions);
if(opt == null) { Debug.Assert(false); return; }
OpenSelBin(opt);
}
private void OnCtxBinOpenOpening(object sender, CancelEventArgs e)
{
string strDataItem;
ProtectedBinary pb;
if(!GetSelBin(out strDataItem, out pb))
{
e.Cancel = true;
return;
}
BinaryDataUtil.BuildOpenWithMenu(m_dynBinOpen, strDataItem, pb,
(m_pwEditMode == PwEditMode.ViewReadOnlyEntry));
}
private void OnBtnTools(object sender, EventArgs e)
{
m_ctxTools.ShowEx(m_btnTools);
}
private void OnCtxToolsHelp(object sender, EventArgs e)
{
if(m_tabMain.SelectedTab == m_tabAdvanced)
AppHelp.ShowHelp(AppDefs.HelpTopics.Entry, AppDefs.HelpTopics.EntryStrings);
else if(m_tabMain.SelectedTab == m_tabAutoType)
AppHelp.ShowHelp(AppDefs.HelpTopics.Entry, AppDefs.HelpTopics.EntryAutoType);
else if(m_tabMain.SelectedTab == m_tabHistory)
AppHelp.ShowHelp(AppDefs.HelpTopics.Entry, AppDefs.HelpTopics.EntryHistory);
else
AppHelp.ShowHelp(AppDefs.HelpTopics.Entry, null);
}
private void OnCtxUrlHelp(object sender, EventArgs e)
{
AppHelp.ShowHelp(AppDefs.HelpTopics.UrlField, null);
}
private void SelectFileAsUrl(string strFilter)
{
string strFlt = string.Empty;
if(strFilter != null) strFlt += strFilter;
strFlt += KPRes.AllFiles + @" (*.*)|*.*";
OpenFileDialogEx dlg = UIUtil.CreateOpenFileDialog(null, strFlt, 1,
null, false, AppDefs.FileDialogContext.Attachments);
if(dlg.ShowDialog() == DialogResult.OK)
m_tbUrl.Text = "cmd://\"" + SprEncoding.EncodeForCommandLine(
dlg.FileName) + "\"";
}
private void OnCtxUrlSelApp(object sender, EventArgs e)
{
SelectFileAsUrl(KPRes.Application + @" (*.exe, *.com, *.bat, *.cmd)|" +
@"*.exe;*.com;*.bat;*.cmd|");
}
private void OnCtxUrlSelDoc(object sender, EventArgs e)
{
SelectFileAsUrl(null);
}
private string CreateFieldReference(string strDefaultRef)
{
FieldRefForm dlg = new FieldRefForm();
dlg.InitEx(m_pwDatabase.RootGroup, m_ilIcons, strDefaultRef);
string strResult = string.Empty;
if(dlg.ShowDialog() == DialogResult.OK)
strResult = dlg.ResultReference;
UIUtil.DestroyForm(dlg);
return strResult;
}
private void CreateFieldReferenceIn(Control c, string strDefaultRef,
string strSep)
{
if(c == null) { Debug.Assert(false); return; }
string strRef = CreateFieldReference(strDefaultRef);
if(string.IsNullOrEmpty(strRef)) return;
string strPre = (c.Text ?? string.Empty);
if((m_mvec != null) && (strPre == MultipleValuesEx.CueString))
strPre = string.Empty;
if(strPre.Length == 0) strSep = string.Empty;
c.Text = strPre + strSep + strRef;
}
private void OnFieldRefInTitle(object sender, EventArgs e)
{
CreateFieldReferenceIn(m_tbTitle, PwDefs.TitleField, string.Empty);
}
private void OnFieldRefInUserName(object sender, EventArgs e)
{
CreateFieldReferenceIn(m_tbUserName, PwDefs.UserNameField, string.Empty);
}
private void OnFieldRefInPassword(object sender, EventArgs e)
{
string strRef = CreateFieldReference(PwDefs.PasswordField);
if(string.IsNullOrEmpty(strRef)) return;
ProtectedString psP = m_icgPassword.GetPasswordEx();
ProtectedString psR = m_icgPassword.GetRepeatEx();
if((m_mvec != null) && psP.Equals(MultipleValuesEx.CueProtectedString, false))
{
psP = ProtectedString.EmptyEx;
psR = ProtectedString.EmptyEx;
}
m_icgPassword.SetPasswords(psP + strRef, psR + strRef);
}
private void OnFieldRefInUrl(object sender, EventArgs e)
{
CreateFieldReferenceIn(m_tbUrl, PwDefs.UrlField, string.Empty);
}
private void OnFieldRefInNotes(object sender, EventArgs e)
{
CreateFieldReferenceIn(m_rtNotes, PwDefs.NotesField, "\r\n");
}
private bool m_bClosing = false; // Mono bug workaround
private void OnFormClosing(object sender, FormClosingEventArgs e)
{
if(m_bClosing) return;
m_bClosing = true;
HandleFormClosing(e);
m_bClosing = false;
}
private void HandleFormClosing(FormClosingEventArgs e)
{
bool bCancel = false;
if(!m_bForceClosing && (m_pwEditMode != PwEditMode.ViewReadOnlyEntry))
{
PwEntry pe = m_pwInitialEntry.CloneDeep();
SaveEntry(pe, false);
bool bModified = !pe.EqualsEntry(m_pwInitialEntry, m_cmpOpt,
MemProtCmpMode.CustomOnly);
bModified |= !m_icgPassword.ValidateData(false);
if(bModified)
{
string strTitle = pe.Strings.ReadSafe(PwDefs.TitleField).Trim();
string strHeader = ((strTitle.Length == 0) ? string.Empty :
(KPRes.Entry + @" '" + strTitle + @"'"));
string strText = KPRes.SaveBeforeCloseEntry;
if(m_mvec != null)
{
strHeader = string.Empty;
strText = KPRes.SaveBeforeCloseQuestion;
}
VistaTaskDialog dlg = new VistaTaskDialog();
dlg.CommandLinks = false;
dlg.Content = strText;
dlg.MainInstruction = strHeader;
dlg.WindowTitle = PwDefs.ShortProductName;
dlg.SetIcon(VtdCustomIcon.Question);
dlg.AddButton((int)DialogResult.Yes, KPRes.YesCmd, null);
dlg.AddButton((int)DialogResult.No, KPRes.NoCmd, null);
dlg.AddButton((int)DialogResult.Cancel, KPRes.Cancel, null);
dlg.DefaultButtonID = (int)DialogResult.Yes;
DialogResult dr;
if(dlg.ShowDialog(this)) dr = (DialogResult)dlg.Result;
else dr = MessageService.Ask(strText, PwDefs.ShortProductName,
MessageBoxButtons.YesNoCancel);
if((dr == DialogResult.Yes) || (dr == DialogResult.OK))
{
bCancel = !SaveEntry(m_pwEntry, true);
if(!bCancel) this.DialogResult = DialogResult.OK;
}
else if((dr == DialogResult.Cancel) || (dr == DialogResult.None))
bCancel = true;
}
}
if(bCancel)
{
this.DialogResult = DialogResult.None;
e.Cancel = true;
return;
}
if(!m_bTouchedOnce) m_pwEntry.Touch(false, false);
CleanUpEx();
}
private void OnBinariesItemActivate(object sender, EventArgs e)
{
OnBtnBinOpen(sender, e);
}
private void OnHistoryItemActivate(object sender, EventArgs e)
{
OnBtnHistoryView(sender, e);
}
private void OnCtxBinImport(object sender, EventArgs e)
{
OpenFileDialogEx ofd = UIUtil.CreateOpenFileDialog(KPRes.AttachFiles,
UIUtil.CreateFileTypeFilter(null, null, true), 1, null, true,
AppDefs.FileDialogContext.Attachments);
if(ofd.ShowDialog() == DialogResult.OK)
BinImportFiles(ofd.FileNames);
}
private void BinImportFiles(string[] vPaths)
{
if(vPaths == null) { Debug.Assert(false); return; }
UpdateEntryBinaries(true, false);
foreach(string strFile in vPaths)
{
if(string.IsNullOrEmpty(strFile)) { Debug.Assert(false); continue; }
string strItem = UrlUtil.GetFileName(strFile);
if(m_vBinaries.Get(strItem) != null)
{
string strMsg = KPRes.AttachedExistsAlready + MessageService.NewLine +
strItem + MessageService.NewParagraph + KPRes.AttachNewRename +
MessageService.NewParagraph + KPRes.AttachNewRenameRemarks0 +
MessageService.NewLine + KPRes.AttachNewRenameRemarks1 +
MessageService.NewLine + KPRes.AttachNewRenameRemarks2;
DialogResult dr = MessageService.Ask(strMsg, null,
MessageBoxButtons.YesNoCancel);
if(dr == DialogResult.Cancel) continue;
else if(dr == DialogResult.Yes)
{
string strFileName = UrlUtil.StripExtension(strItem);
string strExtension = "." + UrlUtil.GetExtension(strItem);
int nTry = 0;
while(true)
{
string strNewName = strFileName + nTry.ToString() + strExtension;
if(m_vBinaries.Get(strNewName) == null)
{
strItem = strNewName;
break;
}
++nTry;
}
}
}
try
{
if(!FileDialogsEx.CheckAttachmentSize(strFile, KPRes.AttachFailed +
MessageService.NewParagraph + strFile))
continue;
byte[] vBytes = File.ReadAllBytes(strFile);
vBytes = DataEditorForm.ConvertAttachment(strItem, vBytes);
if(vBytes != null)
{
ProtectedBinary pb = new ProtectedBinary(false, vBytes);
m_vBinaries.Set(strItem, pb);
}
}
catch(Exception exAttach)
{
MessageService.ShowWarning(KPRes.AttachFailed, strFile, exAttach);
}
}
UpdateEntryBinaries(false, true);
ResizeColumnHeaders();
}
private void OnCtxBinNew(object sender, EventArgs e)
{
string strName;
for(int i = 0; ; ++i)
{
strName = KPRes.New;
if(i >= 1) strName += " (" + i.ToString() + ")";
strName += ".rtf";
if(m_vBinaries.Get(strName) == null) break;
}
ProtectedBinary pb = new ProtectedBinary();
m_vBinaries.Set(strName, pb);
UpdateEntryBinaries(false, true, strName);
ResizeColumnHeaders();
ListViewItem lviNew = m_lvBinaries.FindItemWithText(strName,
false, 0, false);
if(lviNew != null) lviNew.BeginEdit();
}
private void OnBinAfterLabelEdit(object sender, LabelEditEventArgs e)
{
string strNew = e.Label;
e.CancelEdit = true; // In the case of success, we update it on our own
if(string.IsNullOrEmpty(strNew)) return;
int iItem = e.Item;
if((iItem < 0) || (iItem >= m_lvBinaries.Items.Count)) return;
string strOld = m_lvBinaries.Items[iItem].Text;
if(strNew == strOld) return;
if(m_vBinaries.Get(strNew) != null)
{
MessageService.ShowWarning(KPRes.FieldNameExistsAlready);
return;
}
ProtectedBinary pb = m_vBinaries.Get(strOld);
if(pb == null) { Debug.Assert(false); return; }
m_vBinaries.Remove(strOld);
m_vBinaries.Set(strNew, pb);
UpdateEntryBinaries(false, true, strNew);
}
private static void BinDragAccept(DragEventArgs e)
{
if(e == null) { Debug.Assert(false); return; }
IDataObject ido = e.Data;
if((ido == null) || !ido.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.None;
else e.Effect = DragDropEffects.Copy;
}
private void OnBinDragEnter(object sender, DragEventArgs e)
{
BinDragAccept(e);
}
private void OnBinDragOver(object sender, DragEventArgs e)
{
BinDragAccept(e);
}
private void OnBinDragDrop(object sender, DragEventArgs e)
{
try
{
BinImportFiles(e.Data.GetData(DataFormats.FileDrop) as string[]);
}
catch(Exception) { Debug.Assert(false); }
}
private void InitOverridesBox()
{
List<KeyValuePair<string, Image>> l = new List<KeyValuePair<string, Image>>();
AddOverrideUrlItem(l, "cmd://{INTERNETEXPLORER} \"{URL}\"",
AppLocator.InternetExplorerPath);
AddOverrideUrlItem(l, "cmd://{INTERNETEXPLORER} -private \"{URL}\"",
AppLocator.InternetExplorerPath);
AddOverrideUrlItem(l, "microsoft-edge:{URL}",
AppLocator.EdgePath);
AddOverrideUrlItem(l, "cmd://{FIREFOX} \"{URL}\"",
AppLocator.FirefoxPath);
AddOverrideUrlItem(l, "cmd://{FIREFOX} -private-window \"{URL}\"",
AppLocator.FirefoxPath);
AddOverrideUrlItem(l, "cmd://{GOOGLECHROME} \"{URL}\"",
AppLocator.ChromePath);
AddOverrideUrlItem(l, "cmd://{GOOGLECHROME} --incognito \"{URL}\"",
AppLocator.ChromePath);
AddOverrideUrlItem(l, "cmd://{OPERA} \"{URL}\"",
AppLocator.OperaPath);
AddOverrideUrlItem(l, "cmd://{OPERA} --private \"{URL}\"",
AppLocator.OperaPath);
AddOverrideUrlItem(l, "cmd://{SAFARI} \"{URL}\"",
AppLocator.SafariPath);
Debug.Assert(m_cmbOverrideUrl.InvokeRequired ||
MonoWorkarounds.IsRequired(373134));
VoidDelegate f = delegate()
{
try
{
Debug.Assert(!m_cmbOverrideUrl.InvokeRequired);
foreach(KeyValuePair<string, Image> kvp in l)
{
m_cmbOverrideUrl.Items.Add(kvp.Key);
m_lOverrideUrlIcons.Add(kvp.Value);
}
m_cmbOverrideUrl.OrderedImageList = m_lOverrideUrlIcons;
}
catch(Exception) { Debug.Assert(false); }
};
m_cmbOverrideUrl.Invoke(f);
}
private void AddOverrideUrlItem(List<KeyValuePair<string, Image>> l,
string strOverride, string strIconPath)
{
if(string.IsNullOrEmpty(strOverride)) { Debug.Assert(false); return; }
int w = DpiUtil.ScaleIntX(16);
int h = DpiUtil.ScaleIntY(16);
Image img = null;
string str = UrlUtil.GetQuotedAppPath(strIconPath ?? string.Empty);
str = str.Trim();
try
{
if((str.Length > 0) && File.Exists(str))
{
// img = UIUtil.GetFileIcon(str, w, h);
img = FileIcons.GetImageForPath(str, new Size(w, h), true, true);
}
}
catch(Exception) { Debug.Assert(false); }
if(img == null)
img = GfxUtil.ScaleImage(m_ilIcons.Images[(int)PwIcon.Console],
w, h, ScaleTransformFlags.UIIcon);
l.Add(new KeyValuePair<string, Image>(strOverride, img));
}
private void OnBtnAutoTypeUp(object sender, EventArgs e)
{
MoveSelectedAutoTypeItems(false);
}
private void OnBtnAutoTypeDown(object sender, EventArgs e)
{
MoveSelectedAutoTypeItems(true);
}
private void MoveSelectedAutoTypeItems(bool bDown)
{
int n = m_lvAutoType.Items.Count;
int s = m_lvAutoType.SelectedIndices.Count;
if(s == 0) return;
int[] v = new int[s];
m_lvAutoType.SelectedIndices.CopyTo(v, 0);
Array.Sort(v);
if((bDown && (v[s - 1] >= (n - 1))) || (!bDown && (v[0] <= 0)))
return; // Moving as a block is not possible
int iStart = (bDown ? (s - 1) : 0);
int iExcl = (bDown ? -1 : s);
int iStep = (bDown ? -1 : 1);
for(int i = iStart; i != iExcl; i += iStep)
{
int p = v[i];
AutoTypeAssociation a = m_atConfig.GetAt(p);
if(bDown)
{
Debug.Assert(p < (n - 1));
m_atConfig.RemoveAt(p);
m_atConfig.Insert(p + 1, a);
}
else // Up
{
Debug.Assert(p > 0);
m_atConfig.RemoveAt(p);
m_atConfig.Insert(p - 1, a);
}
}
UpdateAutoTypeList(ListSelRestore.ByRef, null, true);
}
private void OnCustomDataSelectedIndexChanged(object sender, EventArgs e)
{
EnableControlsEx();
}
private void OnBtnCDDel(object sender, EventArgs e)
{
UIUtil.StrDictListDeleteSel(m_lvCustomData, m_sdCustomData, (m_mvec != null));
UIUtil.SetFocus(m_lvCustomData, this);
EnableControlsEx();
}
private static void NormalizeStrings(ProtectedStringDictionary d,
PwDatabase pd)
{
if(d == null) { Debug.Assert(false); return; }
MemoryProtectionConfig mp = ((pd != null) ? pd.MemoryProtection :
(new MemoryProtectionConfig()));
string str = d.ReadSafe(PwDefs.NotesField);
d.Set(PwDefs.NotesField, new ProtectedString(mp.ProtectNotes,
StrUtil.NormalizeNewLines(str, true)));
// Custom strings are normalized by the string editing form
}
private void InitUserNameSuggestions()
{
try
{
AceColumn c = Program.Config.MainWindow.FindColumn(
AceColumnType.UserName);
if((c == null) || c.HideWithAsterisks) return;
GFunc<PwEntry, string> f = delegate(PwEntry pe)
{
string str = pe.Strings.ReadSafe(PwDefs.UserNameField);
return ((str.Length != 0) ? str : null);
};
string[] v = m_pwDatabase.RootGroup.CollectEntryStrings(f, true);
// Do not append, because it breaks Ctrl+A;
// https://sourceforge.net/p/keepass/discussion/329220/thread/4f626b91/
UIUtil.EnableAutoCompletion(m_tbUserName, false, v); // Invokes
}
catch(Exception) { Debug.Assert(false); }
}
private void OnUrlTextChanged(object sender, EventArgs e)
{
EnableControlsEx(); // URL override warning
}
private void OnUrlOverrideTextChanged(object sender, EventArgs e)
{
EnableControlsEx(); // URL override warning
}
}
}
| {
"pile_set_name": "Github"
} |
"use strict";var exports=module.exports={};/**
* @copyright Maichong Software Ltd. 2016 http://maichong.it
* @date 2016-10-11
* @author Liang <[email protected]>
*/
/* eslint no-inner-declarations:0 no-inner-declarations:0 */
var _typeof2 = require('../babel-runtime/helpers/typeof.js');
var _typeof3 = _interopRequireDefault(_typeof2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var numberTag = '[object Number]';
var boolTag = '[object Boolean]';
var stringTag = '[object String]';
var symbolTag = '[object Symbol]';
function isObjectLike(value) {
return value != null && (typeof value === 'undefined' ? 'undefined' : (0, _typeof3.default)(value)) === 'object';
}
function objectToString(value) {
return Object.prototype.toString.call(value);
}
function getType(value) {
if (Array.isArray(value)) {
return 'array';
}
var type = typeof value === 'undefined' ? 'undefined' : (0, _typeof3.default)(value);
if (type === 'function') {
return 'func';
}
if (type === 'number' || isObjectLike(value) && objectToString(value) === numberTag) {
return 'number';
}
if (value === true || value === false || isObjectLike(value) && objectToString(value) === boolTag) {
return 'bool';
}
if (type === 'string' || isObjectLike(value) && objectToString(value) === stringTag) {
return 'string';
}
if (type === 'object' && value !== null) {
return 'object';
}
if (type === 'symbol' || isObjectLike(value) && objectToString(value) === symbolTag) {
return 'symbol';
}
return 'unknown';
}
function generate(name, allowNull) {
var validator = function validator(props, propName, componentName) {
var value = props[propName];
if (value === undefined || allowNull && value === null) return null;
var type = getType(value);
return type === name ? null : new Error('组件"' + componentName + '"的属性"' + propName + '"类型声明为"' + name + '",却得到"' + type + '"');
};
validator.isRequired = function (props, propName, componentName) {
var value = props[propName];
if (value === undefined || value === null) {
return new Error('组件"' + componentName + '"的必要属性"' + propName + '"缺失,得到"' + value + '"');
}
return validator(props, propName, componentName);
};
return validator;
}
var any = function any() {};
if (true) {
any.isRequired = function (props, propName, componentName) {
var value = props[propName];
if (value === undefined) {
return new Error('组件"' + componentName + '"的必要属性"' + propName + '"缺失,得到"' + value + '"');
}
return null;
};
module.exports = {
number: generate('number'),
string: generate('string'),
func: generate('func', true),
array: generate('array'),
bool: generate('bool'),
object: generate('object', true),
symbol: generate('symbol'),
any: any
};
} else {
any.isRequired = function () {};
module.exports = {
number: any,
string: any,
func: any,
array: any,
bool: any,
object: any,
symbol: any,
any: any
};
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInByb3AtdHlwZXMuanMiXSwibmFtZXMiOlsibnVtYmVyVGFnIiwiYm9vbFRhZyIsInN0cmluZ1RhZyIsInN5bWJvbFRhZyIsImlzT2JqZWN0TGlrZSIsInZhbHVlIiwib2JqZWN0VG9TdHJpbmciLCJPYmplY3QiLCJwcm90b3R5cGUiLCJ0b1N0cmluZyIsImNhbGwiLCJnZXRUeXBlIiwiQXJyYXkiLCJpc0FycmF5IiwidHlwZSIsImdlbmVyYXRlIiwibmFtZSIsImFsbG93TnVsbCIsInZhbGlkYXRvciIsInByb3BzIiwicHJvcE5hbWUiLCJjb21wb25lbnROYW1lIiwidW5kZWZpbmVkIiwiRXJyb3IiLCJpc1JlcXVpcmVkIiwiYW55IiwiX19ERVZfXyIsIm1vZHVsZSIsImV4cG9ydHMiLCJudW1iZXIiLCJzdHJpbmciLCJmdW5jIiwiYXJyYXkiLCJib29sIiwib2JqZWN0Iiwic3ltYm9sIl0sIm1hcHBpbmdzIjoiQUFBQTs7Ozs7O0FBTUE7O0FBSUE7Ozs7Ozs7O0FBRUEsSUFBTUEsWUFBWSxpQkFBbEI7QUFDQSxJQUFNQyxVQUFVLGtCQUFoQjtBQUNBLElBQU1DLFlBQVksaUJBQWxCO0FBQ0EsSUFBTUMsWUFBWSxpQkFBbEI7O0FBRUEsU0FBU0MsWUFBVCxDQUFzQkMsS0FBdEIsRUFBMkM7QUFDekMsU0FBT0EsU0FBUyxJQUFULElBQWlCLFFBQU9BLEtBQVAsdURBQU9BLEtBQVAsT0FBaUIsUUFBekM7QUFDRDs7QUFFRCxTQUFTQyxjQUFULENBQXdCRCxLQUF4QixFQUErQztBQUM3QyxTQUFPRSxPQUFPQyxTQUFQLENBQWlCQyxRQUFqQixDQUEwQkMsSUFBMUIsQ0FBK0JMLEtBQS9CLENBQVA7QUFDRDs7QUFFRCxTQUFTTSxPQUFULENBQWlCTixLQUFqQixFQUFxQztBQUNuQyxNQUFJTyxNQUFNQyxPQUFOLENBQWNSLEtBQWQsQ0FBSixFQUEwQjtBQUN4QixXQUFPLE9BQVA7QUFDRDs7QUFFRCxNQUFNUyxjQUFjVCxLQUFkLHVEQUFjQSxLQUFkLENBQU47O0FBRUEsTUFBSVMsU0FBUyxVQUFiLEVBQXlCO0FBQ3ZCLFdBQU8sTUFBUDtBQUNEO0FBQ0QsTUFBSUEsU0FBUyxRQUFULElBQXNCVixhQUFhQyxLQUFiLEtBQXVCQyxlQUFlRCxLQUFmLE1BQTBCTCxTQUEzRSxFQUF1RjtBQUNyRixXQUFPLFFBQVA7QUFDRDtBQUNELE1BQ0VLLFVBQVUsSUFBVixJQUFrQkEsVUFBVSxLQUE1QixJQUNJRCxhQUFhQyxLQUFiLEtBQXVCQyxlQUFlRCxLQUFmLE1BQTBCSixPQUZ2RCxFQUdFO0FBQ0EsV0FBTyxNQUFQO0FBQ0Q7QUFDRCxNQUFJYSxTQUFTLFFBQVQsSUFBc0JWLGFBQWFDLEtBQWIsS0FBdUJDLGVBQWVELEtBQWYsTUFBMEJILFNBQTNFLEVBQXVGO0FBQ3JGLFdBQU8sUUFBUDtBQUNEO0FBQ0QsTUFBSVksU0FBUyxRQUFULElBQXFCVCxVQUFVLElBQW5DLEVBQXlDO0FBQ3ZDLFdBQU8sUUFBUDtBQUNEO0FBQ0QsTUFBSVMsU0FBUyxRQUFULElBQXNCVixhQUFhQyxLQUFiLEtBQXVCQyxlQUFlRCxLQUFmLE1BQTBCRixTQUEzRSxFQUF1RjtBQUNyRixXQUFPLFFBQVA7QUFDRDtBQUNELFNBQU8sU0FBUDtBQUNEOztBQUVELFNBQVNZLFFBQVQsQ0FBa0JDLElBQWxCLEVBQWdDQyxTQUFoQyxFQUFxRDtBQUNuRCxNQUFNQyxZQUFZLFNBQVpBLFNBQVksQ0FBVUMsS0FBVixFQUFzQkMsUUFBdEIsRUFBd0NDLGFBQXhDLEVBQXVFO0FBQ3ZGLFFBQU1oQixRQUFRYyxNQUFNQyxRQUFOLENBQWQ7QUFDQSxRQUFJZixVQUFVaUIsU0FBVixJQUF3QkwsYUFBYVosVUFBVSxJQUFuRCxFQUEwRCxPQUFPLElBQVA7QUFDMUQsUUFBTVMsT0FBT0gsUUFBUU4sS0FBUixDQUFiO0FBQ0EsV0FBT1MsU0FBU0UsSUFBVCxHQUFnQixJQUFoQixHQUF1QixJQUFJTyxLQUFKLENBQVUsUUFBUUYsYUFBUixHQUF3QixPQUF4QixHQUFrQ0QsUUFBbEMsR0FBNkMsU0FBN0MsR0FBeURKLElBQXpELEdBQWdFLFFBQWhFLEdBQTJFRixJQUEzRSxHQUFrRixHQUE1RixDQUE5QjtBQUNELEdBTEQ7QUFNQUksWUFBVU0sVUFBVixHQUF1QixVQUFVTCxLQUFWLEVBQXNCQyxRQUF0QixFQUF3Q0MsYUFBeEMsRUFBdUU7QUFDNUYsUUFBTWhCLFFBQVFjLE1BQU1DLFFBQU4sQ0FBZDtBQUNBLFFBQUlmLFVBQVVpQixTQUFWLElBQXVCakIsVUFBVSxJQUFyQyxFQUEyQztBQUN6QyxhQUFPLElBQUlrQixLQUFKLENBQVUsUUFBUUYsYUFBUixHQUF3QixTQUF4QixHQUFvQ0QsUUFBcEMsR0FBK0MsU0FBL0MsR0FBMkRmLEtBQTNELEdBQW1FLEdBQTdFLENBQVA7QUFDRDtBQUNELFdBQU9hLFVBQVVDLEtBQVYsRUFBaUJDLFFBQWpCLEVBQTJCQyxhQUEzQixDQUFQO0FBQ0QsR0FORDtBQU9BLFNBQU9ILFNBQVA7QUFDRDs7QUFFRCxJQUFNTyxNQUFNLFNBQU5BLEdBQU0sR0FBWSxDQUN2QixDQUREOztBQUdBLElBQUlDLE9BQUosRUFBYTtBQUNYRCxNQUFJRCxVQUFKLEdBQWlCLFVBQVVMLEtBQVYsRUFBc0JDLFFBQXRCLEVBQXdDQyxhQUF4QyxFQUF1RTtBQUN0RixRQUFNaEIsUUFBUWMsTUFBTUMsUUFBTixDQUFkO0FBQ0EsUUFBSWYsVUFBVWlCLFNBQWQsRUFBeUI7QUFDdkIsYUFBTyxJQUFJQyxLQUFKLENBQVUsUUFBUUYsYUFBUixHQUF3QixTQUF4QixHQUFvQ0QsUUFBcEMsR0FBK0MsU0FBL0MsR0FBMkRmLEtBQTNELEdBQW1FLEdBQTdFLENBQVA7QUFDRDtBQUNELFdBQU8sSUFBUDtBQUNELEdBTkQ7O0FBUUFzQixTQUFPQyxPQUFQLEdBQWlCO0FBQ2ZDLFlBQVFkLFNBQVMsUUFBVCxDQURPO0FBRWZlLFlBQVFmLFNBQVMsUUFBVCxDQUZPO0FBR2ZnQixVQUFNaEIsU0FBUyxNQUFULEVBQWlCLElBQWpCLENBSFM7QUFJZmlCLFdBQU9qQixTQUFTLE9BQVQsQ0FKUTtBQUtma0IsVUFBTWxCLFNBQVMsTUFBVCxDQUxTO0FBTWZtQixZQUFRbkIsU0FBUyxRQUFULEVBQW1CLElBQW5CLENBTk87QUFPZm9CLFlBQVFwQixTQUFTLFFBQVQsQ0FQTztBQVFmVSxTQUFLQTtBQVJVLEdBQWpCO0FBVUQsQ0FuQkQsTUFtQk87QUFDTEEsTUFBSUQsVUFBSixHQUFpQixZQUFZLENBQzVCLENBREQ7QUFFQUcsU0FBT0MsT0FBUCxHQUFpQjtBQUNmQyxZQUFRSixHQURPO0FBRWZLLFlBQVFMLEdBRk87QUFHZk0sVUFBTU4sR0FIUztBQUlmTyxXQUFPUCxHQUpRO0FBS2ZRLFVBQU1SLEdBTFM7QUFNZlMsWUFBUVQsR0FOTztBQU9mVSxZQUFRVixHQVBPO0FBUWZBLFNBQUtBO0FBUlUsR0FBakI7QUFVRCIsImZpbGUiOiJ1bmtub3duIiwic291cmNlc0NvbnRlbnQiOlsiLyoqXG4gKiBAY29weXJpZ2h0IE1haWNob25nIFNvZnR3YXJlIEx0ZC4gMjAxNiBodHRwOi8vbWFpY2hvbmcuaXRcbiAqIEBkYXRlIDIwMTYtMTAtMTFcbiAqIEBhdXRob3IgTGlhbmcgPGxpYW5nQG1haWNob25nLml0PlxuICovXG5cbi8qIGVzbGludCBuby1pbm5lci1kZWNsYXJhdGlvbnM6MCBuby1pbm5lci1kZWNsYXJhdGlvbnM6MCAqL1xuXG4vLyBAZmxvd1xuXG4ndXNlIHN0cmljdCc7XG5cbmNvbnN0IG51bWJlclRhZyA9ICdbb2JqZWN0IE51bWJlcl0nO1xuY29uc3QgYm9vbFRhZyA9ICdbb2JqZWN0IEJvb2xlYW5dJztcbmNvbnN0IHN0cmluZ1RhZyA9ICdbb2JqZWN0IFN0cmluZ10nO1xuY29uc3Qgc3ltYm9sVGFnID0gJ1tvYmplY3QgU3ltYm9sXSc7XG5cbmZ1bmN0aW9uIGlzT2JqZWN0TGlrZSh2YWx1ZTogYW55KTogYm9vbGVhbiB7XG4gIHJldHVybiB2YWx1ZSAhPSBudWxsICYmIHR5cGVvZiB2YWx1ZSA9PT0gJ29iamVjdCc7XG59XG5cbmZ1bmN0aW9uIG9iamVjdFRvU3RyaW5nKHZhbHVlOiBPYmplY3QpOiBzdHJpbmcge1xuICByZXR1cm4gT2JqZWN0LnByb3RvdHlwZS50b1N0cmluZy5jYWxsKHZhbHVlKTtcbn1cblxuZnVuY3Rpb24gZ2V0VHlwZSh2YWx1ZTogYW55KTogc3RyaW5nIHtcbiAgaWYgKEFycmF5LmlzQXJyYXkodmFsdWUpKSB7XG4gICAgcmV0dXJuICdhcnJheSc7XG4gIH1cblxuICBjb25zdCB0eXBlID0gdHlwZW9mIHZhbHVlO1xuXG4gIGlmICh0eXBlID09PSAnZnVuY3Rpb24nKSB7XG4gICAgcmV0dXJuICdmdW5jJztcbiAgfVxuICBpZiAodHlwZSA9PT0gJ251bWJlcicgfHwgKGlzT2JqZWN0TGlrZSh2YWx1ZSkgJiYgb2JqZWN0VG9TdHJpbmcodmFsdWUpID09PSBudW1iZXJUYWcpKSB7XG4gICAgcmV0dXJuICdudW1iZXInO1xuICB9XG4gIGlmIChcbiAgICB2YWx1ZSA9PT0gdHJ1ZSB8fCB2YWx1ZSA9PT0gZmFsc2VcbiAgICB8fCAoaXNPYmplY3RMaWtlKHZhbHVlKSAmJiBvYmplY3RUb1N0cmluZyh2YWx1ZSkgPT09IGJvb2xUYWcpXG4gICkge1xuICAgIHJldHVybiAnYm9vbCc7XG4gIH1cbiAgaWYgKHR5cGUgPT09ICdzdHJpbmcnIHx8IChpc09iamVjdExpa2UodmFsdWUpICYmIG9iamVjdFRvU3RyaW5nKHZhbHVlKSA9PT0gc3RyaW5nVGFnKSkge1xuICAgIHJldHVybiAnc3RyaW5nJztcbiAgfVxuICBpZiAodHlwZSA9PT0gJ29iamVjdCcgJiYgdmFsdWUgIT09IG51bGwpIHtcbiAgICByZXR1cm4gJ29iamVjdCc7XG4gIH1cbiAgaWYgKHR5cGUgPT09ICdzeW1ib2wnIHx8IChpc09iamVjdExpa2UodmFsdWUpICYmIG9iamVjdFRvU3RyaW5nKHZhbHVlKSA9PT0gc3ltYm9sVGFnKSkge1xuICAgIHJldHVybiAnc3ltYm9sJztcbiAgfVxuICByZXR1cm4gJ3Vua25vd24nO1xufVxuXG5mdW5jdGlvbiBnZW5lcmF0ZShuYW1lOiBzdHJpbmcsIGFsbG93TnVsbD86IGJvb2xlYW4pIHtcbiAgY29uc3QgdmFsaWRhdG9yID0gZnVuY3Rpb24gKHByb3BzOiBhbnksIHByb3BOYW1lOiBzdHJpbmcsIGNvbXBvbmVudE5hbWU6IHN0cmluZyk6ID9FcnJvciB7XG4gICAgY29uc3QgdmFsdWUgPSBwcm9wc1twcm9wTmFtZV07XG4gICAgaWYgKHZhbHVlID09PSB1bmRlZmluZWQgfHwgKGFsbG93TnVsbCAmJiB2YWx1ZSA9PT0gbnVsbCkpIHJldHVybiBudWxsO1xuICAgIGNvbnN0IHR5cGUgPSBnZXRUeXBlKHZhbHVlKTtcbiAgICByZXR1cm4gdHlwZSA9PT0gbmFtZSA/IG51bGwgOiBuZXcgRXJyb3IoJ+e7hOS7tlwiJyArIGNvbXBvbmVudE5hbWUgKyAnXCLnmoTlsZ7mgKdcIicgKyBwcm9wTmFtZSArICdcIuexu+Wei+WjsOaYjuS4ulwiJyArIG5hbWUgKyAnXCLvvIzljbTlvpfliLBcIicgKyB0eXBlICsgJ1wiJyk7XG4gIH07XG4gIHZhbGlkYXRvci5pc1JlcXVpcmVkID0gZnVuY3Rpb24gKHByb3BzOiBhbnksIHByb3BOYW1lOiBzdHJpbmcsIGNvbXBvbmVudE5hbWU6IHN0cmluZyk6ID9FcnJvciB7XG4gICAgY29uc3QgdmFsdWUgPSBwcm9wc1twcm9wTmFtZV07XG4gICAgaWYgKHZhbHVlID09PSB1bmRlZmluZWQgfHwgdmFsdWUgPT09IG51bGwpIHtcbiAgICAgIHJldHVybiBuZXcgRXJyb3IoJ+e7hOS7tlwiJyArIGNvbXBvbmVudE5hbWUgKyAnXCLnmoTlv4XopoHlsZ7mgKdcIicgKyBwcm9wTmFtZSArICdcIue8uuWkse+8jOW+l+WIsFwiJyArIHZhbHVlICsgJ1wiJyk7XG4gICAgfVxuICAgIHJldHVybiB2YWxpZGF0b3IocHJvcHMsIHByb3BOYW1lLCBjb21wb25lbnROYW1lKTtcbiAgfTtcbiAgcmV0dXJuIHZhbGlkYXRvcjtcbn1cblxuY29uc3QgYW55ID0gZnVuY3Rpb24gKCkge1xufTtcblxuaWYgKF9fREVWX18pIHtcbiAgYW55LmlzUmVxdWlyZWQgPSBmdW5jdGlvbiAocHJvcHM6IGFueSwgcHJvcE5hbWU6IHN0cmluZywgY29tcG9uZW50TmFtZTogc3RyaW5nKTogP0Vycm9yIHtcbiAgICBjb25zdCB2YWx1ZSA9IHByb3BzW3Byb3BOYW1lXTtcbiAgICBpZiAodmFsdWUgPT09IHVuZGVmaW5lZCkge1xuICAgICAgcmV0dXJuIG5ldyBFcnJvcign57uE5Lu2XCInICsgY29tcG9uZW50TmFtZSArICdcIueahOW/heimgeWxnuaAp1wiJyArIHByb3BOYW1lICsgJ1wi57y65aSx77yM5b6X5YiwXCInICsgdmFsdWUgKyAnXCInKTtcbiAgICB9XG4gICAgcmV0dXJuIG51bGw7XG4gIH07XG5cbiAgbW9kdWxlLmV4cG9ydHMgPSB7XG4gICAgbnVtYmVyOiBnZW5lcmF0ZSgnbnVtYmVyJyksXG4gICAgc3RyaW5nOiBnZW5lcmF0ZSgnc3RyaW5nJyksXG4gICAgZnVuYzogZ2VuZXJhdGUoJ2Z1bmMnLCB0cnVlKSxcbiAgICBhcnJheTogZ2VuZXJhdGUoJ2FycmF5JyksXG4gICAgYm9vbDogZ2VuZXJhdGUoJ2Jvb2wnKSxcbiAgICBvYmplY3Q6IGdlbmVyYXRlKCdvYmplY3QnLCB0cnVlKSxcbiAgICBzeW1ib2w6IGdlbmVyYXRlKCdzeW1ib2wnKSxcbiAgICBhbnk6IGFueVxuICB9O1xufSBlbHNlIHtcbiAgYW55LmlzUmVxdWlyZWQgPSBmdW5jdGlvbiAoKSB7XG4gIH07XG4gIG1vZHVsZS5leHBvcnRzID0ge1xuICAgIG51bWJlcjogYW55LFxuICAgIHN0cmluZzogYW55LFxuICAgIGZ1bmM6IGFueSxcbiAgICBhcnJheTogYW55LFxuICAgIGJvb2w6IGFueSxcbiAgICBvYmplY3Q6IGFueSxcbiAgICBzeW1ib2w6IGFueSxcbiAgICBhbnk6IGFueVxuICB9O1xufVxuIl19 | {
"pile_set_name": "Github"
} |
/* pcf.c
FreeType font driver for pcf fonts
Copyright 2000-2001, 2003 by
Francesco Zappa Nardelli
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.
*/
#define FT_MAKE_OPTION_SINGLE_OBJECT
#include <ft2build.h>
#include "pcfutil.c"
#include "pcfread.c"
#include "pcfdrivr.c"
/* END */
| {
"pile_set_name": "Github"
} |
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity">
<item android:id="@+id/action_scrolling_lists"
android:title="@string/action_scrolling_lists"
android:orderInCategory="100"
app:showAsAction="never"/>
</menu>
| {
"pile_set_name": "Github"
} |
<template>
<div class="card blue-grey darken-1">
<div class="card-content white-text">
<span class="card-title">Sistema para gerenciamento de escola</span>
<p>
<ul class="collection ">
<li class="collection-item blue-grey darken-2">Todo desenvolvido com TDD</li>
<li class="collection-item blue-grey darken-2">Cadastro de alunos</li>
<li class="collection-item blue-grey darken-2">Cadastro de cedente (Emitente da cobrança)</li>
<li class="collection-item blue-grey darken-2">Cadastro de funcionários</li>
<li class="collection-item blue-grey darken-2">Cadastro de horários</li>
<li class="collection-item blue-grey darken-2">Cadastro de matérias</li>
<li class="collection-item blue-grey darken-2">Cadastro de lições</li>
<li class="collection-item blue-grey darken-2">Cadastro de professores</li>
<li class="collection-item blue-grey darken-2">Cadastro de turmas</li>
<li class="collection-item blue-grey darken-2">Cadastro de usuários (Aluno, Funcionário e Professor)</li>
<li class="collection-item blue-grey darken-2">Geração de boleto automático (caixa e. federal, banco do brasil, banco itau, hsbc, santander)</li>
</ul>
</p>
</div>
</div>
<div class="card blue-grey darken-1">
<div class="card-content white-text">
<span class="card-title">Vídeos</span>
<p>
<iframe width="640" height="360" src="https://www.youtube.com/embed/kd0y0e_2dR4" frameborder="0" allowfullscreen></iframe>
</p>
</div>
</div>
</template>
<script>
export default{
}
</script>
| {
"pile_set_name": "Github"
} |
using System.Diagnostics;
using Xamarin.Forms.CustomAttributes;
using Xamarin.Forms.Internals;
#if UITEST
using NUnit.Framework;
using Xamarin.UITest;
#endif
namespace Xamarin.Forms.Controls.Issues
{
[Preserve (AllMembers = true)]
[Issue (IssueTracker.None, 0, "StackLayout issue", PlatformAffected.All, NavigationBehavior.PushModalAsync)]
public class StackLayoutIssue : TestContentPage
{
protected override void Init ()
{
var logo = new Image {
Source = "cover1.jpg",
WidthRequest = 20,
HeightRequest = 20,
VerticalOptions = LayoutOptions.FillAndExpand,
};
var winPrizeLabel = new Label {
Text = "Win a Xamarin Prize",
#pragma warning disable 618
XAlign = TextAlignment.Center,
#pragma warning restore 618
#pragma warning disable 618
YAlign = TextAlignment.Center,
#pragma warning restore 618
VerticalOptions = LayoutOptions.FillAndExpand
};
#pragma warning disable 618
Device.OnPlatform (iOS: () => winPrizeLabel.Font = Font.OfSize ("HelveticaNeue-UltraLight", NamedSize.Large));
#pragma warning restore 618
StackLayout form = MakeForm ();
var spinButton = new Button {
Text = "Spin"
};
var mainLayout = new StackLayout {
Children = {
logo,
winPrizeLabel,
form,
spinButton
}
};
Content = mainLayout;
Padding = new Thickness (50);
}
#if UITEST
[Test]
public void StackLayoutIssueTestsAllElementsPresent ()
{
// TODO: Fix ME
//var images = App.Query (PlatformQueries.Images);
//Assert.AreEqual (2, images.Length);
//App.WaitForElement (q => q.Marked ("Win a Xamarin Prize"));
//App.WaitForElement (PlatformQueries.EntryWithPlaceholder ("Full Name"));
//App.WaitForElement (PlatformQueries.EntryWithPlaceholder ("Email"));
//App.WaitForElement (PlatformQueries.EntryWithPlaceholder ("Company"));
//App.WaitForElement (q => q.Marked ("Completed Azure Mobile Services Challenge?"));
//var switches = App.Query (q => q.Raw ("Switch"));
//Assert.AreEqual (1, switches.Length);
//App.WaitForElement (q => q.Button ("Spin"));
//App.Screenshot ("All elements present");
Assert.Inconclusive ("Fix Test");
}
#endif
StackLayout MakeForm ()
{
var nameEntry = new Entry {
Placeholder = "Full Name"
};
var emailEntry = new Entry {
Placeholder = "Email"
};
var companyEntry = new Entry {
Placeholder = "Company"
};
var switchContainer = new StackLayout {
Orientation = StackOrientation.Horizontal
};
var switchLabel = new Label {
Text = "Completed Azure Mobile Services Challenge?"
};
var switchElement = new Switch ();
switchContainer.Children.Add (switchLabel);
switchContainer.Children.Add (switchElement);
var entryContainer = new StackLayout {
Children = {
nameEntry,
emailEntry,
companyEntry,
switchContainer
},
MinimumWidthRequest = 50
};
var qrButton = new Image {
Source = "cover1.jpg",
WidthRequest = 100,
HeightRequest = 100
};
var result = new StackLayout {
Orientation = StackOrientation.Horizontal
};
result.Children.Add (entryContainer);
result.Children.Add (qrButton);
result.SizeChanged += (sender, args) => {
Debug.WriteLine (result.Bounds);
};
return result;
}
}
}
| {
"pile_set_name": "Github"
} |
# BulTreeBank
#
# BulTreeBank syntactic tagset
__META_SOURCE_URL__=http://www.bultreebank.org/TechRep/BTB-TR05.pdf
# A - Adjective Lexical Element
A=de.tudarmstadt.ukp.dkpro.core.api.syntax.type.constituent.X
# APA - Head-Adjunct Adjective Phrase
APA=de.tudarmstadt.ukp.dkpro.core.api.syntax.type.constituent.X
# APC - Head-Complement Adjective Phrase
APC=de.tudarmstadt.ukp.dkpro.core.api.syntax.type.constituent.X
# Adv - Adverb Lexical Element
Adv=de.tudarmstadt.ukp.dkpro.core.api.syntax.type.constituent.X
# AdvPA - Head-Adjunct Adverb Phrase
AdvPA=de.tudarmstadt.ukp.dkpro.core.api.syntax.type.constituent.X
# AdvPC - Head-Complement Adverb Phrase
AdvPC=de.tudarmstadt.ukp.dkpro.core.api.syntax.type.constituent.X
# C - Conjunction Lexical Element
C=de.tudarmstadt.ukp.dkpro.core.api.syntax.type.constituent.X
# CL - Clauses: Saturated Verb Phrase
CL=de.tudarmstadt.ukp.dkpro.core.api.syntax.type.constituent.X
# CLCHE - clause introduced by verbal form 'che'
CLCHE=de.tudarmstadt.ukp.dkpro.core.api.syntax.type.constituent.X
# CLDA - clause introduced by verbal form 'da'
CLDA=de.tudarmstadt.ukp.dkpro.core.api.syntax.type.constituent.X
# CLQ - clause introduced by an interrogative pronound or partilce
CLQ=de.tudarmstadt.ukp.dkpro.core.api.syntax.type.constituent.X
# CLR - clause introduced by an relative pronound and surrounded by commas
CLR=de.tudarmstadt.ukp.dkpro.core.api.syntax.type.constituent.X
# CLZADA - clause introduced by verbal form 'za da'
CLZADA=de.tudarmstadt.ukp.dkpro.core.api.syntax.type.constituent.X
# CoordP - Coordination Phrase
CoordP=de.tudarmstadt.ukp.dkpro.core.api.syntax.type.constituent.X
# Gerund - Gerund Lexical Element
Gerund=de.tudarmstadt.ukp.dkpro.core.api.syntax.type.constituent.X
# H - Family Name or Adjective, Derived from Family Names, Lexical Element
H=de.tudarmstadt.ukp.dkpro.core.api.syntax.type.constituent.X
# I - Interjection Lexical Element
I=de.tudarmstadt.ukp.dkpro.core.api.syntax.type.constituent.X
# M - Numeral Lexical Element
M=de.tudarmstadt.ukp.dkpro.core.api.syntax.type.constituent.X
# N - Noun Lexical Element
N=de.tudarmstadt.ukp.dkpro.core.api.syntax.type.constituent.X
# NPA - Head-Adjunct Noun Phrase
NPA=de.tudarmstadt.ukp.dkpro.core.api.syntax.type.constituent.X
# NPC - Head-Complement Noun Phrase
NPC=de.tudarmstadt.ukp.dkpro.core.api.syntax.type.constituent.X
# PP - Prepositional Phrase
PP=de.tudarmstadt.ukp.dkpro.core.api.syntax.type.constituent.X
# Participle - Participle Lexical Element
Participle=de.tudarmstadt.ukp.dkpro.core.api.syntax.type.constituent.X
# Prep - Preposition Lexical Element
Prep=de.tudarmstadt.ukp.dkpro.core.api.syntax.type.constituent.X
# Pron - Pronoun Lexical Element
Pron=de.tudarmstadt.ukp.dkpro.core.api.syntax.type.constituent.X
# S - Sentence Level Clause
S=de.tudarmstadt.ukp.dkpro.core.api.syntax.type.constituent.X
# T - Particle Lexical Element
T=de.tudarmstadt.ukp.dkpro.core.api.syntax.type.constituent.X
# V - Verb Phrase
V=de.tudarmstadt.ukp.dkpro.core.api.syntax.type.constituent.X
# VPA - Verb Phrase (adjunct)
VPA=de.tudarmstadt.ukp.dkpro.core.api.syntax.type.constituent.X
# VPC - Verb Phrase (subject)
VPC=de.tudarmstadt.ukp.dkpro.core.api.syntax.type.constituent.X
# VPF - Verb Phrase (filler)
VPF=de.tudarmstadt.ukp.dkpro.core.api.syntax.type.constituent.X
# VPS - Verb Phrase (subject)
VPS=de.tudarmstadt.ukp.dkpro.core.api.syntax.type.constituent.X
# == Undocumented ==
# Verbalised
# Conj
# ConjArg
# ROOT
#
# Categories used by DKPro internally
#
ROOT=de.tudarmstadt.ukp.dkpro.core.api.syntax.type.constituent.ROOT
*=de.tudarmstadt.ukp.dkpro.core.api.syntax.type.constituent.X
| {
"pile_set_name": "Github"
} |
#!/bin/bash
if [ "$#" != 3 ]; then
echo "Usage: add-memzip.sh input.hex output.hex file-directory"
exit 1
fi
#set -x
input_hex=$1
output_hex=$2
memzip_src_dir=$3
input_bin=${input_hex}.bin
output_bin=${output_hex}.bin
zip_file=${output_hex}.zip
zip_base=$(basename ${zip_file})
zip_dir=$(dirname ${zip_file})
abs_zip_dir=$(realpath ${zip_dir})
rm -f ${zip_file}
(cd ${memzip_src_dir}; zip -0 -r -D ${abs_zip_dir}/${zip_base} .)
objcopy -I ihex -O binary ${input_hex} ${input_bin}
cat ${input_bin} ${zip_file} > ${output_bin}
objcopy -I binary -O ihex ${output_bin} ${output_hex}
echo "Added ${memzip_src_dir} to ${input_hex} creating ${output_hex}"
| {
"pile_set_name": "Github"
} |
/* Soot - a J*va Optimization Framework
* Copyright (C) 1999 Patrick Lam, Patrick Pominville and Raja Vallee-Rai
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/*
* Modified by the Sable Research Group and others 1997-1999.
* See the 'credits' file distributed with Soot for the complete list of
* contributors. (Soot is distributed at http://www.sable.mcgill.ca/soot)
*/
package soot.baf.internal;
import soot.*;
import soot.baf.*;
import soot.util.*;
public class BXorInst extends AbstractOpTypeInst implements XorInst
{
public BXorInst(Type opType)
{
super(opType);
}
public int getInCount()
{
return 2;
}
public int getOutCount()
{
return 1;
}
public Object clone()
{
return new BXorInst(getOpType());
}
public int getInMachineCount()
{
return 2 * AbstractJasminClass.sizeOfType(getOpType());
}
public int getOutMachineCount()
{
return 1 * AbstractJasminClass.sizeOfType(getOpType());
}
public final String getName() { return "xor"; }
public void apply(Switch sw)
{
((InstSwitch) sw).caseXorInst(this);
}
}
| {
"pile_set_name": "Github"
} |
CSRCS += lv_hal_disp.c
CSRCS += lv_hal_indev.c
CSRCS += lv_hal_tick.c
DEPPATH += --dep-path $(LVGL_DIR)/lvgl/lv_hal
VPATH += :$(LVGL_DIR)/lvgl/lv_hal
CFLAGS += "-I$(LVGL_DIR)/lvgl/lv_hal"
| {
"pile_set_name": "Github"
} |
<?php
/*
* 2007-2017 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <[email protected]>
* @copyright 2007-2017 PrestaShop SA
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
abstract class CarrierModuleCore extends Module
{
abstract public function getOrderShippingCost($params, $shipping_cost);
abstract public function getOrderShippingCostExternal($params);
}
| {
"pile_set_name": "Github"
} |
// Package stdlib is a collection of cty functions that are expected to be
// generally useful, and are thus factored out into this shared library in
// the hope that cty-using applications will have consistent behavior when
// using these functions.
//
// See the parent package "function" for more information on the purpose
// and usage of cty functions.
//
// This package contains both Go functions, which provide convenient access
// to call the functions from Go code, and the Function objects themselves.
// The latter follow the naming scheme of appending "Func" to the end of
// the function name.
package stdlib
| {
"pile_set_name": "Github"
} |
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 15 2018 10:31:50).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <objc/NSObject.h>
@class NSString, NSURL, NSURLSession, WFOAuth2Credential;
@interface WFWunderlistSessionManager : NSObject
{
NSURLSession *_session;
WFOAuth2Credential *_credential;
NSString *_clientId;
NSURL *_baseURL;
}
- (void).cxx_destruct;
@property(readonly, nonatomic) NSURL *baseURL; // @synthesize baseURL=_baseURL;
@property(copy, nonatomic) NSString *clientId; // @synthesize clientId=_clientId;
@property(copy, nonatomic) WFOAuth2Credential *credential; // @synthesize credential=_credential;
@property(readonly, nonatomic) NSURLSession *session; // @synthesize session=_session;
- (void)requestPath:(id)arg1 method:(id)arg2 parameters:(id)arg3 completionHandler:(CDUnknownBlockType)arg4;
- (void)requestPath:(id)arg1 parameters:(id)arg2 completionHandler:(CDUnknownBlockType)arg3;
- (void)createFileOnTask:(id)arg1 withFile:(id)arg2 completionHandler:(CDUnknownBlockType)arg3;
- (void)createReminderOnTask:(id)arg1 withDate:(id)arg2 completionHandler:(CDUnknownBlockType)arg3;
- (void)createNoteOnTask:(id)arg1 withContent:(id)arg2 completionHandler:(CDUnknownBlockType)arg3;
- (void)createTaskOnList:(id)arg1 title:(id)arg2 dueDate:(id)arg3 starred:(BOOL)arg4 completionHandler:(CDUnknownBlockType)arg5;
- (void)getListsWithCompletionHandler:(CDUnknownBlockType)arg1;
- (id)initWithSession:(id)arg1;
- (id)initWithSessionConfiguration:(id)arg1;
- (id)init;
@end
| {
"pile_set_name": "Github"
} |
---
layout: page
title: Tags
permalink: /blog/tags
---
{% include blog/tags.html %} | {
"pile_set_name": "Github"
} |
/***************************************************************************
* LPRng - An Extended Print Spooler System
*
* Copyright 1988-2003, Patrick Powell, San Diego, CA
* [email protected]
* See LICENSE for conditions of use.
*
***************************************************************************/
static char *const _id =
"$Id: getopt.c,v 1.57 2003/09/05 20:07:18 papowell Exp $";
#include "lp.h"
/**** ENDINCLUDE ****/
# if 0
--------- now in lp.h ---------
int Optind; /* next argv to process */
int Opterr = 1; /* Zero disables errors msgs */
char *Optarg; /* Pointer to option argument */
char *Name; /* Name of program */
#endif
static char *next_opt; /* pointer to next option char */
static char **Argv_p;
static int Argc_p;
int Getopt (int argc, char *argv[], char *optstring)
{
int option; /* current option found */
char *match; /* matched option in optstring */
if( argv == 0 ){
/* reset parsing */
next_opt = 0;
Optind = 0;
return(0);
}
if (Optind == 0 ) {
char *basename;
/*
* set up the Name variable for error messages
* setproctitle will change this, so
* make a copy.
*/
if( Name == 0 ){
if( argv[0] ){
if( (basename = safestrrchr( argv[0], '/' )) ){
++basename;
} else {
basename = argv[0];
}
Name = basename;
} else {
Name = "???";
}
}
Argv_p = argv;
Argc_p = argc;
Optind = 1;
}
while( next_opt == 0 || *next_opt == '\0' ){
/* No more arguments left in current or initial string */
if (Optind >= argc){
return (EOF);
}
next_opt = argv[Optind++];
}
/* check for start of option string AND no initial '-' */
if( (next_opt == argv[Optind-1]) ){
if( next_opt[0] != '-' ){
--Optind;
return( EOF );
} else {
++next_opt;
if( next_opt[0] == 0 ){
return( EOF );
}
}
}
option = *next_opt++;
/*
* Case of '--', Force end of options
*/
if (option == '-') {
if( *next_opt ){
if( Opterr ){
(void) FPRINTF (STDERR, "--X option form illegal\n" );
return('?');
}
}
return ( EOF );
}
/*
* See if option is in optstring
*/
if ((match = (char *) safestrchr (optstring, option)) == 0 ){
if( Opterr ){
(void) FPRINTF (STDERR, "%s: Illegal option '%c'\n", Name, option);
}
return( '?' );
}
/*
* Argument?
*/
if (match[1] == ':') {
/*
* Set Optarg to proper value
*/
Optarg = 0;
if (*next_opt != '\0') {
Optarg = next_opt;
} else if (Optind < argc) {
Optarg = argv[Optind++];
if (Optarg != 0 && *Optarg == '-') {
Optarg = 0;
}
}
if( Optarg == 0 && Opterr ) {
(void) FPRINTF (STDERR,
"%s: missing argument for '%c'\n", Name, option);
option = '?';
}
next_opt = 0;
} else if (match[1] == '?') {
/*
* Set Optarg to proper value
*/
if (*next_opt != '\0') {
Optarg = next_opt;
} else {
Optarg = 0;
}
next_opt = 0;
}
return (option);
}
| {
"pile_set_name": "Github"
} |
GoodFET JTAG Applications
by Travis Goodspeed
Most MSP430 macros come from definitions in SLAU265A.
| {
"pile_set_name": "Github"
} |
#pragma once
// Params should go here....
// code goes here
// example ABI_SYSV int test(int input);
void sceRemoteplayApprove();
void sceRemoteplayClearAllRegistData();
void sceRemoteplayClearConnectHistory();
void sceRemoteplayConfirmDeviceRegist();
void sceRemoteplayDisconnect();
void sceRemoteplayGeneratePinCode();
void sceRemoteplayGetApMode();
void sceRemoteplayGetConnectHistory();
void sceRemoteplayGetConnectionStatus();
void sceRemoteplayGetConnectUserId();
void sceRemoteplayGetMbusDeviceInfo();
void sceRemoteplayGetRemoteplayStatus();
void sceRemoteplayGetRpMode();
void sceRemoteplayImeClose();
void sceRemoteplayImeFilterResult();
void sceRemoteplayImeGetEvent();
void sceRemoteplayImeNotify();
void sceRemoteplayImeNotifyEventResult();
void sceRemoteplayImeOpen();
void sceRemoteplayImeSetCaret();
void sceRemoteplayImeSetText();
void sceRemoteplayInitialize();
void sceRemoteplayIsRemoteOskReady();
void sceRemoteplayIsRemotePlaying();
void sceRemoteplayNotifyMbusDeviceRegistComplete();
void sceRemoteplayNotifyNpPushWakeup();
void sceRemoteplayNotifyPinCodeError();
void sceRemoteplayNotifyUserDelete();
void sceRemoteplayPrintAllRegistData();
void sceRemoteplayProhibit();
void sceRemoteplayProhibitStreaming();
void sceRemoteplaySetApMode();
void sceRemoteplaySetLogLevel();
void sceRemoteplaySetProhibition();
void sceRemoteplaySetProhibitionForVsh();
void sceRemoteplaySetRpMode();
void sceRemoteplayTerminate();
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.4"/>
<title>AndBase开发框架: src/com/ab/view/listener 目录参考</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { searchBox.OnSelectItem(0); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="ic_launcher.png"/></td>
<td style="padding-left: 0.5em;">
<div id="projectname">AndBase开发框架
 <span id="projectnumber">1.5.7</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- 制作者 Doxygen 1.8.4 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'搜索');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>首页</span></a></li>
<li><a href="pages.html"><span>相关页面</span></a></li>
<li><a href="namespaces.html"><span>命名空间</span></a></li>
<li><a href="annotated.html"><span>类</span></a></li>
<li><a href="files.html"><span>文件</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="搜索" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
<a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark"> </span>全部</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark"> </span>类</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark"> </span>命名空间</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark"> </span>文件</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark"> </span>函数</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark"> </span>变量</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(6)"><span class="SelectionMark"> </span>枚举值</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(7)"><span class="SelectionMark"> </span>页</a></div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="dir_68267d1309a1af8e8297ef4c3efbcdba.html">src</a></li><li class="navelem"><a class="el" href="dir_541eb0a6c58a7690acc5b848a4b1b724.html">com</a></li><li class="navelem"><a class="el" href="dir_dae2b154897f0cb08624485520423afe.html">ab</a></li><li class="navelem"><a class="el" href="dir_54a4ad554980bec28f2ae4858a4ebb6d.html">view</a></li><li class="navelem"><a class="el" href="dir_48a7f79fecf3b2ebc50d6d724a129917.html">listener</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title">listener 目录参考</div> </div>
</div><!--header-->
<div class="contents">
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="files"></a>
文件</h2></td></tr>
<tr class="memitem:_ab_ioc_event_listener_8java"><td class="memItemLeft" align="right" valign="top">文件  </td><td class="memItemRight" valign="bottom"><a class="el" href="_ab_ioc_event_listener_8java.html">AbIocEventListener.java</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:_ab_on_change_listener_8java"><td class="memItemLeft" align="right" valign="top">文件  </td><td class="memItemRight" valign="bottom"><a class="el" href="_ab_on_change_listener_8java.html">AbOnChangeListener.java</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:_ab_on_item_click_listener_8java"><td class="memItemLeft" align="right" valign="top">文件  </td><td class="memItemRight" valign="bottom"><a class="el" href="_ab_on_item_click_listener_8java.html">AbOnItemClickListener.java</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:_ab_on_list_view_listener_8java"><td class="memItemLeft" align="right" valign="top">文件  </td><td class="memItemRight" valign="bottom"><a class="el" href="_ab_on_list_view_listener_8java.html">AbOnListViewListener.java</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:_ab_on_open_listener_8java"><td class="memItemLeft" align="right" valign="top">文件  </td><td class="memItemRight" valign="bottom"><a class="el" href="_ab_on_open_listener_8java.html">AbOnOpenListener.java</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:_ab_on_page_change_listener_8java"><td class="memItemLeft" align="right" valign="top">文件  </td><td class="memItemRight" valign="bottom"><a class="el" href="_ab_on_page_change_listener_8java.html">AbOnPageChangeListener.java</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:_ab_on_progress_listener_8java"><td class="memItemLeft" align="right" valign="top">文件  </td><td class="memItemRight" valign="bottom"><a class="el" href="_ab_on_progress_listener_8java.html">AbOnProgressListener.java</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:_ab_on_refresh_listener_8java"><td class="memItemLeft" align="right" valign="top">文件  </td><td class="memItemRight" valign="bottom"><a class="el" href="_ab_on_refresh_listener_8java.html">AbOnRefreshListener.java</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:_ab_on_scroll_listener_8java"><td class="memItemLeft" align="right" valign="top">文件  </td><td class="memItemRight" valign="bottom"><a class="el" href="_ab_on_scroll_listener_8java.html">AbOnScrollListener.java</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:_ab_on_touch_listener_8java"><td class="memItemLeft" align="right" valign="top">文件  </td><td class="memItemRight" valign="bottom"><a class="el" href="_ab_on_touch_listener_8java.html">AbOnTouchListener.java</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
</table>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
生成于 2014年 三月 19日 星期三 16:24:32 , 为 AndBase开发框架使用  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.4
</small></address>
</body>
</html>
| {
"pile_set_name": "Github"
} |
<?xml version='1.0' encoding='utf-8'?>
<fluidity_options>
<simulation_name>
<string_value lines="1">MMS_C_cv</string_value>
</simulation_name>
<problem_type>
<string_value lines="1">fluids</string_value>
</problem_type>
<geometry>
<dimension>
<integer_value rank="0">3</integer_value>
</dimension>
<mesh name="CoordinateMesh">
<from_file file_name="MMS_C">
<format name="gmsh"/>
<stat>
<include_in_stat/>
</stat>
</from_file>
</mesh>
<mesh name="VelocityMesh">
<from_mesh>
<mesh name="CoordinateMesh"/>
<mesh_shape>
<polynomial_degree>
<integer_value rank="0">1</integer_value>
</polynomial_degree>
</mesh_shape>
<stat>
<exclude_from_stat/>
</stat>
</from_mesh>
</mesh>
<quadrature>
<degree>
<integer_value rank="0">5</integer_value>
</degree>
<controlvolume_surface_degree>
<integer_value rank="0">5</integer_value>
</controlvolume_surface_degree>
</quadrature>
</geometry>
<io>
<dump_format>
<string_value>vtk</string_value>
</dump_format>
<dump_period>
<constant>
<real_value rank="0">1000.0</real_value>
</constant>
</dump_period>
<output_mesh name="VelocityMesh"/>
<stat/>
</io>
<timestepping>
<current_time>
<real_value rank="0">0.0</real_value>
</current_time>
<timestep>
<real_value rank="0">0.0020631993150867218</real_value>
<comment>0.0020631993150867218 gives a cv cfl number of 0.5</comment>
</timestep>
<finish_time>
<real_value rank="0">5.0</real_value>
</finish_time>
<steady_state>
<tolerance>
<real_value rank="0">1.E-10</real_value>
<infinity_norm/>
</tolerance>
<acceleration_form/>
</steady_state>
</timestepping>
<material_phase name="Burgers">
<vector_field rank="1" name="Velocity">
<prescribed>
<mesh name="VelocityMesh"/>
<value name="WholeMesh">
<python>
<string_value type="code" language="python" lines="20">def val(XX, t):
from math import sin,cos
x = XX[0];
y = XX[1];
x2 = x*x;
y2 = y*y;
u = sin(5*(x2+y2));
v = cos(3*(x2-y2));
w = 0
return (u, v, w)</string_value>
</python>
</value>
<output/>
<stat>
<include_in_stat/>
</stat>
<detectors>
<exclude_from_detectors/>
</detectors>
<particles>
<exclude_from_particles/>
</particles>
</prescribed>
</vector_field>
<scalar_field rank="0" name="NumericalSolution">
<prognostic>
<mesh name="VelocityMesh"/>
<equation name="AdvectionDiffusion"/>
<spatial_discretisation>
<control_volumes>
<mass_terms>
<exclude_mass_terms/>
</mass_terms>
<face_value name="FirstOrderUpwind"/>
<diffusion_scheme name="BassiRebay"/>
</control_volumes>
<conservative_advection>
<real_value rank="0">0.0</real_value>
</conservative_advection>
</spatial_discretisation>
<temporal_discretisation>
<theta>
<real_value rank="0">1.0</real_value>
</theta>
</temporal_discretisation>
<solver>
<iterative_method name="gmres">
<restart>
<integer_value rank="0">30</integer_value>
</restart>
</iterative_method>
<preconditioner name="sor"/>
<relative_error>
<real_value rank="0">1.E-10</real_value>
</relative_error>
<max_iterations>
<integer_value rank="0">350</integer_value>
</max_iterations>
<never_ignore_solver_failures/>
<diagnostics>
<monitors/>
</diagnostics>
</solver>
<initial_condition name="WholeMesh">
<constant>
<real_value rank="0">0.0</real_value>
</constant>
</initial_condition>
<boundary_conditions name="sides">
<surface_ids>
<integer_value rank="1" shape="2">7 10</integer_value>
</surface_ids>
<type name="dirichlet">
<python>
<string_value type="code" language="python" lines="20">def val(XX, t):
from math import sin,cos,sqrt
omega = 0.0;
x = XX[0];
y = XX[1];
x4 = x*x*x*x;
y2 = y*y;
u = sin(25*x*y+omega*t)-2*y/(sqrt(x));
return u</string_value>
</python>
</type>
</boundary_conditions>
<scalar_field name="Source" rank="0">
<prescribed>
<value name="WholeMesh">
<python>
<string_value type="code" language="python" lines="20">def val(XX, t):
from math import sin,cos,sqrt
omega = 0.0;
x = XX[0];
y = XX[1];
x2 = x*x;
y2 = y*y;
xp5 = sqrt(x)
x1p5 = xp5*x
S = (25*y*cos(25*x*y) + 1.0*y/x1p5)*sin(5*(y2 + x2)) + (25*x*cos(25*x*y) - 2/xp5)*cos(3*(x2 - y2));
return S</string_value>
</python>
</value>
<output/>
<stat/>
<detectors>
<exclude_from_detectors/>
</detectors>
<particles>
<exclude_from_particles/>
</particles>
</prescribed>
</scalar_field>
<output>
<include_previous_time_step/>
</output>
<stat/>
<convergence>
<include_in_convergence/>
</convergence>
<detectors>
<include_in_detectors/>
</detectors>
<particles>
<exclude_from_particles/>
</particles>
<steady_state>
<include_in_steady_state/>
</steady_state>
<consistent_interpolation/>
</prognostic>
</scalar_field>
<scalar_field rank="0" name="AnalyticalSolution">
<prescribed>
<mesh name="VelocityMesh"/>
<value name="WholeMesh">
<python>
<string_value type="code" language="python" lines="20">def val(XX, t):
from math import sin,cos,sqrt
omega = 0.0;
x = XX[0];
y = XX[1];
u = sin(25*x*y + omega*t) - 2*y/(sqrt(x));
return u</string_value>
</python>
</value>
<output/>
<stat/>
<detectors>
<exclude_from_detectors/>
</detectors>
<particles>
<exclude_from_particles/>
</particles>
</prescribed>
</scalar_field>
<scalar_field rank="0" name="AbsoluteDifference">
<diagnostic field_name_a="AnalyticalSolution" field_name_b="NumericalSolution">
<algorithm name="Internal" material_phase_support="multiple"/>
<mesh name="VelocityMesh"/>
<output/>
<stat>
<include_cv_stats/>
</stat>
<convergence>
<include_in_convergence/>
</convergence>
<detectors>
<include_in_detectors/>
</detectors>
<particles>
<exclude_from_particles/>
</particles>
<steady_state>
<include_in_steady_state/>
</steady_state>
</diagnostic>
</scalar_field>
</material_phase>
</fluidity_options>
| {
"pile_set_name": "Github"
} |
#include <occa/modes/metal/stream.hpp>
namespace occa {
namespace metal {
stream::stream(modeDevice_t *modeDevice_,
const occa::properties &properties_,
api::metal::commandQueue_t metalCommandQueue_) :
modeStream_t(modeDevice_, properties_),
metalCommandQueue(metalCommandQueue_) {}
stream::~stream() {
metalCommandQueue.free();
}
}
}
| {
"pile_set_name": "Github"
} |
@echo off
del *.ncb
del *.aps
del *.opt
del *.plg
cls | {
"pile_set_name": "Github"
} |
package endpoints
import "testing"
func TestEnumDefaultPartitions(t *testing.T) {
resolver := DefaultResolver()
enum, ok := resolver.(EnumPartitions)
if ok != true {
t.Fatalf("resolver must satisfy EnumPartition interface")
}
ps := enum.Partitions()
if a, e := len(ps), len(defaultPartitions); a != e {
t.Errorf("expected %d partitions, got %d", e, a)
}
}
func TestEnumDefaultRegions(t *testing.T) {
expectPart := defaultPartitions[0]
partEnum := defaultPartitions[0].Partition()
regEnum := partEnum.Regions()
if a, e := len(regEnum), len(expectPart.Regions); a != e {
t.Errorf("expected %d regions, got %d", e, a)
}
}
func TestEnumPartitionServices(t *testing.T) {
expectPart := testPartitions[0]
partEnum := testPartitions[0].Partition()
if a, e := partEnum.ID(), "part-id"; a != e {
t.Errorf("expect %q partition ID, got %q", e, a)
}
svcEnum := partEnum.Services()
if a, e := len(svcEnum), len(expectPart.Services); a != e {
t.Errorf("expected %d regions, got %d", e, a)
}
}
func TestEnumRegionServices(t *testing.T) {
p := testPartitions[0].Partition()
rs := p.Regions()
if a, e := len(rs), 2; a != e {
t.Errorf("expect %d regions got %d", e, a)
}
if _, ok := rs["us-east-1"]; !ok {
t.Errorf("expect us-east-1 region to be found, was not")
}
if _, ok := rs["us-west-2"]; !ok {
t.Errorf("expect us-west-2 region to be found, was not")
}
r := rs["us-east-1"]
if a, e := r.ID(), "us-east-1"; a != e {
t.Errorf("expect %q region ID, got %q", e, a)
}
if a, e := r.Description(), "region description"; a != e {
t.Errorf("expect %q region Description, got %q", e, a)
}
ss := r.Services()
if a, e := len(ss), 1; a != e {
t.Errorf("expect %d services for us-east-1, got %d", e, a)
}
if _, ok := ss["service1"]; !ok {
t.Errorf("expect service1 service to be found, was not")
}
resolved, err := r.ResolveEndpoint("service1")
if err != nil {
t.Fatalf("expect no error, got %v", err)
}
if a, e := resolved.URL, "https://service1.us-east-1.amazonaws.com"; a != e {
t.Errorf("expect %q resolved URL, got %q", e, a)
}
}
func TestEnumServiceRegions(t *testing.T) {
p := testPartitions[0].Partition()
rs := p.Services()["service1"].Regions()
if e, a := 2, len(rs); e != a {
t.Errorf("expect %d regions, got %d", e, a)
}
if _, ok := rs["us-east-1"]; !ok {
t.Errorf("expect region to be found")
}
if _, ok := rs["us-west-2"]; !ok {
t.Errorf("expect region to be found")
}
}
func TestEnumServicesEndpoints(t *testing.T) {
p := testPartitions[0].Partition()
ss := p.Services()
if a, e := len(ss), 5; a != e {
t.Errorf("expect %d regions got %d", e, a)
}
if _, ok := ss["service1"]; !ok {
t.Errorf("expect service1 region to be found, was not")
}
if _, ok := ss["service2"]; !ok {
t.Errorf("expect service2 region to be found, was not")
}
s := ss["service1"]
if a, e := s.ID(), "service1"; a != e {
t.Errorf("expect %q service ID, got %q", e, a)
}
resolved, err := s.ResolveEndpoint("us-west-2")
if err != nil {
t.Fatalf("expect no error, got %v", err)
}
if a, e := resolved.URL, "https://service1.us-west-2.amazonaws.com"; a != e {
t.Errorf("expect %q resolved URL, got %q", e, a)
}
}
func TestEnumEndpoints(t *testing.T) {
p := testPartitions[0].Partition()
s := p.Services()["service1"]
es := s.Endpoints()
if a, e := len(es), 2; a != e {
t.Errorf("expect %d endpoints for service2, got %d", e, a)
}
if _, ok := es["us-east-1"]; !ok {
t.Errorf("expect us-east-1 to be found, was not")
}
e := es["us-east-1"]
if a, e := e.ID(), "us-east-1"; a != e {
t.Errorf("expect %q endpoint ID, got %q", e, a)
}
if a, e := e.ServiceID(), "service1"; a != e {
t.Errorf("expect %q service ID, got %q", e, a)
}
resolved, err := e.ResolveEndpoint()
if err != nil {
t.Fatalf("expect no error, got %v", err)
}
if a, e := resolved.URL, "https://service1.us-east-1.amazonaws.com"; a != e {
t.Errorf("expect %q resolved URL, got %q", e, a)
}
}
func TestResolveEndpointForPartition(t *testing.T) {
enum := testPartitions.Partitions()[0]
expected, err := testPartitions.EndpointFor("service1", "us-east-1")
actual, err := enum.EndpointFor("service1", "us-east-1")
if err != nil {
t.Fatalf("unexpected error, %v", err)
}
if expected != actual {
t.Errorf("expect resolved endpoint to be %v, but got %v", expected, actual)
}
}
func TestAddScheme(t *testing.T) {
cases := []struct {
In string
Expect string
DisableSSL bool
}{
{
In: "https://example.com",
Expect: "https://example.com",
},
{
In: "example.com",
Expect: "https://example.com",
},
{
In: "http://example.com",
Expect: "http://example.com",
},
{
In: "example.com",
Expect: "http://example.com",
DisableSSL: true,
},
{
In: "https://example.com",
Expect: "https://example.com",
DisableSSL: true,
},
}
for i, c := range cases {
actual := AddScheme(c.In, c.DisableSSL)
if actual != c.Expect {
t.Errorf("%d, expect URL to be %q, got %q", i, c.Expect, actual)
}
}
}
func TestResolverFunc(t *testing.T) {
var resolver Resolver
resolver = ResolverFunc(func(s, r string, opts ...func(*Options)) (ResolvedEndpoint, error) {
return ResolvedEndpoint{
URL: "https://service.region.dnssuffix.com",
SigningRegion: "region",
SigningName: "service",
}, nil
})
resolved, err := resolver.EndpointFor("service", "region", func(o *Options) {
o.DisableSSL = true
})
if err != nil {
t.Fatalf("expect no error, got %v", err)
}
if a, e := resolved.URL, "https://service.region.dnssuffix.com"; a != e {
t.Errorf("expect %q endpoint URL, got %q", e, a)
}
if a, e := resolved.SigningRegion, "region"; a != e {
t.Errorf("expect %q region, got %q", e, a)
}
if a, e := resolved.SigningName, "service"; a != e {
t.Errorf("expect %q signing name, got %q", e, a)
}
}
func TestOptionsSet(t *testing.T) {
var actual Options
actual.Set(DisableSSLOption, UseDualStackOption, StrictMatchingOption)
expect := Options{
DisableSSL: true,
UseDualStack: true,
StrictMatching: true,
}
if actual != expect {
t.Errorf("expect %v options got %v", expect, actual)
}
}
func TestRegionsForService(t *testing.T) {
ps := DefaultPartitions()
var expect map[string]Region
var serviceID string
for _, s := range ps[0].Services() {
expect = s.Regions()
serviceID = s.ID()
if len(expect) > 0 {
break
}
}
actual, ok := RegionsForService(ps, ps[0].ID(), serviceID)
if !ok {
t.Fatalf("expect regions to be found, was not")
}
if len(actual) == 0 {
t.Fatalf("expect service %s to have regions", serviceID)
}
if e, a := len(expect), len(actual); e != a {
t.Fatalf("expect %d regions, got %d", e, a)
}
for id, r := range actual {
if e, a := id, r.ID(); e != a {
t.Errorf("expect %s region id, got %s", e, a)
}
if _, ok := expect[id]; !ok {
t.Errorf("expect %s region to be found", id)
}
if a, e := r.Description(), expect[id].desc; a != e {
t.Errorf("expect %q region Description, got %q", e, a)
}
}
}
func TestRegionsForService_NotFound(t *testing.T) {
ps := testPartitions.Partitions()
actual, ok := RegionsForService(ps, ps[0].ID(), "service-not-exists")
if ok {
t.Fatalf("expect no regions to be found, but were")
}
if len(actual) != 0 {
t.Errorf("expect no regions, got %v", actual)
}
}
func TestPartitionForRegion(t *testing.T) {
ps := DefaultPartitions()
expect := ps[len(ps)%2]
var regionID string
for id := range expect.Regions() {
regionID = id
break
}
actual, ok := PartitionForRegion(ps, regionID)
if !ok {
t.Fatalf("expect partition to be found")
}
if e, a := expect.ID(), actual.ID(); e != a {
t.Errorf("expect %s partition, got %s", e, a)
}
}
func TestPartitionForRegion_NotFound(t *testing.T) {
ps := DefaultPartitions()
actual, ok := PartitionForRegion(ps, "regionNotExists")
if ok {
t.Errorf("expect no partition to be found, got %v", actual)
}
}
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.8"/>
<title>AndBase开发框架: com.ab.util.AbJsonUtil< T >类 参考</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { searchBox.OnSelectItem(0); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="ic_launcher.png"/></td>
<td style="padding-left: 0.5em;">
<div id="projectname">AndBase开发框架
 <span id="projectnumber">1.6</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- 制作者 Doxygen 1.8.8 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'搜索');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>首页</span></a></li>
<li><a href="pages.html"><span>相关页面</span></a></li>
<li><a href="namespaces.html"><span>命名空间</span></a></li>
<li class="current"><a href="annotated.html"><span>类</span></a></li>
<li><a href="files.html"><span>文件</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="搜索" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>类列表</span></a></li>
<li><a href="classes.html"><span>类索引</span></a></li>
<li><a href="hierarchy.html"><span>类继承关系</span></a></li>
<li><a href="functions.html"><span>类成员</span></a></li>
</ul>
</div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
<a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark"> </span>全部</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark"> </span>类</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark"> </span>命名空间</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark"> </span>文件</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark"> </span>函数</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark"> </span>变量</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(6)"><span class="SelectionMark"> </span>枚举值</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(7)"><span class="SelectionMark"> </span>页</a></div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="namespacecom.html">com</a></li><li class="navelem"><a class="el" href="namespacecom_1_1ab.html">ab</a></li><li class="navelem"><a class="el" href="namespacecom_1_1ab_1_1util.html">util</a></li><li class="navelem"><a class="el" href="classcom_1_1ab_1_1util_1_1_ab_json_util_3_01_t_01_4.html">AbJsonUtil< T ></a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="summary">
<a href="#nested-classes">类</a> |
<a href="#pub-static-methods">静态 Public 成员函数</a> |
<a href="classcom_1_1ab_1_1util_1_1_ab_json_util_3_01_t_01_4-members.html">所有成员列表</a> </div>
<div class="headertitle">
<div class="title">com.ab.util.AbJsonUtil< T >类 参考</div> </div>
</div><!--header-->
<div class="contents">
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="nested-classes"></a>
类</h2></td></tr>
<tr class="memitem:"><td class="memItemLeft" align="right" valign="top">class  </td><td class="memItemRight" valign="bottom"><a class="el" href="classcom_1_1ab_1_1util_1_1_ab_json_util_3_01_t_01_4_1_1_user.html">User</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-static-methods"></a>
静态 Public 成员函数</h2></td></tr>
<tr class="memitem:aa99aa6e31a9b587655ad0f91da86c8f3"><td class="memItemLeft" align="right" valign="top">static String </td><td class="memItemRight" valign="bottom"><a class="el" href="classcom_1_1ab_1_1util_1_1_ab_json_util_3_01_t_01_4.html#aa99aa6e31a9b587655ad0f91da86c8f3">toJson</a> (Object src)</td></tr>
<tr class="separator:aa99aa6e31a9b587655ad0f91da86c8f3"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a709370540612360b6583e232f64b5b8e"><td class="memItemLeft" align="right" valign="top">static String </td><td class="memItemRight" valign="bottom"><a class="el" href="classcom_1_1ab_1_1util_1_1_ab_json_util_3_01_t_01_4.html#a709370540612360b6583e232f64b5b8e">toJson</a> (List<?> list)</td></tr>
<tr class="separator:a709370540612360b6583e232f64b5b8e"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ace7098a26e1a551f0de6d1878313f000"><td class="memItemLeft" align="right" valign="top">static List<?> </td><td class="memItemRight" valign="bottom"><a class="el" href="classcom_1_1ab_1_1util_1_1_ab_json_util_3_01_t_01_4.html#ace7098a26e1a551f0de6d1878313f000">fromJson</a> (String json, TypeToken typeToken)</td></tr>
<tr class="separator:ace7098a26e1a551f0de6d1878313f000"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a37b08d5fa4ab679f24e2fc6f272d1e5e"><td class="memItemLeft" align="right" valign="top">static Object </td><td class="memItemRight" valign="bottom"><a class="el" href="classcom_1_1ab_1_1util_1_1_ab_json_util_3_01_t_01_4.html#a37b08d5fa4ab679f24e2fc6f272d1e5e">fromJson</a> (String json, Class clazz)</td></tr>
<tr class="separator:a37b08d5fa4ab679f24e2fc6f272d1e5e"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ac00d4994b41ff390c5206d4a59ce8f15"><td class="memItemLeft" align="right" valign="top">static void </td><td class="memItemRight" valign="bottom"><a class="el" href="classcom_1_1ab_1_1util_1_1_ab_json_util_3_01_t_01_4.html#ac00d4994b41ff390c5206d4a59ce8f15">main</a> (String[] args)</td></tr>
<tr class="separator:ac00d4994b41ff390c5206d4a59ce8f15"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<a name="details" id="details"></a><h2 class="groupheader">详细描述</h2>
<div class="textblock"><p>© 2012 amsoft.cn 名称:AbStrUtil.java 描述:json处理类.</p>
<dl class="section author"><dt>作者</dt><dd>还如一梦中 </dd></dl>
<dl class="section version"><dt>版本</dt><dd>v1.0 </dd></dl>
<dl class="section date"><dt>日期</dt><dd>:2013-01-17 下午11:52:13 </dd></dl>
<dl class="params"><dt>参数</dt><dd>
<table class="params">
<tr><td class="paramname"><T></td><td></td></tr>
</table>
</dd>
</dl>
</div><h2 class="groupheader">成员函数说明</h2>
<a class="anchor" id="ace7098a26e1a551f0de6d1878313f000"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">static List<?> com.ab.util.AbJsonUtil< T >.fromJson </td>
<td>(</td>
<td class="paramtype">String </td>
<td class="paramname"><em>json</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">TypeToken </td>
<td class="paramname"><em>typeToken</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">inline</span><span class="mlabel">static</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>描述:将json转化为列表. </p><dl class="params"><dt>参数</dt><dd>
<table class="params">
<tr><td class="paramname">json</td><td></td></tr>
<tr><td class="paramname">typeToken</td><td>new TypeToken<ArrayList<?>>() {}.getType(); </td></tr>
</table>
</dd>
</dl>
<dl class="section return"><dt>返回</dt><dd></dd></dl>
</div>
</div>
<a class="anchor" id="a37b08d5fa4ab679f24e2fc6f272d1e5e"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">static Object com.ab.util.AbJsonUtil< T >.fromJson </td>
<td>(</td>
<td class="paramtype">String </td>
<td class="paramname"><em>json</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">Class </td>
<td class="paramname"><em>clazz</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">inline</span><span class="mlabel">static</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>描述:将json转化为对象. </p><dl class="params"><dt>参数</dt><dd>
<table class="params">
<tr><td class="paramname">json</td><td></td></tr>
<tr><td class="paramname">clazz</td><td></td></tr>
</table>
</dd>
</dl>
<dl class="section return"><dt>返回</dt><dd></dd></dl>
</div>
</div>
<a class="anchor" id="ac00d4994b41ff390c5206d4a59ce8f15"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">static void com.ab.util.AbJsonUtil< T >.main </td>
<td>(</td>
<td class="paramtype">String[] </td>
<td class="paramname"><em>args</em></td><td>)</td>
<td></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">inline</span><span class="mlabel">static</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>The main method.</p>
<dl class="params"><dt>参数</dt><dd>
<table class="params">
<tr><td class="paramname">args</td><td>the arguments </td></tr>
</table>
</dd>
</dl>
</div>
</div>
<a class="anchor" id="aa99aa6e31a9b587655ad0f91da86c8f3"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">static String com.ab.util.AbJsonUtil< T >.toJson </td>
<td>(</td>
<td class="paramtype">Object </td>
<td class="paramname"><em>src</em></td><td>)</td>
<td></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">inline</span><span class="mlabel">static</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>描述:将对象转化为json. </p><dl class="params"><dt>参数</dt><dd>
<table class="params">
<tr><td class="paramname">list</td><td></td></tr>
</table>
</dd>
</dl>
<dl class="section return"><dt>返回</dt><dd></dd></dl>
</div>
</div>
<a class="anchor" id="a709370540612360b6583e232f64b5b8e"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">static String com.ab.util.AbJsonUtil< T >.toJson </td>
<td>(</td>
<td class="paramtype">List<?> </td>
<td class="paramname"><em>list</em></td><td>)</td>
<td></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">inline</span><span class="mlabel">static</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>描述:将列表转化为json. </p><dl class="params"><dt>参数</dt><dd>
<table class="params">
<tr><td class="paramname">list</td><td></td></tr>
</table>
</dd>
</dl>
<dl class="section return"><dt>返回</dt><dd></dd></dl>
</div>
</div>
<hr/>该类的文档由以下文件生成:<ul>
<li>src/com/ab/util/<a class="el" href="_ab_json_util_8java.html">AbJsonUtil.java</a></li>
</ul>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
生成于 2014年 十一月 6日 星期四 11:22:02 , 为 AndBase开发框架使用  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.8
</small></address>
</body>
</html>
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.8"/>
<title>NVIDIA DeepLearning Dataset Synthesizer (NDDS): UNVSceneFeatureExtractor_ScenePixelVelocity Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
$(window).load(resizeHeight);
</script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { searchBox.OnSelectItem(0); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">NVIDIA DeepLearning Dataset Synthesizer (NDDS)
</div>
</td>
<td> <div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.8 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){initNavTree('class_u_n_v_scene_feature_extractor___scene_pixel_velocity.html','');});
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
<a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark"> </span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark"> </span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark"> </span>Namespaces</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark"> </span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark"> </span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark"> </span>Typedefs</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(6)"><span class="SelectionMark"> </span>Pages</a></div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="header">
<div class="summary">
<a href="#pub-methods">Public Member Functions</a> |
<a href="#pro-methods">Protected Member Functions</a> |
<a href="class_u_n_v_scene_feature_extractor___scene_pixel_velocity-members.html">List of all members</a> </div>
<div class="headertitle">
<div class="title">UNVSceneFeatureExtractor_ScenePixelVelocity Class Reference</div> </div>
</div><!--header-->
<div class="contents">
<div id="dynsection-0" onclick="return toggleVisibility(this)" class="dynheader closed" style="cursor:pointer;">
<img id="dynsection-0-trigger" src="closed.png" alt="+"/> Inheritance diagram for UNVSceneFeatureExtractor_ScenePixelVelocity:</div>
<div id="dynsection-0-summary" class="dynsummary" style="display:block;">
</div>
<div id="dynsection-0-content" class="dyncontent" style="display:none;">
<div class="center"><img src="class_u_n_v_scene_feature_extractor___scene_pixel_velocity__inherit__graph.png" border="0" usemap="#_u_n_v_scene_feature_extractor___scene_pixel_velocity_inherit__map" alt="Inheritance graph"/></div>
<map name="_u_n_v_scene_feature_extractor___scene_pixel_velocity_inherit__map" id="_u_n_v_scene_feature_extractor___scene_pixel_velocity_inherit__map">
<area shape="rect" id="node2" href="class_u_n_v_scene_feature_extractor___pixel_data.html" title="Base class for all the feature extractors that capture the scene view in pixel data format..." alt="" coords="5,155,188,196"/>
<area shape="rect" id="node3" href="class_u_n_v_scene_feature_extractor.html" title="UNVSceneFeatureExtractor" alt="" coords="5,80,188,107"/>
</map>
<center><span class="legend">[<a target="top" href="graph_legend.html">legend</a>]</span></center></div>
<div id="dynsection-1" onclick="return toggleVisibility(this)" class="dynheader closed" style="cursor:pointer;">
<img id="dynsection-1-trigger" src="closed.png" alt="+"/> Collaboration diagram for UNVSceneFeatureExtractor_ScenePixelVelocity:</div>
<div id="dynsection-1-summary" class="dynsummary" style="display:block;">
</div>
<div id="dynsection-1-content" class="dyncontent" style="display:none;">
<div class="center"><img src="class_u_n_v_scene_feature_extractor___scene_pixel_velocity__coll__graph.png" border="0" usemap="#_u_n_v_scene_feature_extractor___scene_pixel_velocity_coll__map" alt="Collaboration graph"/></div>
<map name="_u_n_v_scene_feature_extractor___scene_pixel_velocity_coll__map" id="_u_n_v_scene_feature_extractor___scene_pixel_velocity_coll__map">
<area shape="rect" id="node2" href="class_u_n_v_scene_feature_extractor___pixel_data.html" title="Base class for all the feature extractors that capture the scene view in pixel data format..." alt="" coords="1921,273,2104,314"/>
<area shape="rect" id="node3" href="class_u_n_v_scene_feature_extractor.html" title="UNVSceneFeatureExtractor" alt="" coords="1689,152,1872,179"/>
<area shape="rect" id="node13" href="class_u_n_v_scene_data_handler.html" title="Base interface for serializing/visualizing captured pixel and annotation data. " alt="" coords="213,93,370,120"/>
<area shape="rect" id="node5" href="class_u_n_v_scene_capturer_viewpoint_component.html" title="UNVSceneCapturerViewpointComponent: Represents each viewpoint from where the capturer captures data..." alt="" coords="1353,199,1544,241"/>
<area shape="rect" id="node7" href="class_a_n_v_scene_capturer_actor.html" title="The scene exporter actor. " alt="" coords="999,145,1165,172"/>
<area shape="rect" id="node9" href="struct_f_n_v_scene_capturer_settings.html" title="FNVSceneCapturerSettings" alt="" coords="602,257,785,284"/>
<area shape="rect" id="node15" href="struct_f_n_v_scene_capturer_viewpoint_settings.html" title="FNVSceneCapturerViewpoint\lSettings" alt="" coords="987,263,1177,305"/>
<area shape="rect" id="node10" href="struct_f_camera_intrinsic_settings.html" title="FCameraIntrinsicSettings" alt="" coords="207,212,375,239"/>
<area shape="rect" id="node11" href="struct_f_n_v_image_size.html" title="FNVImageSize" alt="" coords="237,279,346,305"/>
<area shape="rect" id="node16" href="class_u_n_v_scene_capture_component2_d.html" title="UNVSceneCaptureComponent2D" alt="" coords="587,339,800,365"/>
<area shape="rect" id="node12" href="class_u_n_v_scene_data_visualizer.html" title="NVSceneDataVisualizer - visualize all the captured data (image buffer and object annotation info) usi..." alt="" coords="608,93,779,120"/>
<area shape="rect" id="node14" href="struct_f_n_v_frame_counter.html" title="FNVFrameCounter" alt="" coords="628,43,759,69"/>
<area shape="rect" id="node18" href="struct_f_n_v_texture_render_target_reader.html" title="FNVTextureRenderTargetReader" alt="" coords="187,397,396,424"/>
<area shape="rect" id="node19" href="struct_f_n_v_texture_reader.html" title="FNVTextureReader" alt="" coords="5,397,137,424"/>
</map>
<center><span class="legend">[<a target="top" href="graph_legend.html">legend</a>]</span></center></div>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a>
Public Member Functions</h2></td></tr>
<tr class="memitem:a5ccb3c5558f3bf6efecc6bcc44efe42d"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a5ccb3c5558f3bf6efecc6bcc44efe42d"></a>
 </td><td class="memItemRight" valign="bottom"><b>UNVSceneFeatureExtractor_ScenePixelVelocity</b> (const FObjectInitializer &ObjectInitializer)</td></tr>
<tr class="separator:a5ccb3c5558f3bf6efecc6bcc44efe42d"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="inherit_header pub_methods_class_u_n_v_scene_feature_extractor___pixel_data"><td colspan="2" onclick="javascript:toggleInherit('pub_methods_class_u_n_v_scene_feature_extractor___pixel_data')"><img src="closed.png" alt="-"/> Public Member Functions inherited from <a class="el" href="class_u_n_v_scene_feature_extractor___pixel_data.html">UNVSceneFeatureExtractor_PixelData</a></td></tr>
<tr class="memitem:ae58cb308bfdc06a375f7fa0d6b822d47 inherit pub_methods_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ae58cb308bfdc06a375f7fa0d6b822d47"></a>
 </td><td class="memItemRight" valign="bottom"><b>UNVSceneFeatureExtractor_PixelData</b> (const FObjectInitializer &ObjectInitializer)</td></tr>
<tr class="separator:ae58cb308bfdc06a375f7fa0d6b822d47 inherit pub_methods_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a64509d26037585505a31d771931797a6 inherit pub_methods_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a64509d26037585505a31d771931797a6"></a>
virtual bool </td><td class="memItemRight" valign="bottom"><b>CaptureSceneToPixelsData</b> (<a class="el" href="class_u_n_v_scene_feature_extractor___pixel_data.html#a0f21b8ac8c3eeb15148ce22137b4c16c">UNVSceneFeatureExtractor_PixelData::OnFinishedCaptureScenePixelsDataCallback</a> Callback)</td></tr>
<tr class="separator:a64509d26037585505a31d771931797a6 inherit pub_methods_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ada6b9b701847afe7c550dbcff2eaa67e inherit pub_methods_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ada6b9b701847afe7c550dbcff2eaa67e"></a>
<a class="el" href="class_u_n_v_scene_capture_component2_d.html">UNVSceneCaptureComponent2D</a> * </td><td class="memItemRight" valign="bottom"><b>CreateSceneCaptureComponent2d</b> (UMaterialInstance *PostProcessingMaterial=nullptr, const FString &ComponentName=TEXT(""))</td></tr>
<tr class="separator:ada6b9b701847afe7c550dbcff2eaa67e inherit pub_methods_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:af2351acda25b581ea03911e920fd7dd3 inherit pub_methods_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="af2351acda25b581ea03911e920fd7dd3"></a>
virtual class <br class="typebreak" />
UTextureRenderTarget2D * </td><td class="memItemRight" valign="bottom"><b>GetRenderTarget</b> () const </td></tr>
<tr class="separator:af2351acda25b581ea03911e920fd7dd3 inherit pub_methods_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a5b5661d6f8f149414d3b0ce3c86e47c2 inherit pub_methods_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a5b5661d6f8f149414d3b0ce3c86e47c2"></a>
virtual void </td><td class="memItemRight" valign="bottom"><b>StartCapturing</b> () override</td></tr>
<tr class="separator:a5b5661d6f8f149414d3b0ce3c86e47c2 inherit pub_methods_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a629cc58cb76a88f17d77be32a23cc364 inherit pub_methods_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a629cc58cb76a88f17d77be32a23cc364"></a>
virtual void </td><td class="memItemRight" valign="bottom"><b>StopCapturing</b> () override</td></tr>
<tr class="separator:a629cc58cb76a88f17d77be32a23cc364 inherit pub_methods_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a3a27e205c76587f448e2aa829857788c inherit pub_methods_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a3a27e205c76587f448e2aa829857788c"></a>
virtual void </td><td class="memItemRight" valign="bottom"><b>UpdateCapturerSettings</b> () override</td></tr>
<tr class="separator:a3a27e205c76587f448e2aa829857788c inherit pub_methods_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="inherit_header pub_methods_class_u_n_v_scene_feature_extractor"><td colspan="2" onclick="javascript:toggleInherit('pub_methods_class_u_n_v_scene_feature_extractor')"><img src="closed.png" alt="-"/> Public Member Functions inherited from <a class="el" href="class_u_n_v_scene_feature_extractor.html">UNVSceneFeatureExtractor</a></td></tr>
<tr class="memitem:a76359ae0cb2d17f37fdbbbcbb7787d87 inherit pub_methods_class_u_n_v_scene_feature_extractor"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a76359ae0cb2d17f37fdbbbcbb7787d87"></a>
 </td><td class="memItemRight" valign="bottom"><b>UNVSceneFeatureExtractor</b> (const FObjectInitializer &ObjectInitializer)</td></tr>
<tr class="separator:a76359ae0cb2d17f37fdbbbcbb7787d87 inherit pub_methods_class_u_n_v_scene_feature_extractor"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:aaa0997c8a905cb26d91115bb021be1d5 inherit pub_methods_class_u_n_v_scene_feature_extractor"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="aaa0997c8a905cb26d91115bb021be1d5"></a>
FString </td><td class="memItemRight" valign="bottom"><b>GetDisplayName</b> () const </td></tr>
<tr class="separator:aaa0997c8a905cb26d91115bb021be1d5 inherit pub_methods_class_u_n_v_scene_feature_extractor"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a274a31dbb06870dcaf24d0fedd6bbd35 inherit pub_methods_class_u_n_v_scene_feature_extractor"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a274a31dbb06870dcaf24d0fedd6bbd35"></a>
virtual class UWorld * </td><td class="memItemRight" valign="bottom"><b>GetWorld</b> () const override</td></tr>
<tr class="separator:a274a31dbb06870dcaf24d0fedd6bbd35 inherit pub_methods_class_u_n_v_scene_feature_extractor"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a15361c8657be31e8b340defd0ab59466 inherit pub_methods_class_u_n_v_scene_feature_extractor"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a15361c8657be31e8b340defd0ab59466"></a>
void </td><td class="memItemRight" valign="bottom"><b>Init</b> (<a class="el" href="class_u_n_v_scene_capturer_viewpoint_component.html">UNVSceneCapturerViewpointComponent</a> *InOwnerViewpoint)</td></tr>
<tr class="separator:a15361c8657be31e8b340defd0ab59466 inherit pub_methods_class_u_n_v_scene_feature_extractor"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ace6015e5c574c8c54ef304d13f2c82a8 inherit pub_methods_class_u_n_v_scene_feature_extractor"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ace6015e5c574c8c54ef304d13f2c82a8"></a>
bool </td><td class="memItemRight" valign="bottom"><b>IsEnabled</b> () const </td></tr>
<tr class="separator:ace6015e5c574c8c54ef304d13f2c82a8 inherit pub_methods_class_u_n_v_scene_feature_extractor"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pro-methods"></a>
Protected Member Functions</h2></td></tr>
<tr class="memitem:a3c5a8836cb3c1c1b09ffc3383a005d31"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a3c5a8836cb3c1c1b09ffc3383a005d31"></a>
virtual void </td><td class="memItemRight" valign="bottom"><b>UpdateSettings</b> () override</td></tr>
<tr class="separator:a3c5a8836cb3c1c1b09ffc3383a005d31"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="inherit_header pro_methods_class_u_n_v_scene_feature_extractor___pixel_data"><td colspan="2" onclick="javascript:toggleInherit('pro_methods_class_u_n_v_scene_feature_extractor___pixel_data')"><img src="closed.png" alt="-"/> Protected Member Functions inherited from <a class="el" href="class_u_n_v_scene_feature_extractor___pixel_data.html">UNVSceneFeatureExtractor_PixelData</a></td></tr>
<tr class="memitem:af8ff9cd0cd3bfad9ce0259f3e2eb0927 inherit pro_methods_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="af8ff9cd0cd3bfad9ce0259f3e2eb0927"></a>
virtual void </td><td class="memItemRight" valign="bottom"><b>UpdateMaterial</b> ()</td></tr>
<tr class="separator:af8ff9cd0cd3bfad9ce0259f3e2eb0927 inherit pro_methods_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="inherited"></a>
Additional Inherited Members</h2></td></tr>
<tr class="inherit_header pub_types_class_u_n_v_scene_feature_extractor___pixel_data"><td colspan="2" onclick="javascript:toggleInherit('pub_types_class_u_n_v_scene_feature_extractor___pixel_data')"><img src="closed.png" alt="-"/> Public Types inherited from <a class="el" href="class_u_n_v_scene_feature_extractor___pixel_data.html">UNVSceneFeatureExtractor_PixelData</a></td></tr>
<tr class="memitem:a0f21b8ac8c3eeb15148ce22137b4c16c inherit pub_types_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memItemLeft" align="right" valign="top">typedef TFunction< void(const <br class="typebreak" />
<a class="el" href="struct_f_n_v_texture_pixel_data.html">FNVTexturePixelData</a> <br class="typebreak" />
&, <a class="el" href="class_u_n_v_scene_feature_extractor___pixel_data.html">UNVSceneFeatureExtractor_PixelData</a> *)> </td><td class="memItemRight" valign="bottom"><a class="el" href="class_u_n_v_scene_feature_extractor___pixel_data.html#a0f21b8ac8c3eeb15148ce22137b4c16c">OnFinishedCaptureScenePixelsDataCallback</a></td></tr>
<tr class="memdesc:a0f21b8ac8c3eeb15148ce22137b4c16c inherit pub_types_class_u_n_v_scene_feature_extractor___pixel_data"><td class="mdescLeft"> </td><td class="mdescRight">Callback function get called after the scene capture component finished capturing scene and read back its pixels data <a class="el" href="struct_f_n_v_texture_pixel_data.html">FNVTexturePixelData</a> - The struct contain the captured scene's pixels data UNVSceneFeatureExtractor_PixelData* - Reference to the feature extractor that captured the scene pixels data. <a href="#a0f21b8ac8c3eeb15148ce22137b4c16c">More...</a><br /></td></tr>
<tr class="separator:a0f21b8ac8c3eeb15148ce22137b4c16c inherit pub_types_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="inherit_header pub_attribs_class_u_n_v_scene_feature_extractor"><td colspan="2" onclick="javascript:toggleInherit('pub_attribs_class_u_n_v_scene_feature_extractor')"><img src="closed.png" alt="-"/> Public Attributes inherited from <a class="el" href="class_u_n_v_scene_feature_extractor.html">UNVSceneFeatureExtractor</a></td></tr>
<tr class="memitem:a9c320223090611aba5e3cbedb7800478 inherit pub_attribs_class_u_n_v_scene_feature_extractor"><td class="memItemLeft" align="right" valign="top">bool </td><td class="memItemRight" valign="bottom"><a class="el" href="class_u_n_v_scene_feature_extractor.html#a9c320223090611aba5e3cbedb7800478">bIsEnabled</a></td></tr>
<tr class="memdesc:a9c320223090611aba5e3cbedb7800478 inherit pub_attribs_class_u_n_v_scene_feature_extractor"><td class="mdescLeft"> </td><td class="mdescRight">If true, the feature extractor will capture otherwise it won't ToDo: Move to protected. <a href="#a9c320223090611aba5e3cbedb7800478">More...</a><br /></td></tr>
<tr class="separator:a9c320223090611aba5e3cbedb7800478 inherit pub_attribs_class_u_n_v_scene_feature_extractor"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:acc66355107ff790a9672c5a81df6c500 inherit pub_attribs_class_u_n_v_scene_feature_extractor"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="acc66355107ff790a9672c5a81df6c500"></a>
FString </td><td class="memItemRight" valign="bottom"><b>Description</b></td></tr>
<tr class="separator:acc66355107ff790a9672c5a81df6c500 inherit pub_attribs_class_u_n_v_scene_feature_extractor"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ae31575da6433a19027f2f7e498bcf9c5 inherit pub_attribs_class_u_n_v_scene_feature_extractor"><td class="memItemLeft" align="right" valign="top">FString </td><td class="memItemRight" valign="bottom"><a class="el" href="class_u_n_v_scene_feature_extractor.html#ae31575da6433a19027f2f7e498bcf9c5">DisplayName</a></td></tr>
<tr class="memdesc:ae31575da6433a19027f2f7e498bcf9c5 inherit pub_attribs_class_u_n_v_scene_feature_extractor"><td class="mdescLeft"> </td><td class="mdescRight">Name of the feature extractor to show. <a href="#ae31575da6433a19027f2f7e498bcf9c5">More...</a><br /></td></tr>
<tr class="separator:ae31575da6433a19027f2f7e498bcf9c5 inherit pub_attribs_class_u_n_v_scene_feature_extractor"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:abf63eeace4a3fd1d102fa3990dbe7a4b inherit pub_attribs_class_u_n_v_scene_feature_extractor"><td class="memItemLeft" align="right" valign="top">FString </td><td class="memItemRight" valign="bottom"><a class="el" href="class_u_n_v_scene_feature_extractor.html#abf63eeace4a3fd1d102fa3990dbe7a4b">ExportFileNamePostfix</a></td></tr>
<tr class="memdesc:abf63eeace4a3fd1d102fa3990dbe7a4b inherit pub_attribs_class_u_n_v_scene_feature_extractor"><td class="mdescLeft"> </td><td class="mdescRight">The string to add to the end of the exported file's name captured from this feature extractor. e.g: "depth", "mask" ... <a href="#abf63eeace4a3fd1d102fa3990dbe7a4b">More...</a><br /></td></tr>
<tr class="separator:abf63eeace4a3fd1d102fa3990dbe7a4b inherit pub_attribs_class_u_n_v_scene_feature_extractor"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="inherit_header pro_attribs_class_u_n_v_scene_feature_extractor___pixel_data"><td colspan="2" onclick="javascript:toggleInherit('pro_attribs_class_u_n_v_scene_feature_extractor___pixel_data')"><img src="closed.png" alt="-"/> Protected Attributes inherited from <a class="el" href="class_u_n_v_scene_feature_extractor___pixel_data.html">UNVSceneFeatureExtractor_PixelData</a></td></tr>
<tr class="memitem:a52a15fb7558d1fb7d472d0e5a718b8ad inherit pro_attribs_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memItemLeft" align="right" valign="top">bool </td><td class="memItemRight" valign="bottom"><a class="el" href="class_u_n_v_scene_feature_extractor___pixel_data.html#a52a15fb7558d1fb7d472d0e5a718b8ad">bOnlyShowTrainingActors</a></td></tr>
<tr class="memdesc:a52a15fb7558d1fb7d472d0e5a718b8ad inherit pro_attribs_class_u_n_v_scene_feature_extractor___pixel_data"><td class="mdescLeft"> </td><td class="mdescRight">If true, only show the training actors in the exported images. <a href="#a52a15fb7558d1fb7d472d0e5a718b8ad">More...</a><br /></td></tr>
<tr class="separator:a52a15fb7558d1fb7d472d0e5a718b8ad inherit pro_attribs_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a06215d3f5e19b31dd532e63b2e996926 inherit pro_attribs_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memItemLeft" align="right" valign="top">bool </td><td class="memItemRight" valign="bottom"><a class="el" href="class_u_n_v_scene_feature_extractor___pixel_data.html#a06215d3f5e19b31dd532e63b2e996926">bOverrideExportImageType</a></td></tr>
<tr class="memdesc:a06215d3f5e19b31dd532e63b2e996926 inherit pro_attribs_class_u_n_v_scene_feature_extractor___pixel_data"><td class="mdescLeft"> </td><td class="mdescRight">If true, this feature extractors have its own exported image type and doesn't use the owner capturer's image type. <a href="#a06215d3f5e19b31dd532e63b2e996926">More...</a><br /></td></tr>
<tr class="separator:a06215d3f5e19b31dd532e63b2e996926 inherit pro_attribs_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ad9b4d65df5ced77a32890fb813c68700 inherit pro_attribs_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ad9b4d65df5ced77a32890fb813c68700"></a>
bool </td><td class="memItemRight" valign="bottom"><b>bOverrideShowFlagSettings</b></td></tr>
<tr class="separator:ad9b4d65df5ced77a32890fb813c68700 inherit pro_attribs_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:af77f235e3ac7107a3156872b6228f0cc inherit pro_attribs_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="af77f235e3ac7107a3156872b6228f0cc"></a>
bool </td><td class="memItemRight" valign="bottom"><b>bUpdateContinuously</b></td></tr>
<tr class="separator:af77f235e3ac7107a3156872b6228f0cc inherit pro_attribs_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a0fd105ec49be8e1a7f98067b4e19d10f inherit pro_attribs_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a0fd105ec49be8e1a7f98067b4e19d10f"></a>
TEnumAsByte<br class="typebreak" />
< ENVCapturedPixelFormat > </td><td class="memItemRight" valign="bottom"><b>CapturedPixelFormat</b></td></tr>
<tr class="separator:a0fd105ec49be8e1a7f98067b4e19d10f inherit pro_attribs_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:aeae3411d1242a69a7098f38113818563 inherit pro_attribs_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="aeae3411d1242a69a7098f38113818563"></a>
TEnumAsByte< enum <br class="typebreak" />
ESceneCaptureSource > </td><td class="memItemRight" valign="bottom"><b>CaptureSource</b></td></tr>
<tr class="separator:aeae3411d1242a69a7098f38113818563 inherit pro_attribs_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a73f8fad9d7c455d69f11e0327c4234f2 inherit pro_attribs_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a73f8fad9d7c455d69f11e0327c4234f2"></a>
ENVImageFormat </td><td class="memItemRight" valign="bottom"><b>ExportImageFormat</b></td></tr>
<tr class="separator:a73f8fad9d7c455d69f11e0327c4234f2 inherit pro_attribs_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a18c8329bb5036fbef1dae6ccfccd2678 inherit pro_attribs_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memItemLeft" align="right" valign="top">TArray< AActor * > </td><td class="memItemRight" valign="bottom"><a class="el" href="class_u_n_v_scene_feature_extractor___pixel_data.html#a18c8329bb5036fbef1dae6ccfccd2678">IgnoreActors</a></td></tr>
<tr class="memdesc:a18c8329bb5036fbef1dae6ccfccd2678 inherit pro_attribs_class_u_n_v_scene_feature_extractor___pixel_data"><td class="mdescLeft"> </td><td class="mdescRight">List of actors to ignore when capturing image. <a href="#a18c8329bb5036fbef1dae6ccfccd2678">More...</a><br /></td></tr>
<tr class="separator:a18c8329bb5036fbef1dae6ccfccd2678 inherit pro_attribs_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a27d526d241f6ee25a2ce385d30093395 inherit pro_attribs_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memItemLeft" align="right" valign="top">TArray< struct <br class="typebreak" />
FEngineShowFlagsSetting > </td><td class="memItemRight" valign="bottom"><a class="el" href="class_u_n_v_scene_feature_extractor___pixel_data.html#a27d526d241f6ee25a2ce385d30093395">OverrideShowFlagSettings</a></td></tr>
<tr class="memdesc:a27d526d241f6ee25a2ce385d30093395 inherit pro_attribs_class_u_n_v_scene_feature_extractor___pixel_data"><td class="mdescLeft"> </td><td class="mdescRight">ShowFlags for the SceneCapture's ViewFamily, to control rendering settings for this view. Hidden but accessible through details customization. <a href="#a27d526d241f6ee25a2ce385d30093395">More...</a><br /></td></tr>
<tr class="separator:a27d526d241f6ee25a2ce385d30093395 inherit pro_attribs_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a57ead57cd0443ecc2847fc6f76bcfcb1 inherit pro_attribs_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a57ead57cd0443ecc2847fc6f76bcfcb1"></a>
TEnumAsByte< EPixelFormat > </td><td class="memItemRight" valign="bottom"><b>OverrideTexturePixelFormat</b></td></tr>
<tr class="separator:a57ead57cd0443ecc2847fc6f76bcfcb1 inherit pro_attribs_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:aa901dd737663a18b73d3ad02cc52eaa3 inherit pro_attribs_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="aa901dd737663a18b73d3ad02cc52eaa3"></a>
float </td><td class="memItemRight" valign="bottom"><b>PostProcessBlendWeight</b></td></tr>
<tr class="separator:aa901dd737663a18b73d3ad02cc52eaa3 inherit pro_attribs_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a13e900a98b5c082d9881d7f80d43e8bb inherit pro_attribs_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a13e900a98b5c082d9881d7f80d43e8bb"></a>
class UMaterialInterface * </td><td class="memItemRight" valign="bottom"><b>PostProcessMaterial</b></td></tr>
<tr class="separator:a13e900a98b5c082d9881d7f80d43e8bb inherit pro_attribs_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a78a3bc1244715e190ba462d518414133 inherit pro_attribs_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a78a3bc1244715e190ba462d518414133"></a>
class UMaterialInstanceDynamic * </td><td class="memItemRight" valign="bottom"><b>PostProcessMaterialInstance</b></td></tr>
<tr class="separator:a78a3bc1244715e190ba462d518414133 inherit pro_attribs_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ac4183f9641abbcfe88749534972f7870 inherit pro_attribs_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ac4183f9641abbcfe88749534972f7870"></a>
TArray<br class="typebreak" />
< <a class="el" href="struct_f_n_v_scene_capture_component_data.html">FNVSceneCaptureComponentData</a> > </td><td class="memItemRight" valign="bottom"><b>SceneCaptureComp2DDataList</b></td></tr>
<tr class="separator:ac4183f9641abbcfe88749534972f7870 inherit pro_attribs_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a8bfd2b8a225206b5c9f713aa89389702 inherit pro_attribs_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a8bfd2b8a225206b5c9f713aa89389702"></a>
<a class="el" href="class_u_n_v_scene_capture_component2_d.html">UNVSceneCaptureComponent2D</a> * </td><td class="memItemRight" valign="bottom"><b>SceneCaptureComponent</b></td></tr>
<tr class="separator:a8bfd2b8a225206b5c9f713aa89389702 inherit pro_attribs_class_u_n_v_scene_feature_extractor___pixel_data"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="inherit_header pro_attribs_class_u_n_v_scene_feature_extractor"><td colspan="2" onclick="javascript:toggleInherit('pro_attribs_class_u_n_v_scene_feature_extractor')"><img src="closed.png" alt="-"/> Protected Attributes inherited from <a class="el" href="class_u_n_v_scene_feature_extractor.html">UNVSceneFeatureExtractor</a></td></tr>
<tr class="memitem:aadcb3df816489934be1c5f82b58d19bd inherit pro_attribs_class_u_n_v_scene_feature_extractor"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="aadcb3df816489934be1c5f82b58d19bd"></a>
bool </td><td class="memItemRight" valign="bottom"><b>bCapturing</b></td></tr>
<tr class="separator:aadcb3df816489934be1c5f82b58d19bd inherit pro_attribs_class_u_n_v_scene_feature_extractor"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a9f8936d8a98240b881ce447ffd233c8b inherit pro_attribs_class_u_n_v_scene_feature_extractor"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a9f8936d8a98240b881ce447ffd233c8b"></a>
<a class="el" href="class_a_n_v_scene_capturer_actor.html">ANVSceneCapturerActor</a> * </td><td class="memItemRight" valign="bottom"><b>OwnerCapturer</b></td></tr>
<tr class="separator:a9f8936d8a98240b881ce447ffd233c8b inherit pro_attribs_class_u_n_v_scene_feature_extractor"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a6000e0c959cc3a7092e5c7d8007d4fd5 inherit pro_attribs_class_u_n_v_scene_feature_extractor"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a6000e0c959cc3a7092e5c7d8007d4fd5"></a>
<a class="el" href="class_u_n_v_scene_capturer_viewpoint_component.html">UNVSceneCapturerViewpointComponent</a> * </td><td class="memItemRight" valign="bottom"><b>OwnerViewpoint</b></td></tr>
<tr class="separator:a6000e0c959cc3a7092e5c7d8007d4fd5 inherit pro_attribs_class_u_n_v_scene_feature_extractor"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2>
<div class="textblock">
<p>Definition at line <a class="el" href="_n_v_scene_feature_extractor___image_export_8h_source.html#l00125">125</a> of file <a class="el" href="_n_v_scene_feature_extractor___image_export_8h_source.html">NVSceneFeatureExtractor_ImageExport.h</a>.</p>
</div><hr/>The documentation for this class was generated from the following file:<ul>
<li><a class="el" href="_n_v_scene_feature_extractor___image_export_8h_source.html">NVSceneFeatureExtractor_ImageExport.h</a></li>
</ul>
</div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="navelem"><a class="el" href="class_u_n_v_scene_feature_extractor___scene_pixel_velocity.html">UNVSceneFeatureExtractor_ScenePixelVelocity</a></li>
<li class="footer">Generated on Wed Dec 5 2018 15:01:39 for NVIDIA DeepLearning Dataset Synthesizer (NDDS) by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.8 </li>
</ul>
</div>
</body>
</html>
| {
"pile_set_name": "Github"
} |
/* ----------------------------------------------------------------------------
* ergoDOX : controller : Teensy 2.0 specific exports : functions
* ----------------------------------------------------------------------------
* Copyright (c) 2012 Ben Blazak <[email protected]>
* Released under The MIT License (MIT) (see "license.md")
* Project located at <https://github.com/benblazak/ergodox-firmware>
* ------------------------------------------------------------------------- */
#ifndef KEYBOARD__ERGODOX__CONTROLLER__TEENSY_2_0__FUNCTIONS_h
#define KEYBOARD__ERGODOX__CONTROLLER__TEENSY_2_0__FUNCTIONS_h
#include <stdbool.h>
#include <stdint.h>
#include "../matrix.h"
// --------------------------------------------------------------------
uint8_t teensy_init(void);
uint8_t teensy_update_matrix( bool matrix[KB_ROWS][KB_COLUMNS] );
#endif
| {
"pile_set_name": "Github"
} |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: Templates\CSharp\Requests\IEntityCollectionRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The interface IDeviceCompliancePolicyDeviceStatusesCollectionRequest.
/// </summary>
public partial interface IDeviceCompliancePolicyDeviceStatusesCollectionRequest : IBaseRequest
{
/// <summary>
/// Adds the specified DeviceComplianceDeviceStatus to the collection via POST.
/// </summary>
/// <param name="deviceComplianceDeviceStatus">The DeviceComplianceDeviceStatus to add.</param>
/// <returns>The created DeviceComplianceDeviceStatus.</returns>
System.Threading.Tasks.Task<DeviceComplianceDeviceStatus> AddAsync(DeviceComplianceDeviceStatus deviceComplianceDeviceStatus);
/// <summary>
/// Adds the specified DeviceComplianceDeviceStatus to the collection via POST.
/// </summary>
/// <param name="deviceComplianceDeviceStatus">The DeviceComplianceDeviceStatus to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created DeviceComplianceDeviceStatus.</returns>
System.Threading.Tasks.Task<DeviceComplianceDeviceStatus> AddAsync(DeviceComplianceDeviceStatus deviceComplianceDeviceStatus, CancellationToken cancellationToken);
/// <summary>
/// Gets the collection page.
/// </summary>
/// <returns>The collection page.</returns>
System.Threading.Tasks.Task<IDeviceCompliancePolicyDeviceStatusesCollectionPage> GetAsync();
/// <summary>
/// Gets the collection page.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The collection page.</returns>
System.Threading.Tasks.Task<IDeviceCompliancePolicyDeviceStatusesCollectionPage> GetAsync(CancellationToken cancellationToken);
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
IDeviceCompliancePolicyDeviceStatusesCollectionRequest Expand(string value);
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
IDeviceCompliancePolicyDeviceStatusesCollectionRequest Expand(Expression<Func<DeviceComplianceDeviceStatus, object>> expandExpression);
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
IDeviceCompliancePolicyDeviceStatusesCollectionRequest Select(string value);
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
IDeviceCompliancePolicyDeviceStatusesCollectionRequest Select(Expression<Func<DeviceComplianceDeviceStatus, object>> selectExpression);
/// <summary>
/// Adds the specified top value to the request.
/// </summary>
/// <param name="value">The top value.</param>
/// <returns>The request object to send.</returns>
IDeviceCompliancePolicyDeviceStatusesCollectionRequest Top(int value);
/// <summary>
/// Adds the specified filter value to the request.
/// </summary>
/// <param name="value">The filter value.</param>
/// <returns>The request object to send.</returns>
IDeviceCompliancePolicyDeviceStatusesCollectionRequest Filter(string value);
/// <summary>
/// Adds the specified skip value to the request.
/// </summary>
/// <param name="value">The skip value.</param>
/// <returns>The request object to send.</returns>
IDeviceCompliancePolicyDeviceStatusesCollectionRequest Skip(int value);
/// <summary>
/// Adds the specified orderby value to the request.
/// </summary>
/// <param name="value">The orderby value.</param>
/// <returns>The request object to send.</returns>
IDeviceCompliancePolicyDeviceStatusesCollectionRequest OrderBy(string value);
}
}
| {
"pile_set_name": "Github"
} |
<script>
import { onMount } from 'svelte';
import { fly } from 'svelte/transition';
import { notification } from '../stores';
import GridContainer from './GridContainer.svelte';
import GridRow from './GridRow.svelte';
export let alert;
onMount(() => {
setTimeout(() => { notification.clear(); }, 2000);
});
</script>
<div
transition:fly={{ y: 100, duration: 750 }}
class="position-fixed mobile-lg:margin-top-2 tablet:margin-top-4
width-full z-top">
<GridContainer>
<GridRow>
<div
class="grid-row usa-alert usa-alert--{alert.type}
usa-alert--slim width-full flex-row shadow-4">
<div class="grid-col flex-fill usa-alert__body">
<p class="usa-alert__text">{alert.message}</p>
</div>
<div class="grid-col flex-auto">
<button
class="usa-button usa-button--outline"
on:click|preventDefault={notification.clear}>
Close
</button>
</div>
</div>
</GridRow>
</GridContainer>
</div> | {
"pile_set_name": "Github"
} |
/*!
* Connect - query
* Copyright(c) 2011 TJ Holowaychuk
* Copyright(c) 2011 Sencha Inc.
* MIT Licensed
*/
/**
* Module dependencies.
*/
var qs = require('qs')
, parse = require('../utils').parseUrl;
/**
* Query:
*
* Automatically parse the query-string when available,
* populating the `req.query` object.
*
* Examples:
*
* connect()
* .use(connect.query())
* .use(function(req, res){
* res.end(JSON.stringify(req.query));
* });
*
* The `options` passed are provided to qs.parse function.
*
* @param {Object} options
* @return {Function}
* @api public
*/
module.exports = function query(options){
return function query(req, res, next){
if (!req.query) {
req.query = ~req.url.indexOf('?')
? qs.parse(parse(req).query, options)
: {};
}
next();
};
};
| {
"pile_set_name": "Github"
} |
// Copyright 2014 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.
'use strict';
/**
* Fake task.
*
* @param {boolean} isDefault Whether the task is default or not.
* @param {string} taskId Task ID.
* @param {string} title Title of the task.
* @param {boolean=} opt_isGenericFileHandler Whether the task is a generic
* file handler.
* @constructor
*/
function FakeTask(isDefault, taskId, title, opt_isGenericFileHandler) {
this.driveApp = false;
this.iconUrl = 'chrome://theme/IDR_DEFAULT_FAVICON'; // Dummy icon
this.isDefault = isDefault;
this.taskId = taskId;
this.title = title;
this.isGenericFileHandler = opt_isGenericFileHandler || false;
Object.freeze(this);
}
/**
* Fake tasks for a local volume.
*
* @type {Array<FakeTask>}
* @const
*/
var DOWNLOADS_FAKE_TASKS = [
new FakeTask(true, 'dummytaskid|open-with', 'DummyTask1'),
new FakeTask(false, 'dummytaskid-2|open-with', 'DummyTask2')
];
/**
* Fake tasks for a drive volume.
*
* @type {Array<FakeTask>}
* @const
*/
var DRIVE_FAKE_TASKS = [
new FakeTask(true, 'dummytaskid|drive|open-with', 'DummyTask1'),
new FakeTask(false, 'dummytaskid-2|drive|open-with', 'DummyTask2')
];
/**
* Sets up task tests.
*
* @param {string} rootPath Root path.
* @param {Array<FakeTask>} fakeTasks Fake tasks.
*/
function setupTaskTest(rootPath, fakeTasks) {
return setupAndWaitUntilReady(null, rootPath).then(function(results) {
return remoteCall.callRemoteTestUtil(
'overrideTasks',
results.windowId,
[fakeTasks]).then(function() {
return results.windowId;
});
});
}
/**
* Tests executing the default task when there is only one task.
*
* @param {string} expectedTaskId Task ID expected to execute.
* @param {string} windowId Window ID.
*/
function executeDefaultTask(expectedTaskId, windowId) {
// Select file.
var selectFilePromise =
remoteCall.callRemoteTestUtil('selectFile', windowId, ['hello.txt']);
// Double-click the file.
var doubleClickPromise = selectFilePromise.then(function(result) {
chrome.test.assertTrue(result);
return remoteCall.callRemoteTestUtil(
'fakeMouseDoubleClick',
windowId,
['#file-list li.table-row[selected] .filename-label span']);
});
// Wait until the task is executed.
return doubleClickPromise.then(function(result) {
chrome.test.assertTrue(!!result);
return remoteCall.waitUntilTaskExecutes(windowId, expectedTaskId);
});
}
/**
* Tests to specify default task via the default task dialog.
*
* @param {string} expectedTaskId Task ID to be expected to newly specify as
* default.
* @param {string} windowId Window ID.
* @return {Promise} Promise to be fulfilled/rejected depends on the test
* result.
*/
function defaultTaskDialog(expectedTaskId, windowId) {
// Prepare expected labels.
var expectedLabels = [
'DummyTask1 (default)',
'DummyTask2'
];
// Select file.
var selectFilePromise =
remoteCall.callRemoteTestUtil('selectFile', windowId, ['hello.txt']);
// Click the change default menu.
var menuClickedPromise = selectFilePromise.
then(function() {
return remoteCall.waitForElement(windowId, '#tasks[multiple]');
}).
then(function() {
return remoteCall.waitForElement(
windowId, '#tasks-menu .change-default');
}).
then(function() {
return remoteCall.callRemoteTestUtil(
'fakeEvent', windowId, ['#tasks', 'select', {
item: {type: 'ChangeDefaultTask'}
}]);
}).
then(function(result) {
chrome.test.assertTrue(result);
});
// Wait for the list of menu item is added as expected.
var menuPreparedPromise = menuClickedPromise.then(function() {
return repeatUntil(function() {
// Obtains menu items.
var menuItemsPromise = remoteCall.callRemoteTestUtil(
'queryAllElements',
windowId,
['#default-task-dialog #default-tasks-list li']);
// Compare the contents of items.
return menuItemsPromise.then(function(items) {
var actualLabels = items.map(function(item) { return item.text; });
if (chrome.test.checkDeepEq(expectedLabels, actualLabels)) {
return true;
} else {
return pending('Tasks do not match, expected: %j, actual: %j.',
expectedLabels,
actualLabels);
}
});
});
});
// Click the non default item.
var itemClickedPromise = menuPreparedPromise.
then(function() {
return remoteCall.callRemoteTestUtil(
'fakeEvent',
windowId,
[
'#default-task-dialog #default-tasks-list li:nth-of-type(2)',
'mousedown',
{bubbles: true, button: 0}
]);
}).
then(function() {
return remoteCall.callRemoteTestUtil(
'fakeEvent',
windowId,
[
'#default-task-dialog #default-tasks-list li:nth-of-type(2)',
'click',
{bubbles: true}
]);
}).
then(function(result) {
chrome.test.assertTrue(result);
});
// Wait for the dialog hidden, and the task is executed.
var dialogHiddenPromise = itemClickedPromise.then(function() {
return remoteCall.waitForElementLost(
windowId, '#default-task-dialog', null);
});
// Execute the new default task.
var taskButtonClicked = dialogHiddenPromise.
then(function() {
return remoteCall.callRemoteTestUtil(
'fakeEvent', windowId, ['#tasks', 'click']);
}).
then(function(result) {
chrome.test.assertTrue(result);
});
// Check the executed tasks.
return dialogHiddenPromise.then(function() {
return remoteCall.waitUntilTaskExecutes(windowId, expectedTaskId);
});
}
testcase.executeDefaultTaskOnDrive = function() {
testPromise(setupTaskTest(RootPath.DRIVE, DRIVE_FAKE_TASKS).then(
executeDefaultTask.bind(null, 'dummytaskid|drive|open-with')));
};
testcase.executeDefaultTaskOnDownloads = function() {
testPromise(setupTaskTest(RootPath.DOWNLOADS, DOWNLOADS_FAKE_TASKS).then(
executeDefaultTask.bind(null, 'dummytaskid|open-with')));
};
testcase.defaultTaskDialogOnDrive = function() {
testPromise(setupTaskTest(RootPath.DRIVE, DRIVE_FAKE_TASKS).then(
defaultTaskDialog.bind(null, 'dummytaskid-2|drive|open-with')));
};
testcase.defaultTaskDialogOnDownloads = function() {
testPromise(setupTaskTest(RootPath.DOWNLOADS, DOWNLOADS_FAKE_TASKS).then(
defaultTaskDialog.bind(null, 'dummytaskid-2|open-with')));
};
testcase.genericTaskIsNotExecuted = function() {
var tasks = [
new FakeTask(false, 'dummytaskid|open-with', 'DummyTask1',
true /* isGenericFileHandler */),
new FakeTask(false, 'dummytaskid-2|open-with', 'DummyTask2',
true /* isGenericFileHandler */)
];
// When default task is not set, executeDefaultInternal_ in file_tasks.js
// tries to show it in a browser tab. By checking the view-in-browser task is
// executed, we check that default task is not set in this situation.
//
// See: src/ui/file_manager/file_manager/foreground/js/file_tasks.js&l=404
testPromise(setupTaskTest(RootPath.DOWNLOADS, tasks)
.then(function(windowId) {
return executeDefaultTask(
FILE_MANAGER_EXTENSIONS_ID + '|file|view-in-browser',
windowId);
}));
};
testcase.genericAndNonGenericTasksAreMixed = function() {
var tasks = [
new FakeTask(false, 'dummytaskid|open-with', 'DummyTask1',
true /* isGenericFileHandler */),
new FakeTask(false, 'dummytaskid-2|open-with', 'DummyTask2',
false /* isGenericFileHandler */),
new FakeTask(false, 'dummytaskid-3|open-with', 'DummyTask3',
true /* isGenericFileHandler */)
];
testPromise(setupTaskTest(RootPath.DOWNLOADS, tasks).then(
executeDefaultTask.bind(null, 'dummytaskid-2|open-with')));
}
| {
"pile_set_name": "Github"
} |
using System;
using System.IO;
using System.Collections.Generic;
using EQExtractor2.InternalTypes;
using EQExtractor2.OpCodes;
using EQPacket;
using MyUtils;
namespace EQExtractor2.Patches
{
public enum IdentificationStatus { No, Tentative, Yes };
class PatchSpecficDecoder
{
protected class PacketToMatch
{
public String OPCodeName;
public PacketDirection Direction;
public Int32 RequiredSize;
public bool VersionMatched;
};
public PatchSpecficDecoder()
{
Version = "Unsupported Client Version";
ExpectedPPLength = 0;
PPZoneIDOffset = 0;
PatchConfFileName = "";
IDStatus = IdentificationStatus.No;
SupportsSQLGeneration = true;
}
public string GetVersion()
{
return Version;
}
virtual public bool UnsupportedVersion()
{
return ExpectedPPLength == 0;
}
virtual public bool Init(string ConfDirectory, ref string ErrorMessage)
{
OpManager = new OpCodeManager();
return false;
}
virtual public IdentificationStatus Identify(int OpCode, int Size, PacketDirection Direction)
{
return IdentificationStatus.No;
}
virtual public List<Door> GetDoors()
{
List<Door> DoorList = new List<Door>();
return DoorList;
}
virtual public UInt16 GetZoneNumber()
{
return 0;
}
virtual public int VerifyPlayerProfile()
{
return 0;
}
virtual public MerchantManager GetMerchantData(NPCSpawnList NPCSL)
{
return null;
}
virtual public Item DecodeItemPacket(byte[] PacketBuffer)
{
Item NewItem = new Item();
return NewItem;
}
virtual public List<ZonePoint> GetZonePointList()
{
List<ZonePoint> ZonePointList = new List<ZonePoint>();
return ZonePointList;
}
virtual public NewZoneStruct GetZoneData()
{
NewZoneStruct NewZone = new NewZoneStruct();
return NewZone;
}
virtual public List<ZoneEntryStruct> GetSpawns()
{
List<ZoneEntryStruct> ZoneSpawns = new List<ZoneEntryStruct>();
return ZoneSpawns;
}
virtual public List<PositionUpdate> GetHighResolutionMovementUpdates()
{
List<PositionUpdate> Updates = new List<PositionUpdate>();
return Updates;
}
virtual public List<PositionUpdate> GetLowResolutionMovementUpdates()
{
List<PositionUpdate> Updates = new List<PositionUpdate>();
return Updates;
}
virtual public List<PositionUpdate> GetAllMovementUpdates()
{
List<PositionUpdate> Updates = new List<PositionUpdate>();
return Updates;
}
virtual public PositionUpdate Decode_OP_NPCMoveUpdate(byte[] UpdatePacket)
{
PositionUpdate PosUpdate = new PositionUpdate();
return PosUpdate;
}
virtual public PositionUpdate Decode_OP_MobUpdate(byte[] MobUpdatePacket)
{
PositionUpdate PosUpdate = new PositionUpdate();
return PosUpdate;
}
virtual public List<PositionUpdate> GetClientMovementUpdates()
{
List<PositionUpdate> Updates = new List<PositionUpdate>();
return Updates;
}
virtual public List<GroundSpawnStruct> GetGroundSpawns()
{
List<GroundSpawnStruct> GroundSpawns = new List<GroundSpawnStruct>();
return GroundSpawns;
}
virtual public List<UInt32> GetFindableSpawns()
{
List<UInt32> FindableSpawnList = new List<UInt32>();
return FindableSpawnList;
}
virtual public string GetZoneName()
{
return "";
}
virtual public bool DumpAAs(string FileName)
{
return false;
}
public void GivePackets(PacketManager pm)
{
Packets = pm;
}
virtual public void RegisterExplorers()
{
}
public List<byte[]> GetPacketsOfType(string OpCodeName, PacketDirection Direction)
{
List<byte[]> ReturnList = new List<byte[]>();
if (OpManager == null)
return ReturnList;
UInt32 OpCodeNumber = OpManager.OpCodeNameToNumber(OpCodeName);
foreach (EQApplicationPacket app in Packets.PacketList)
{
if ((app.OpCode == OpCodeNumber) && (app.Direction == Direction) && (app.Locked))
ReturnList.Add(app.Buffer);
}
return ReturnList;
}
public DateTime GetCaptureStartTime()
{
if (Packets.PacketList.Count > 0)
{
return Packets.PacketList[0].PacketTime;
}
return DateTime.MinValue;
}
public bool DumpPackets(string FileName, bool ShowTimeStamps)
{
StreamWriter PacketDumpStream;
try
{
PacketDumpStream = new StreamWriter(FileName);
}
catch
{
return false;
}
string Direction = "";
foreach (EQApplicationPacket p in Packets.PacketList)
{
if(ShowTimeStamps)
PacketDumpStream.WriteLine(p.PacketTime.ToString());
if (p.Direction == PacketDirection.ServerToClient)
Direction = "[Server->Client]";
else
Direction = "[Client->Server]";
OpCode oc = OpManager.GetOpCodeByNumber(p.OpCode);
string OpCodeName = (oc != null) ? oc.Name : "OP_Unknown";
PacketDumpStream.WriteLine("[OPCode: 0x" + p.OpCode.ToString("x4") + "] " + OpCodeName + " " + Direction + " [Size: " + p.Buffer.Length + "]");
PacketDumpStream.WriteLine(Utils.HexDump(p.Buffer));
if ((oc != null) && (oc.Explorer != null))
oc.Explorer(PacketDumpStream, new ByteStream(p.Buffer), p.Direction);
}
PacketDumpStream.Close();
return true;
}
public int PacketTypeCountByName(string OPCodeName)
{
UInt32 OpCodeNumber = OpManager.OpCodeNameToNumber(OPCodeName);
int Count = 0;
foreach (EQApplicationPacket app in Packets.PacketList)
{
if (app.OpCode == OpCodeNumber)
++Count;
}
return Count;
}
protected void AddExplorerSpawn(UInt32 ID, string Name)
{
ExplorerSpawnRecord e = new ExplorerSpawnRecord(ID, Name);
ExplorerSpawns.Add(e);
}
protected string FindExplorerSpawn(UInt32 ID)
{
foreach(ExplorerSpawnRecord s in ExplorerSpawns)
{
if (s.ID == ID)
return s.Name;
}
return "";
}
protected PacketManager Packets;
public OpCodeManager OpManager;
protected string Version;
protected int ExpectedPPLength;
protected int PPZoneIDOffset;
protected string PatchConfFileName;
protected PacketToMatch[] PacketsToMatch;
protected UInt32 WaitingForPacket;
protected IdentificationStatus IDStatus;
private List<ExplorerSpawnRecord> ExplorerSpawns = new List<ExplorerSpawnRecord>();
public bool SupportsSQLGeneration;
}
}
| {
"pile_set_name": "Github"
} |
package com.rafsan.inventory.controller.sales;
import com.rafsan.inventory.entity.Sale;
import com.rafsan.inventory.interfaces.SaleInterface;
import com.rafsan.inventory.model.SalesModel;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.animation.TranslateTransition;
import javafx.beans.binding.Bindings;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.Image;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.util.Duration;
public class SalesController implements Initializable, SaleInterface {
@FXML
private TableView<Sale> salesTable;
@FXML
private TableColumn<Sale, Long> idColumn;
@FXML
private TableColumn<Sale, String> productColumn, dateColumn;
@FXML
private TableColumn<Sale, Double> quantityColumn, priceColumn, totalColumn;
@FXML
private TextField searchField;
@FXML
private Button deleteButton;
private SalesModel model;
private double xOffset = 0;
private double yOffset = 0;
@FXML
private Button menu;
@FXML
private VBox drawer;
@Override
public void initialize(URL location, ResourceBundle resources) {
model = new SalesModel();
drawerAction();
loadData();
idColumn.setCellValueFactory(new PropertyValueFactory<>("id"));
productColumn.setCellValueFactory((TableColumn.CellDataFeatures<Sale, String> p) ->
new SimpleStringProperty(p.getValue().getProduct().getProductName()));
quantityColumn.setCellValueFactory(new PropertyValueFactory<>("quantity"));
priceColumn.setCellValueFactory(new PropertyValueFactory<>("price"));
totalColumn.setCellValueFactory(new PropertyValueFactory<>("total"));
dateColumn.setCellValueFactory(new PropertyValueFactory<>("date"));
salesTable.setItems(SALELIST);
filterData();
deleteButton
.disableProperty()
.bind(Bindings.isEmpty(salesTable.getSelectionModel().getSelectedItems()));
}
private void filterData() {
FilteredList<Sale> searchedData = new FilteredList<>(SALELIST, e -> true);
searchField.setOnKeyReleased(e -> {
searchField.textProperty().addListener((observable, oldValue, newValue) -> {
searchedData.setPredicate(sale -> {
if (newValue == null || newValue.isEmpty()) {
return true;
}
String lowerCaseFilter = newValue.toLowerCase();
if (sale.getProduct().getProductName().toLowerCase().contains(lowerCaseFilter)) {
return true;
} else if (sale.getProduct().getCategory().getType().toLowerCase().contains(lowerCaseFilter)) {
return true;
}
return false;
});
});
SortedList<Sale> sortedData = new SortedList<>(searchedData);
sortedData.comparatorProperty().bind(salesTable.comparatorProperty());
salesTable.setItems(sortedData);
});
}
private void loadData(){
if (!SALELIST.isEmpty()) {
SALELIST.clear();
}
SALELIST.addAll(model.getSales());
}
private void drawerAction() {
TranslateTransition openNav = new TranslateTransition(new Duration(350), drawer);
openNav.setToX(0);
TranslateTransition closeNav = new TranslateTransition(new Duration(350), drawer);
menu.setOnAction((ActionEvent evt) -> {
if (drawer.getTranslateX() != 0) {
openNav.play();
menu.getStyleClass().remove("hamburger-button");
menu.getStyleClass().add("open-menu");
} else {
closeNav.setToX(-(drawer.getWidth()));
closeNav.play();
menu.getStyleClass().remove("open-menu");
menu.getStyleClass().add("hamburger-button");
}
});
}
@FXML
public void adminAction(ActionEvent event) throws Exception {
windows("/fxml/Admin.fxml", "Admin", event);
}
@FXML
public void productAction(ActionEvent event) throws Exception {
windows("/fxml/Product.fxml", "Product", event);
}
@FXML
public void categoryAction(ActionEvent event) throws Exception {
windows("/fxml/Category.fxml", "Category", event);
}
@FXML
public void purchaseAction(ActionEvent event) throws Exception {
windows("/fxml/Purchase.fxml", "Purchase", event);
}
@FXML
public void reportAction(ActionEvent event) throws Exception {
windows("/fxml/Report.fxml", "Report", event);
}
@FXML
public void supplierAction(ActionEvent event) throws Exception {
windows("/fxml/Supplier.fxml", "Supplier", event);
}
@FXML
public void staffAction(ActionEvent event) throws Exception {
windows("/fxml/Employee.fxml", "Employee", event);
}
@FXML
public void logoutAction(ActionEvent event) throws Exception {
((Node) (event.getSource())).getScene().getWindow().hide();
Parent root = FXMLLoader.load(getClass().getResource("/fxml/Login.fxml"));
Stage stage = new Stage();
root.setOnMousePressed((MouseEvent e) -> {
xOffset = e.getSceneX();
yOffset = e.getSceneY();
});
root.setOnMouseDragged((MouseEvent e) -> {
stage.setX(e.getScreenX() - xOffset);
stage.setY(e.getScreenY() - yOffset);
});
Scene scene = new Scene(root);
stage.setTitle("Inventory:: Version 1.0");
stage.getIcons().add(new Image("/images/logo.png"));
stage.initStyle(StageStyle.UNDECORATED);
stage.setScene(scene);
stage.show();
}
private void windows(String path, String title, ActionEvent event) throws Exception {
double width = ((Node) event.getSource()).getScene().getWidth();
double height = ((Node) event.getSource()).getScene().getHeight();
Parent root = FXMLLoader.load(getClass().getResource(path));
Scene scene = new Scene(root, width, height);
Stage stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
stage.setTitle(title);
stage.getIcons().add(new Image("/images/logo.png"));
stage.setScene(scene);
stage.show();
}
@FXML
public void deleteAction(ActionEvent event) throws Exception {
}
}
| {
"pile_set_name": "Github"
} |
// aggregations/bucket/terms-aggregation.asciidoc:748
[source, python]
----
resp = client.search(
body={
"aggs": {"tags": {"terms": {"field": "tags", "missing": "N/A"}}}
},
)
print(resp)
---- | {
"pile_set_name": "Github"
} |
(function () {
'use strict';
var directive = function () {
var htmlTemplate="<nav ng-show='pageInfo.totalPages>0&&pageInfo.showPages>0'><ul class='pagination'><li><a href='javascript:void(0)' ng-click='prePages()' ng-show='showPrePageBtn'>«</a></li>"+
"<li ng-repeat='p in currentPages' ng-class='activeClass(p.index)'><a href='javascript:void(0)' ng-click='goPage(p.index)'>{{p.index}}</a></li>"+
"<li><a href='javascript:void(0)' ng-click='nextPages()' ng-show='showNextPageBtn'>»</a></li></ul></nav>";
return {
restrict: 'EA',
scope: {
pageInfo: '=',
onChange:'&'
},
template: htmlTemplate,
link: function (scope, element, attrs) {
scope.showPrePageBtn=false;
scope.showNextPageBtn=false;
scope.currentPages=[];
scope.pageInfo.showPages = scope.pageInfo.showPages?scope.pageInfo.showPages:5;
scope.pageInfo.pageIndex = scope.pageInfo.pageIndex?scope.pageInfo.pageIndex:1;
scope.pageInfo.totalPages= scope.pageInfo.totalPages?scope.pageInfo.totalPages:0;
scope.$watch('pageInfo.totalPages',function(newValue,oldValue){
if(newValue&&newValue!=oldValue){
// if totalPages changed to rebuild the directive
build();
}
});
scope.$watch('pageInfo.showPages',function(newValue,oldValue){
if(newValue&&newValue!=oldValue){
// if showPages changed to rebuild the directive
build();
}
});
scope.$watch('pageInfo.pageIndex',function(newValue,oldValue){
if(newValue&&newValue!=oldValue){
// if pageIndex changed to rebuild the directive
for(var i in scope.currentPages){
var index = scope.currentPages[i].index;
if(index === scope.pageInfo.pageIndex ){
//if pageIndex in showing pages not rebuild.
return;
}
}
build();
}
});
var setPrepageOrNextpageBtnStatus=function(){
if( scope.currentPages.length>0){
scope.showPrePageBtn = !(scope.currentPages[0].index === 1);
scope.showNextPageBtn = !(scope.currentPages[scope.currentPages.length-1].index === scope.pageInfo.totalPages);
}
}
var build=function(){
console.log('build ngbootstrappagebar .');
scope.currentPages=[];
if(scope.pageInfo.pageIndex > scope.pageInfo.totalPages){
scope.pageInfo.pageIndex = scope.pageInfo.totalPages;
}
if(scope.pageInfo.totalPages>0&&scope.pageInfo.pageIndex==0){
scope.pageInfo.pageIndex = 1;
}
var y =scope.pageInfo.pageIndex%scope.pageInfo.showPages;
if(y===0){
y=5;
}
for(var i=0;i<scope.pageInfo.showPages;i++){
var index = scope.pageInfo.pageIndex-y+1+i;
if(index>0&&index<= scope.pageInfo.totalPages){
scope.currentPages.push({
index:scope.pageInfo.pageIndex-y+1+i
});
}
}
setPrepageOrNextpageBtnStatus();
}
scope.activeClass=function(index){
if(index===scope.pageInfo.pageIndex){
return 'active';
}else{
return '';
}
};
scope.goPage=function(index){
console.log('go to page :',index);
scope.pageInfo.pageIndex = index;
if(scope.onChange()){
scope.onChange()(index);
}
};
scope.nextPages=function(){
if(scope.currentPages.length > 0){
var lastPageIndex = scope.currentPages[scope.currentPages.length-1].index;
if(lastPageIndex === scope.pageInfo.totalPages){
return;
}
scope.currentPages = [];
for(var i =0;i< scope.pageInfo.showPages;i++){
var index = lastPageIndex + i + 1 ;
if(index <= scope.pageInfo.totalPages){
scope.currentPages.push({index:index});
}
}
setPrepageOrNextpageBtnStatus();
}
}
scope.prePages=function(){
if(scope.currentPages.length > 0){
var firstPageIndex = scope.currentPages[0].index;
if(firstPageIndex === 1){
return;
}
scope.currentPages = [];
for(var i = scope.pageInfo.showPages ; i > 0 ; i--){
var index = firstPageIndex - i ;
if(index > 0 ){
scope.currentPages.push({index:index});
}
}
setPrepageOrNextpageBtnStatus();
}
}
build();
}
};
};
angular.module('agile.bootstrap-pagebar',[]).directive('pagebar', directive);
}()); | {
"pile_set_name": "Github"
} |
package scribe
import scala.language.experimental.macros
import perfolation._
case class Position(className: String,
methodName: Option[String],
line: Option[Int],
column: Option[Int],
fileName: String) {
def toTraceElement: StackTraceElement = {
val fn = if (fileName.indexOf('/') != -1) {
fileName.substring(fileName.lastIndexOf('/') + 1)
} else {
fileName
}
new StackTraceElement(className, methodName.getOrElse("unknown"), fn, line.getOrElse(-1))
}
override def toString: String = {
val mn = methodName.map(m => p":$m").getOrElse("")
val ln = line.map(l => p":$l").getOrElse("")
val cn = column.map(c => p":$c").getOrElse("")
val fn = if (fileName.indexOf('/') != -1) {
fileName.substring(fileName.lastIndexOf('/') + 1)
} else {
fileName
}
p"$className$mn$ln$cn ($fn)"
}
}
object Position {
private lazy val threadLocal = new ThreadLocal[List[Position]] {
override def initialValue(): List[Position] = Nil
}
def push(position: Position): Unit = threadLocal.set(position :: threadLocal.get())
def push(): Unit = macro scribe.Macros.pushPosition
def pop(): Option[Position] = {
val stack = threadLocal.get()
if (stack.nonEmpty) {
threadLocal.set(stack.tail)
}
stack.headOption
}
def stack: List[Position] = threadLocal.get().distinct
def stack_=(stack: List[Position]): Unit = threadLocal.set(stack)
def fix[T <: Throwable](throwable: T): T = {
val positionTrace = stack.reverse.map(_.toTraceElement).distinct
val original = throwable.getStackTrace.toList.filterNot(positionTrace.contains)
val trace = (original.head :: positionTrace ::: original.tail).distinct
throwable.setStackTrace(trace.toArray)
throwable
}
} | {
"pile_set_name": "Github"
} |
/*=========================================================================================
File Name: lasagna.js
Description: echarts lasagna chart
----------------------------------------------------------------------------------------
Item Name: Robust - Responsive Admin Template
Version: 2.0
Author: PIXINVENT
Author URL: http://www.themeforest.net/user/pixinvent
==========================================================================================*/
// Lasagna chart
// ------------------------------
$(window).on("load", function(){
// Set paths
// ------------------------------
require.config({
paths: {
echarts: '../../../app-assets/vendors/js/charts/echarts'
}
});
// Configuration
// ------------------------------
require(
[
'echarts',
'echarts/chart/pie',
'echarts/chart/funnel'
],
// Charts setup
function (ec) {
// Initialize chart
// ------------------------------
var myChart = ec.init(document.getElementById('lasagna'));
// Chart Options
// ------------------------------
chartOptions = {
// Add title
title: {
text: 'Browser statistics',
subtext: 'Based on shared research',
x: 'center'
},
// Add tooltip
tooltip: {
trigger: 'item',
formatter: '{a} <br/>{b}: {c} ({d}%)'
},
// Add legend
legend: {
x: 'left',
orient: 'vertical',
data: ['Chrome','Firefox','Safari','IE9+','IE8-']
},
// Add custom colors
color: ['#00A5A8', '#626E82', '#FF7D4D','#FF4558', '#28D094'],
// Enable drag recalculate
calculable: false,
// Add series
series: (function () {
var series = [];
for (var i = 0; i < 30; i++) {
series.push({
name: 'Browser',
type: 'pie',
itemStyle: {
normal: {
label: {
show: i > 28
},
labelLine: {
show: i > 28,
length: 20
}
}
},
radius: [i * 3.6 + 40, i * 3.6 + 43],
center: ['50%', '55%'],
data: [
{value: i * 128 + 80, name: 'Chrome'},
{value: i * 64 + 160, name: 'Firefox'},
{value: i * 32 + 320, name: 'Safari'},
{value: i * 16 + 640, name: 'IE9+'},
{value: i * 8 + 1280, name: 'IE8-'}
]
})
}
return series;
})()
};
// Apply options
// ------------------------------
myChart.setOption(chartOptions);
// Resize chart
// ------------------------------
$(function () {
// Resize chart on menu width change and window resize
$(window).on('resize', resize);
$(".menu-toggle").on('click', resize);
// Resize function
function resize() {
setTimeout(function() {
// Resize chart
myChart.resize();
}, 200);
}
});
}
);
}); | {
"pile_set_name": "Github"
} |
//
// YBPopupMenuPath.h
// YBPopupMenu
//
// Created by lyb on 2017/5/9.
// Copyright © 2017年 lyb. All rights reserved.
//
#import <UIKit/UIKit.h>
typedef NS_ENUM(NSInteger, YBPopupMenuArrowDirection) {
YBPopupMenuArrowDirectionTop = 0, //箭头朝上
YBPopupMenuArrowDirectionBottom, //箭头朝下
YBPopupMenuArrowDirectionLeft, //箭头朝左
YBPopupMenuArrowDirectionRight, //箭头朝右
YBPopupMenuArrowDirectionNone //没有箭头
};
@interface YBPopupMenuPath : NSObject
+ (CAShapeLayer *)yb_maskLayerWithRect:(CGRect)rect
rectCorner:(UIRectCorner)rectCorner
cornerRadius:(CGFloat)cornerRadius
arrowWidth:(CGFloat)arrowWidth
arrowHeight:(CGFloat)arrowHeight
arrowPosition:(CGFloat)arrowPosition
arrowDirection:(YBPopupMenuArrowDirection)arrowDirection;
+ (UIBezierPath *)yb_bezierPathWithRect:(CGRect)rect
rectCorner:(UIRectCorner)rectCorner
cornerRadius:(CGFloat)cornerRadius
borderWidth:(CGFloat)borderWidth
borderColor:(UIColor *)borderColor
backgroundColor:(UIColor *)backgroundColor
arrowWidth:(CGFloat)arrowWidth
arrowHeight:(CGFloat)arrowHeight
arrowPosition:(CGFloat)arrowPosition
arrowDirection:(YBPopupMenuArrowDirection)arrowDirection;
@end
| {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_75) on Wed Aug 26 17:08:43 CDT 2015 -->
<title>ketai.sensors</title>
<meta name="date" content="2015-08-26">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="ketai.sensors";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../index-files/index-1.html">Index</a></li>
<li><a href="../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../ketai/net/wifidirect/package-summary.html">Prev Package</a></li>
<li><a href="../../ketai/ui/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../index.html?ketai/sensors/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 title="Package" class="title">Package ketai.sensors</h1>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="packageSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation">
<caption><span>Class Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Class</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../ketai/sensors/KetaiAudioInput.html" title="class in ketai.sensors">KetaiAudioInput</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../ketai/sensors/KetaiLocation.html" title="class in ketai.sensors">KetaiLocation</a></td>
<td class="colLast">
<div class="block">The KetaiLocation class provides android location services data to a sketch.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../ketai/sensors/KetaiSensor.html" title="class in ketai.sensors">KetaiSensor</a></td>
<td class="colLast">
<div class="block">The KetaiSensor class provides access to android sensors.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../ketai/sensors/Location.html" title="class in ketai.sensors">Location</a></td>
<td class="colLast">
<div class="block">Wrapper for the android location class.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../index-files/index-1.html">Index</a></li>
<li><a href="../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../ketai/net/wifidirect/package-summary.html">Prev Package</a></li>
<li><a href="../../ketai/ui/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../index.html?ketai/sensors/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {
"pile_set_name": "Github"
} |
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 1997-2017 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://oss.oracle.com/licenses/CDDL+GPL-1.1
* or LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package com.sun.xml.ws.sdo.sample.service.types;
import commonj.sdo.Type;
import commonj.sdo.impl.HelperProvider;
import org.eclipse.persistence.sdo.SDODataObject;
public class SortAttributeImpl extends SDODataObject implements SortAttribute {
public static String SDO_URI = "http://sdo.sample.service/types/";
public SortAttributeImpl() {}
// public Type getType() {
// if(type == null){
// Type lookupType = HelperProvider.getTypeHelper().getType(SDO_URI, "SortAttribute");
// setType(lookupType);
// }
// return type;
// }
public java.lang.String getName() {
return getString("name");
}
public void setName(java.lang.String value) {
set("name" , value);
}
public boolean getDescending() {
return getBoolean("descending");
}
public void setDescending(boolean value) {
set("descending" , value);
}
}
| {
"pile_set_name": "Github"
} |
// Copyright Aleksey Gurtovoy 2000-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// Preprocessed version of "boost/mpl/greater_equal.hpp" header
// -- DO NOT modify by hand!
namespace boost { namespace mpl {
template<
typename Tag1
, typename Tag2
>
struct greater_equal_impl
: if_c<
( BOOST_MPL_AUX_NESTED_VALUE_WKND(int, Tag1)
> BOOST_MPL_AUX_NESTED_VALUE_WKND(int, Tag2)
)
, aux::cast2nd_impl< greater_equal_impl< Tag1,Tag1 >,Tag1, Tag2 >
, aux::cast1st_impl< greater_equal_impl< Tag2,Tag2 >,Tag1, Tag2 >
>::type
{
};
/// for Digital Mars C++/compilers with no CTPS/TTP support
template<> struct greater_equal_impl< na,na >
{
template< typename U1, typename U2 > struct apply
{
typedef apply type;
BOOST_STATIC_CONSTANT(int, value = 0);
};
};
template< typename Tag > struct greater_equal_impl< na,Tag >
{
template< typename U1, typename U2 > struct apply
{
typedef apply type;
BOOST_STATIC_CONSTANT(int, value = 0);
};
};
template< typename Tag > struct greater_equal_impl< Tag,na >
{
template< typename U1, typename U2 > struct apply
{
typedef apply type;
BOOST_STATIC_CONSTANT(int, value = 0);
};
};
template< typename T > struct greater_equal_tag
{
typedef typename T::tag type;
};
template<
typename BOOST_MPL_AUX_NA_PARAM(N1)
, typename BOOST_MPL_AUX_NA_PARAM(N2)
>
struct greater_equal
: greater_equal_impl<
typename greater_equal_tag<N1>::type
, typename greater_equal_tag<N2>::type
>::template apply< N1,N2 >::type
{
BOOST_MPL_AUX_LAMBDA_SUPPORT(2, greater_equal, (N1, N2))
};
BOOST_MPL_AUX_NA_SPEC2(2, 2, greater_equal)
}}
namespace boost { namespace mpl {
template<>
struct greater_equal_impl< integral_c_tag,integral_c_tag >
{
template< typename N1, typename N2 > struct apply
: bool_< ( BOOST_MPL_AUX_VALUE_WKND(N1)::value >= BOOST_MPL_AUX_VALUE_WKND(N2)::value ) >
{
};
};
}}
| {
"pile_set_name": "Github"
} |
Pass 1: Checking inodes, blocks, and sizes
Pass 2: Checking directory structure
Pass 3: Checking directory connectivity
Pass 4: Checking reference counts
Pass 5: Checking group summary information
test_filesys: 13/16 files (0.0% non-contiguous), 23/100 blocks
Exit status is 0
| {
"pile_set_name": "Github"
} |
name = Apache Solr search
description = Search with Solr
dependencies[] = search
dependencies[] = apachesolr
package = Apache Solr
core = "6.x"
php = 5.1.4
; Information added by drupal.org packaging script on 2011-11-17
version = "6.x-1.6"
core = "6.x"
project = "apachesolr"
datestamp = "1321498537"
| {
"pile_set_name": "Github"
} |
Unknown package: foo/bar
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2012 Red Hat Inc.
*
* 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 COPYRIGHT HOLDER(S) OR AUTHOR(S) 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.
*
* Authors: Ben Skeggs
*/
#include "nv50.h"
#include "rootnv50.h"
static const struct nv50_disp_func
gk104_disp = {
.intr = gf119_disp_intr,
.uevent = &gf119_disp_chan_uevent,
.super = gf119_disp_intr_supervisor,
.root = &gk104_disp_root_oclass,
.head.vblank_init = gf119_disp_vblank_init,
.head.vblank_fini = gf119_disp_vblank_fini,
.head.scanoutpos = gf119_disp_root_scanoutpos,
.outp.internal.crt = nv50_dac_output_new,
.outp.internal.tmds = nv50_sor_output_new,
.outp.internal.lvds = nv50_sor_output_new,
.outp.internal.dp = gf119_sor_dp_new,
.dac.nr = 3,
.dac.power = nv50_dac_power,
.dac.sense = nv50_dac_sense,
.sor.nr = 4,
.sor.power = nv50_sor_power,
.sor.hda_eld = gf119_hda_eld,
.sor.hdmi = gk104_hdmi_ctrl,
};
int
gk104_disp_new(struct nvkm_device *device, int index, struct nvkm_disp **pdisp)
{
return gf119_disp_new_(&gk104_disp, device, index, pdisp);
}
| {
"pile_set_name": "Github"
} |
//
// MAGroundOverlayRenderer.h
// DevDemo2D
//
// Created by AutoNavi.
// Copyright (c) 2014年 AutoNavi. All rights reserved.
//
#import "MAOverlayRenderer.h"
#import "MAGroundOverlay.h"
/*!
@brief 此类是将MAGroundOverlay中的覆盖图片显示在地图上的renderer;
*/
@interface MAGroundOverlayRenderer : MAOverlayRenderer
/*!
@brief groundOverlay 具有覆盖图片,以及图片覆盖的区域
*/
@property (nonatomic ,readonly) MAGroundOverlay *groundOverlay;
/*!
@brief 根据指定的GroundOverlay生成将图片显示在地图上Renderer
@param groundOverlay 制定了覆盖图片,以及图片的覆盖区域的groundOverlay
@return 以GroundOverlay新生成Renderer
*/
- (instancetype)initWithGroundOverlay:(MAGroundOverlay *)groundOverlay;
@end
| {
"pile_set_name": "Github"
} |
//
// NSTableView_iTerm.h
// iTerm2
//
// Created by George Nachman on 12/2/14.
//
//
#import <Cocoa/Cocoa.h>
@interface NSTableColumn (iTerm)
- (CGFloat)suggestedRowHeight;
@end
| {
"pile_set_name": "Github"
} |
<?php
/**
* @file
* Translate link plugin.
*/
/**
* This handler adds translate link for all translatable entities.
*/
class entity_translation_handler_field_translate_link extends views_handler_field {
function construct() {
parent::construct();
$this->additional_fields['entity_id'] = 'entity_id';
$this->additional_fields['entity_type'] = 'entity_type';
$this->additional_fields['language'] = 'language';
}
/**
* Add required additional fields.
*/
function query() {
$this->ensure_my_table();
$this->add_additional_fields();
}
/**
* Add the text option.
* @see views_handler_field::option_definition()
*/
function option_definition() {
$options = parent::option_definition();
$options['text'] = array('default' => '', 'translatable' => TRUE);
return $options;
}
/**
* Add the option to set the title of the translate link.
* @see views_handler_field::options_form()
*/
function options_form(&$form, &$form_state) {
$form['text'] = array(
'#type' => 'textfield',
'#title' => t('Text to display'),
'#default_value' => $this->options['text'],
);
parent::options_form($form, $form_state);
// The path is set by render_link function so don't allow setting it.
$form['alter']['path'] = array('#access' => FALSE);
$form['alter']['external'] = array('#access' => FALSE);
}
/**
* Load all entities based on the data we have.
*/
function post_execute(&$values) {
$ids = array();
$ids_by_type = array();
foreach ($values as $row) {
if ($entity_type = $this->get_value($row, 'entity_type')) {
$ids_by_type[$entity_type][] = $this->get_value($row, 'entity_id');
}
}
foreach ($ids_by_type as $type => $ids) {
$this->entities[$type] = entity_load($type, $ids);
}
}
/**
* @see views_handler_field::render()
*/
function render($values) {
$type = $this->get_value($values, 'entity_type');
$entity_id = $this->get_value($values, 'entity_id');
// Check if entity is not empty
if (!$entity_id || !$type) {
return NULL;
}
$language = $this->get_value($values, 'language');
$entity = $this->entities[$type][$entity_id];
return $this->render_link($type, $entity_id, $entity, $language);
}
/**
* Render the link to the translation overview page of the entity.
*/
function render_link($entity_type, $entity_id, $entity, $language) {
if (!entity_translation_tab_access($entity_type, $entity)) {
return;
}
// We use the entity info here to avoid having to call entity_load() for all
// the entities.
$info = entity_get_info($entity_type);
$path = $info['translation']['entity_translation']['path schemes']['default']['translate path'];
$path = str_replace($info['translation']['entity_translation']['path schemes']['default']['path wildcard'], $entity_id, $path);
$this->options['alter']['make_link'] = TRUE;
$this->options['alter']['path'] = $path;
$this->options['alter']['query'] = drupal_get_destination();
$text = !empty($this->options['text']) ? $this->options['text'] : t('translate');
return $text;
}
}
| {
"pile_set_name": "Github"
} |
/*! jQuery UI - v1.12.1 - 2018-12-06
* http://jqueryui.com
* Includes: widget.js, position.js, keycode.js, unique-id.js, widgets/autocomplete.js, widgets/menu.js
* Copyright jQuery Foundation and other contributors; Licensed MIT */
(function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define([ "jquery" ], factory );
} else {
// Browser globals
factory( jQuery );
}
}(function( $ ) {
$.ui = $.ui || {};
var version = $.ui.version = "1.12.1";
/*!
* jQuery UI Widget 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: Widget
//>>group: Core
//>>description: Provides a factory for creating stateful widgets with a common API.
//>>docs: http://api.jqueryui.com/jQuery.widget/
//>>demos: http://jqueryui.com/widget/
var widgetUuid = 0;
var widgetSlice = Array.prototype.slice;
$.cleanData = ( function( orig ) {
return function( elems ) {
var events, elem, i;
for ( i = 0; ( elem = elems[ i ] ) != null; i++ ) {
try {
// Only trigger remove when necessary to save time
events = $._data( elem, "events" );
if ( events && events.remove ) {
$( elem ).triggerHandler( "remove" );
}
// Http://bugs.jquery.com/ticket/8235
} catch ( e ) {}
}
orig( elems );
};
} )( $.cleanData );
$.widget = function( name, base, prototype ) {
var existingConstructor, constructor, basePrototype;
// ProxiedPrototype allows the provided prototype to remain unmodified
// so that it can be used as a mixin for multiple widgets (#8876)
var proxiedPrototype = {};
var namespace = name.split( "." )[ 0 ];
name = name.split( "." )[ 1 ];
var fullName = namespace + "-" + name;
if ( !prototype ) {
prototype = base;
base = $.Widget;
}
if ( $.isArray( prototype ) ) {
prototype = $.extend.apply( null, [ {} ].concat( prototype ) );
}
// Create selector for plugin
$.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) {
return !!$.data( elem, fullName );
};
$[ namespace ] = $[ namespace ] || {};
existingConstructor = $[ namespace ][ name ];
constructor = $[ namespace ][ name ] = function( options, element ) {
// Allow instantiation without "new" keyword
if ( !this._createWidget ) {
return new constructor( options, element );
}
// Allow instantiation without initializing for simple inheritance
// must use "new" keyword (the code above always passes args)
if ( arguments.length ) {
this._createWidget( options, element );
}
};
// Extend with the existing constructor to carry over any static properties
$.extend( constructor, existingConstructor, {
version: prototype.version,
// Copy the object used to create the prototype in case we need to
// redefine the widget later
_proto: $.extend( {}, prototype ),
// Track widgets that inherit from this widget in case this widget is
// redefined after a widget inherits from it
_childConstructors: []
} );
basePrototype = new base();
// We need to make the options hash a property directly on the new instance
// otherwise we'll modify the options hash on the prototype that we're
// inheriting from
basePrototype.options = $.widget.extend( {}, basePrototype.options );
$.each( prototype, function( prop, value ) {
if ( !$.isFunction( value ) ) {
proxiedPrototype[ prop ] = value;
return;
}
proxiedPrototype[ prop ] = ( function() {
function _super() {
return base.prototype[ prop ].apply( this, arguments );
}
function _superApply( args ) {
return base.prototype[ prop ].apply( this, args );
}
return function() {
var __super = this._super;
var __superApply = this._superApply;
var returnValue;
this._super = _super;
this._superApply = _superApply;
returnValue = value.apply( this, arguments );
this._super = __super;
this._superApply = __superApply;
return returnValue;
};
} )();
} );
constructor.prototype = $.widget.extend( basePrototype, {
// TODO: remove support for widgetEventPrefix
// always use the name + a colon as the prefix, e.g., draggable:start
// don't prefix for widgets that aren't DOM-based
widgetEventPrefix: existingConstructor ? ( basePrototype.widgetEventPrefix || name ) : name
}, proxiedPrototype, {
constructor: constructor,
namespace: namespace,
widgetName: name,
widgetFullName: fullName
} );
// If this widget is being redefined then we need to find all widgets that
// are inheriting from it and redefine all of them so that they inherit from
// the new version of this widget. We're essentially trying to replace one
// level in the prototype chain.
if ( existingConstructor ) {
$.each( existingConstructor._childConstructors, function( i, child ) {
var childPrototype = child.prototype;
// Redefine the child widget using the same prototype that was
// originally used, but inherit from the new version of the base
$.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor,
child._proto );
} );
// Remove the list of existing child constructors from the old constructor
// so the old child constructors can be garbage collected
delete existingConstructor._childConstructors;
} else {
base._childConstructors.push( constructor );
}
$.widget.bridge( name, constructor );
return constructor;
};
$.widget.extend = function( target ) {
var input = widgetSlice.call( arguments, 1 );
var inputIndex = 0;
var inputLength = input.length;
var key;
var value;
for ( ; inputIndex < inputLength; inputIndex++ ) {
for ( key in input[ inputIndex ] ) {
value = input[ inputIndex ][ key ];
if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) {
// Clone objects
if ( $.isPlainObject( value ) ) {
target[ key ] = $.isPlainObject( target[ key ] ) ?
$.widget.extend( {}, target[ key ], value ) :
// Don't extend strings, arrays, etc. with objects
$.widget.extend( {}, value );
// Copy everything else by reference
} else {
target[ key ] = value;
}
}
}
}
return target;
};
$.widget.bridge = function( name, object ) {
var fullName = object.prototype.widgetFullName || name;
$.fn[ name ] = function( options ) {
var isMethodCall = typeof options === "string";
var args = widgetSlice.call( arguments, 1 );
var returnValue = this;
if ( isMethodCall ) {
// If this is an empty collection, we need to have the instance method
// return undefined instead of the jQuery instance
if ( !this.length && options === "instance" ) {
returnValue = undefined;
} else {
this.each( function() {
var methodValue;
var instance = $.data( this, fullName );
if ( options === "instance" ) {
returnValue = instance;
return false;
}
if ( !instance ) {
return $.error( "cannot call methods on " + name +
" prior to initialization; " +
"attempted to call method '" + options + "'" );
}
if ( !$.isFunction( instance[ options ] ) || options.charAt( 0 ) === "_" ) {
return $.error( "no such method '" + options + "' for " + name +
" widget instance" );
}
methodValue = instance[ options ].apply( instance, args );
if ( methodValue !== instance && methodValue !== undefined ) {
returnValue = methodValue && methodValue.jquery ?
returnValue.pushStack( methodValue.get() ) :
methodValue;
return false;
}
} );
}
} else {
// Allow multiple hashes to be passed on init
if ( args.length ) {
options = $.widget.extend.apply( null, [ options ].concat( args ) );
}
this.each( function() {
var instance = $.data( this, fullName );
if ( instance ) {
instance.option( options || {} );
if ( instance._init ) {
instance._init();
}
} else {
$.data( this, fullName, new object( options, this ) );
}
} );
}
return returnValue;
};
};
$.Widget = function( /* options, element */ ) {};
$.Widget._childConstructors = [];
$.Widget.prototype = {
widgetName: "widget",
widgetEventPrefix: "",
defaultElement: "<div>",
options: {
classes: {},
disabled: false,
// Callbacks
create: null
},
_createWidget: function( options, element ) {
element = $( element || this.defaultElement || this )[ 0 ];
this.element = $( element );
this.uuid = widgetUuid++;
this.eventNamespace = "." + this.widgetName + this.uuid;
this.bindings = $();
this.hoverable = $();
this.focusable = $();
this.classesElementLookup = {};
if ( element !== this ) {
$.data( element, this.widgetFullName, this );
this._on( true, this.element, {
remove: function( event ) {
if ( event.target === element ) {
this.destroy();
}
}
} );
this.document = $( element.style ?
// Element within the document
element.ownerDocument :
// Element is window or document
element.document || element );
this.window = $( this.document[ 0 ].defaultView || this.document[ 0 ].parentWindow );
}
this.options = $.widget.extend( {},
this.options,
this._getCreateOptions(),
options );
this._create();
if ( this.options.disabled ) {
this._setOptionDisabled( this.options.disabled );
}
this._trigger( "create", null, this._getCreateEventData() );
this._init();
},
_getCreateOptions: function() {
return {};
},
_getCreateEventData: $.noop,
_create: $.noop,
_init: $.noop,
destroy: function() {
var that = this;
this._destroy();
$.each( this.classesElementLookup, function( key, value ) {
that._removeClass( value, key );
} );
// We can probably remove the unbind calls in 2.0
// all event bindings should go through this._on()
this.element
.off( this.eventNamespace )
.removeData( this.widgetFullName );
this.widget()
.off( this.eventNamespace )
.removeAttr( "aria-disabled" );
// Clean up events and states
this.bindings.off( this.eventNamespace );
},
_destroy: $.noop,
widget: function() {
return this.element;
},
option: function( key, value ) {
var options = key;
var parts;
var curOption;
var i;
if ( arguments.length === 0 ) {
// Don't return a reference to the internal hash
return $.widget.extend( {}, this.options );
}
if ( typeof key === "string" ) {
// Handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }
options = {};
parts = key.split( "." );
key = parts.shift();
if ( parts.length ) {
curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] );
for ( i = 0; i < parts.length - 1; i++ ) {
curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {};
curOption = curOption[ parts[ i ] ];
}
key = parts.pop();
if ( arguments.length === 1 ) {
return curOption[ key ] === undefined ? null : curOption[ key ];
}
curOption[ key ] = value;
} else {
if ( arguments.length === 1 ) {
return this.options[ key ] === undefined ? null : this.options[ key ];
}
options[ key ] = value;
}
}
this._setOptions( options );
return this;
},
_setOptions: function( options ) {
var key;
for ( key in options ) {
this._setOption( key, options[ key ] );
}
return this;
},
_setOption: function( key, value ) {
if ( key === "classes" ) {
this._setOptionClasses( value );
}
this.options[ key ] = value;
if ( key === "disabled" ) {
this._setOptionDisabled( value );
}
return this;
},
_setOptionClasses: function( value ) {
var classKey, elements, currentElements;
for ( classKey in value ) {
currentElements = this.classesElementLookup[ classKey ];
if ( value[ classKey ] === this.options.classes[ classKey ] ||
!currentElements ||
!currentElements.length ) {
continue;
}
// We are doing this to create a new jQuery object because the _removeClass() call
// on the next line is going to destroy the reference to the current elements being
// tracked. We need to save a copy of this collection so that we can add the new classes
// below.
elements = $( currentElements.get() );
this._removeClass( currentElements, classKey );
// We don't use _addClass() here, because that uses this.options.classes
// for generating the string of classes. We want to use the value passed in from
// _setOption(), this is the new value of the classes option which was passed to
// _setOption(). We pass this value directly to _classes().
elements.addClass( this._classes( {
element: elements,
keys: classKey,
classes: value,
add: true
} ) );
}
},
_setOptionDisabled: function( value ) {
this._toggleClass( this.widget(), this.widgetFullName + "-disabled", null, !!value );
// If the widget is becoming disabled, then nothing is interactive
if ( value ) {
this._removeClass( this.hoverable, null, "ui-state-hover" );
this._removeClass( this.focusable, null, "ui-state-focus" );
}
},
enable: function() {
return this._setOptions( { disabled: false } );
},
disable: function() {
return this._setOptions( { disabled: true } );
},
_classes: function( options ) {
var full = [];
var that = this;
options = $.extend( {
element: this.element,
classes: this.options.classes || {}
}, options );
function processClassString( classes, checkOption ) {
var current, i;
for ( i = 0; i < classes.length; i++ ) {
current = that.classesElementLookup[ classes[ i ] ] || $();
if ( options.add ) {
current = $( $.unique( current.get().concat( options.element.get() ) ) );
} else {
current = $( current.not( options.element ).get() );
}
that.classesElementLookup[ classes[ i ] ] = current;
full.push( classes[ i ] );
if ( checkOption && options.classes[ classes[ i ] ] ) {
full.push( options.classes[ classes[ i ] ] );
}
}
}
this._on( options.element, {
"remove": "_untrackClassesElement"
} );
if ( options.keys ) {
processClassString( options.keys.match( /\S+/g ) || [], true );
}
if ( options.extra ) {
processClassString( options.extra.match( /\S+/g ) || [] );
}
return full.join( " " );
},
_untrackClassesElement: function( event ) {
var that = this;
$.each( that.classesElementLookup, function( key, value ) {
if ( $.inArray( event.target, value ) !== -1 ) {
that.classesElementLookup[ key ] = $( value.not( event.target ).get() );
}
} );
},
_removeClass: function( element, keys, extra ) {
return this._toggleClass( element, keys, extra, false );
},
_addClass: function( element, keys, extra ) {
return this._toggleClass( element, keys, extra, true );
},
_toggleClass: function( element, keys, extra, add ) {
add = ( typeof add === "boolean" ) ? add : extra;
var shift = ( typeof element === "string" || element === null ),
options = {
extra: shift ? keys : extra,
keys: shift ? element : keys,
element: shift ? this.element : element,
add: add
};
options.element.toggleClass( this._classes( options ), add );
return this;
},
_on: function( suppressDisabledCheck, element, handlers ) {
var delegateElement;
var instance = this;
// No suppressDisabledCheck flag, shuffle arguments
if ( typeof suppressDisabledCheck !== "boolean" ) {
handlers = element;
element = suppressDisabledCheck;
suppressDisabledCheck = false;
}
// No element argument, shuffle and use this.element
if ( !handlers ) {
handlers = element;
element = this.element;
delegateElement = this.widget();
} else {
element = delegateElement = $( element );
this.bindings = this.bindings.add( element );
}
$.each( handlers, function( event, handler ) {
function handlerProxy() {
// Allow widgets to customize the disabled handling
// - disabled as an array instead of boolean
// - disabled class as method for disabling individual parts
if ( !suppressDisabledCheck &&
( instance.options.disabled === true ||
$( this ).hasClass( "ui-state-disabled" ) ) ) {
return;
}
return ( typeof handler === "string" ? instance[ handler ] : handler )
.apply( instance, arguments );
}
// Copy the guid so direct unbinding works
if ( typeof handler !== "string" ) {
handlerProxy.guid = handler.guid =
handler.guid || handlerProxy.guid || $.guid++;
}
var match = event.match( /^([\w:-]*)\s*(.*)$/ );
var eventName = match[ 1 ] + instance.eventNamespace;
var selector = match[ 2 ];
if ( selector ) {
delegateElement.on( eventName, selector, handlerProxy );
} else {
element.on( eventName, handlerProxy );
}
} );
},
_off: function( element, eventName ) {
eventName = ( eventName || "" ).split( " " ).join( this.eventNamespace + " " ) +
this.eventNamespace;
element.off( eventName ).off( eventName );
// Clear the stack to avoid memory leaks (#10056)
this.bindings = $( this.bindings.not( element ).get() );
this.focusable = $( this.focusable.not( element ).get() );
this.hoverable = $( this.hoverable.not( element ).get() );
},
_delay: function( handler, delay ) {
function handlerProxy() {
return ( typeof handler === "string" ? instance[ handler ] : handler )
.apply( instance, arguments );
}
var instance = this;
return setTimeout( handlerProxy, delay || 0 );
},
_hoverable: function( element ) {
this.hoverable = this.hoverable.add( element );
this._on( element, {
mouseenter: function( event ) {
this._addClass( $( event.currentTarget ), null, "ui-state-hover" );
},
mouseleave: function( event ) {
this._removeClass( $( event.currentTarget ), null, "ui-state-hover" );
}
} );
},
_focusable: function( element ) {
this.focusable = this.focusable.add( element );
this._on( element, {
focusin: function( event ) {
this._addClass( $( event.currentTarget ), null, "ui-state-focus" );
},
focusout: function( event ) {
this._removeClass( $( event.currentTarget ), null, "ui-state-focus" );
}
} );
},
_trigger: function( type, event, data ) {
var prop, orig;
var callback = this.options[ type ];
data = data || {};
event = $.Event( event );
event.type = ( type === this.widgetEventPrefix ?
type :
this.widgetEventPrefix + type ).toLowerCase();
// The original event may come from any element
// so we need to reset the target on the new event
event.target = this.element[ 0 ];
// Copy original event properties over to the new event
orig = event.originalEvent;
if ( orig ) {
for ( prop in orig ) {
if ( !( prop in event ) ) {
event[ prop ] = orig[ prop ];
}
}
}
this.element.trigger( event, data );
return !( $.isFunction( callback ) &&
callback.apply( this.element[ 0 ], [ event ].concat( data ) ) === false ||
event.isDefaultPrevented() );
}
};
$.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) {
$.Widget.prototype[ "_" + method ] = function( element, options, callback ) {
if ( typeof options === "string" ) {
options = { effect: options };
}
var hasOptions;
var effectName = !options ?
method :
options === true || typeof options === "number" ?
defaultEffect :
options.effect || defaultEffect;
options = options || {};
if ( typeof options === "number" ) {
options = { duration: options };
}
hasOptions = !$.isEmptyObject( options );
options.complete = callback;
if ( options.delay ) {
element.delay( options.delay );
}
if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) {
element[ method ]( options );
} else if ( effectName !== method && element[ effectName ] ) {
element[ effectName ]( options.duration, options.easing, callback );
} else {
element.queue( function( next ) {
$( this )[ method ]();
if ( callback ) {
callback.call( element[ 0 ] );
}
next();
} );
}
};
} );
var widget = $.widget;
/*!
* jQuery UI Position 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/position/
*/
//>>label: Position
//>>group: Core
//>>description: Positions elements relative to other elements.
//>>docs: http://api.jqueryui.com/position/
//>>demos: http://jqueryui.com/position/
( function() {
var cachedScrollbarWidth,
max = Math.max,
abs = Math.abs,
rhorizontal = /left|center|right/,
rvertical = /top|center|bottom/,
roffset = /[\+\-]\d+(\.[\d]+)?%?/,
rposition = /^\w+/,
rpercent = /%$/,
_position = $.fn.position;
function getOffsets( offsets, width, height ) {
return [
parseFloat( offsets[ 0 ] ) * ( rpercent.test( offsets[ 0 ] ) ? width / 100 : 1 ),
parseFloat( offsets[ 1 ] ) * ( rpercent.test( offsets[ 1 ] ) ? height / 100 : 1 )
];
}
function parseCss( element, property ) {
return parseInt( $.css( element, property ), 10 ) || 0;
}
function getDimensions( elem ) {
var raw = elem[ 0 ];
if ( raw.nodeType === 9 ) {
return {
width: elem.width(),
height: elem.height(),
offset: { top: 0, left: 0 }
};
}
if ( $.isWindow( raw ) ) {
return {
width: elem.width(),
height: elem.height(),
offset: { top: elem.scrollTop(), left: elem.scrollLeft() }
};
}
if ( raw.preventDefault ) {
return {
width: 0,
height: 0,
offset: { top: raw.pageY, left: raw.pageX }
};
}
return {
width: elem.outerWidth(),
height: elem.outerHeight(),
offset: elem.offset()
};
}
$.position = {
scrollbarWidth: function() {
if ( cachedScrollbarWidth !== undefined ) {
return cachedScrollbarWidth;
}
var w1, w2,
div = $( "<div " +
"style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'>" +
"<div style='height:100px;width:auto;'></div></div>" ),
innerDiv = div.children()[ 0 ];
$( "body" ).append( div );
w1 = innerDiv.offsetWidth;
div.css( "overflow", "scroll" );
w2 = innerDiv.offsetWidth;
if ( w1 === w2 ) {
w2 = div[ 0 ].clientWidth;
}
div.remove();
return ( cachedScrollbarWidth = w1 - w2 );
},
getScrollInfo: function( within ) {
var overflowX = within.isWindow || within.isDocument ? "" :
within.element.css( "overflow-x" ),
overflowY = within.isWindow || within.isDocument ? "" :
within.element.css( "overflow-y" ),
hasOverflowX = overflowX === "scroll" ||
( overflowX === "auto" && within.width < within.element[ 0 ].scrollWidth ),
hasOverflowY = overflowY === "scroll" ||
( overflowY === "auto" && within.height < within.element[ 0 ].scrollHeight );
return {
width: hasOverflowY ? $.position.scrollbarWidth() : 0,
height: hasOverflowX ? $.position.scrollbarWidth() : 0
};
},
getWithinInfo: function( element ) {
var withinElement = $( element || window ),
isWindow = $.isWindow( withinElement[ 0 ] ),
isDocument = !!withinElement[ 0 ] && withinElement[ 0 ].nodeType === 9,
hasOffset = !isWindow && !isDocument;
return {
element: withinElement,
isWindow: isWindow,
isDocument: isDocument,
offset: hasOffset ? $( element ).offset() : { left: 0, top: 0 },
scrollLeft: withinElement.scrollLeft(),
scrollTop: withinElement.scrollTop(),
width: withinElement.outerWidth(),
height: withinElement.outerHeight()
};
}
};
$.fn.position = function( options ) {
if ( !options || !options.of ) {
return _position.apply( this, arguments );
}
// Make a copy, we don't want to modify arguments
options = $.extend( {}, options );
var atOffset, targetWidth, targetHeight, targetOffset, basePosition, dimensions,
target = $( options.of ),
within = $.position.getWithinInfo( options.within ),
scrollInfo = $.position.getScrollInfo( within ),
collision = ( options.collision || "flip" ).split( " " ),
offsets = {};
dimensions = getDimensions( target );
if ( target[ 0 ].preventDefault ) {
// Force left top to allow flipping
options.at = "left top";
}
targetWidth = dimensions.width;
targetHeight = dimensions.height;
targetOffset = dimensions.offset;
// Clone to reuse original targetOffset later
basePosition = $.extend( {}, targetOffset );
// Force my and at to have valid horizontal and vertical positions
// if a value is missing or invalid, it will be converted to center
$.each( [ "my", "at" ], function() {
var pos = ( options[ this ] || "" ).split( " " ),
horizontalOffset,
verticalOffset;
if ( pos.length === 1 ) {
pos = rhorizontal.test( pos[ 0 ] ) ?
pos.concat( [ "center" ] ) :
rvertical.test( pos[ 0 ] ) ?
[ "center" ].concat( pos ) :
[ "center", "center" ];
}
pos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : "center";
pos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : "center";
// Calculate offsets
horizontalOffset = roffset.exec( pos[ 0 ] );
verticalOffset = roffset.exec( pos[ 1 ] );
offsets[ this ] = [
horizontalOffset ? horizontalOffset[ 0 ] : 0,
verticalOffset ? verticalOffset[ 0 ] : 0
];
// Reduce to just the positions without the offsets
options[ this ] = [
rposition.exec( pos[ 0 ] )[ 0 ],
rposition.exec( pos[ 1 ] )[ 0 ]
];
} );
// Normalize collision option
if ( collision.length === 1 ) {
collision[ 1 ] = collision[ 0 ];
}
if ( options.at[ 0 ] === "right" ) {
basePosition.left += targetWidth;
} else if ( options.at[ 0 ] === "center" ) {
basePosition.left += targetWidth / 2;
}
if ( options.at[ 1 ] === "bottom" ) {
basePosition.top += targetHeight;
} else if ( options.at[ 1 ] === "center" ) {
basePosition.top += targetHeight / 2;
}
atOffset = getOffsets( offsets.at, targetWidth, targetHeight );
basePosition.left += atOffset[ 0 ];
basePosition.top += atOffset[ 1 ];
return this.each( function() {
var collisionPosition, using,
elem = $( this ),
elemWidth = elem.outerWidth(),
elemHeight = elem.outerHeight(),
marginLeft = parseCss( this, "marginLeft" ),
marginTop = parseCss( this, "marginTop" ),
collisionWidth = elemWidth + marginLeft + parseCss( this, "marginRight" ) +
scrollInfo.width,
collisionHeight = elemHeight + marginTop + parseCss( this, "marginBottom" ) +
scrollInfo.height,
position = $.extend( {}, basePosition ),
myOffset = getOffsets( offsets.my, elem.outerWidth(), elem.outerHeight() );
if ( options.my[ 0 ] === "right" ) {
position.left -= elemWidth;
} else if ( options.my[ 0 ] === "center" ) {
position.left -= elemWidth / 2;
}
if ( options.my[ 1 ] === "bottom" ) {
position.top -= elemHeight;
} else if ( options.my[ 1 ] === "center" ) {
position.top -= elemHeight / 2;
}
position.left += myOffset[ 0 ];
position.top += myOffset[ 1 ];
collisionPosition = {
marginLeft: marginLeft,
marginTop: marginTop
};
$.each( [ "left", "top" ], function( i, dir ) {
if ( $.ui.position[ collision[ i ] ] ) {
$.ui.position[ collision[ i ] ][ dir ]( position, {
targetWidth: targetWidth,
targetHeight: targetHeight,
elemWidth: elemWidth,
elemHeight: elemHeight,
collisionPosition: collisionPosition,
collisionWidth: collisionWidth,
collisionHeight: collisionHeight,
offset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ],
my: options.my,
at: options.at,
within: within,
elem: elem
} );
}
} );
if ( options.using ) {
// Adds feedback as second argument to using callback, if present
using = function( props ) {
var left = targetOffset.left - position.left,
right = left + targetWidth - elemWidth,
top = targetOffset.top - position.top,
bottom = top + targetHeight - elemHeight,
feedback = {
target: {
element: target,
left: targetOffset.left,
top: targetOffset.top,
width: targetWidth,
height: targetHeight
},
element: {
element: elem,
left: position.left,
top: position.top,
width: elemWidth,
height: elemHeight
},
horizontal: right < 0 ? "left" : left > 0 ? "right" : "center",
vertical: bottom < 0 ? "top" : top > 0 ? "bottom" : "middle"
};
if ( targetWidth < elemWidth && abs( left + right ) < targetWidth ) {
feedback.horizontal = "center";
}
if ( targetHeight < elemHeight && abs( top + bottom ) < targetHeight ) {
feedback.vertical = "middle";
}
if ( max( abs( left ), abs( right ) ) > max( abs( top ), abs( bottom ) ) ) {
feedback.important = "horizontal";
} else {
feedback.important = "vertical";
}
options.using.call( this, props, feedback );
};
}
elem.offset( $.extend( position, { using: using } ) );
} );
};
$.ui.position = {
fit: {
left: function( position, data ) {
var within = data.within,
withinOffset = within.isWindow ? within.scrollLeft : within.offset.left,
outerWidth = within.width,
collisionPosLeft = position.left - data.collisionPosition.marginLeft,
overLeft = withinOffset - collisionPosLeft,
overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset,
newOverRight;
// Element is wider than within
if ( data.collisionWidth > outerWidth ) {
// Element is initially over the left side of within
if ( overLeft > 0 && overRight <= 0 ) {
newOverRight = position.left + overLeft + data.collisionWidth - outerWidth -
withinOffset;
position.left += overLeft - newOverRight;
// Element is initially over right side of within
} else if ( overRight > 0 && overLeft <= 0 ) {
position.left = withinOffset;
// Element is initially over both left and right sides of within
} else {
if ( overLeft > overRight ) {
position.left = withinOffset + outerWidth - data.collisionWidth;
} else {
position.left = withinOffset;
}
}
// Too far left -> align with left edge
} else if ( overLeft > 0 ) {
position.left += overLeft;
// Too far right -> align with right edge
} else if ( overRight > 0 ) {
position.left -= overRight;
// Adjust based on position and margin
} else {
position.left = max( position.left - collisionPosLeft, position.left );
}
},
top: function( position, data ) {
var within = data.within,
withinOffset = within.isWindow ? within.scrollTop : within.offset.top,
outerHeight = data.within.height,
collisionPosTop = position.top - data.collisionPosition.marginTop,
overTop = withinOffset - collisionPosTop,
overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset,
newOverBottom;
// Element is taller than within
if ( data.collisionHeight > outerHeight ) {
// Element is initially over the top of within
if ( overTop > 0 && overBottom <= 0 ) {
newOverBottom = position.top + overTop + data.collisionHeight - outerHeight -
withinOffset;
position.top += overTop - newOverBottom;
// Element is initially over bottom of within
} else if ( overBottom > 0 && overTop <= 0 ) {
position.top = withinOffset;
// Element is initially over both top and bottom of within
} else {
if ( overTop > overBottom ) {
position.top = withinOffset + outerHeight - data.collisionHeight;
} else {
position.top = withinOffset;
}
}
// Too far up -> align with top
} else if ( overTop > 0 ) {
position.top += overTop;
// Too far down -> align with bottom edge
} else if ( overBottom > 0 ) {
position.top -= overBottom;
// Adjust based on position and margin
} else {
position.top = max( position.top - collisionPosTop, position.top );
}
}
},
flip: {
left: function( position, data ) {
var within = data.within,
withinOffset = within.offset.left + within.scrollLeft,
outerWidth = within.width,
offsetLeft = within.isWindow ? within.scrollLeft : within.offset.left,
collisionPosLeft = position.left - data.collisionPosition.marginLeft,
overLeft = collisionPosLeft - offsetLeft,
overRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft,
myOffset = data.my[ 0 ] === "left" ?
-data.elemWidth :
data.my[ 0 ] === "right" ?
data.elemWidth :
0,
atOffset = data.at[ 0 ] === "left" ?
data.targetWidth :
data.at[ 0 ] === "right" ?
-data.targetWidth :
0,
offset = -2 * data.offset[ 0 ],
newOverRight,
newOverLeft;
if ( overLeft < 0 ) {
newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth -
outerWidth - withinOffset;
if ( newOverRight < 0 || newOverRight < abs( overLeft ) ) {
position.left += myOffset + atOffset + offset;
}
} else if ( overRight > 0 ) {
newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset +
atOffset + offset - offsetLeft;
if ( newOverLeft > 0 || abs( newOverLeft ) < overRight ) {
position.left += myOffset + atOffset + offset;
}
}
},
top: function( position, data ) {
var within = data.within,
withinOffset = within.offset.top + within.scrollTop,
outerHeight = within.height,
offsetTop = within.isWindow ? within.scrollTop : within.offset.top,
collisionPosTop = position.top - data.collisionPosition.marginTop,
overTop = collisionPosTop - offsetTop,
overBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop,
top = data.my[ 1 ] === "top",
myOffset = top ?
-data.elemHeight :
data.my[ 1 ] === "bottom" ?
data.elemHeight :
0,
atOffset = data.at[ 1 ] === "top" ?
data.targetHeight :
data.at[ 1 ] === "bottom" ?
-data.targetHeight :
0,
offset = -2 * data.offset[ 1 ],
newOverTop,
newOverBottom;
if ( overTop < 0 ) {
newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight -
outerHeight - withinOffset;
if ( newOverBottom < 0 || newOverBottom < abs( overTop ) ) {
position.top += myOffset + atOffset + offset;
}
} else if ( overBottom > 0 ) {
newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset +
offset - offsetTop;
if ( newOverTop > 0 || abs( newOverTop ) < overBottom ) {
position.top += myOffset + atOffset + offset;
}
}
}
},
flipfit: {
left: function() {
$.ui.position.flip.left.apply( this, arguments );
$.ui.position.fit.left.apply( this, arguments );
},
top: function() {
$.ui.position.flip.top.apply( this, arguments );
$.ui.position.fit.top.apply( this, arguments );
}
}
};
} )();
var position = $.ui.position;
/*!
* jQuery UI Keycode 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: Keycode
//>>group: Core
//>>description: Provide keycodes as keynames
//>>docs: http://api.jqueryui.com/jQuery.ui.keyCode/
var keycode = $.ui.keyCode = {
BACKSPACE: 8,
COMMA: 188,
DELETE: 46,
DOWN: 40,
END: 35,
ENTER: 13,
ESCAPE: 27,
HOME: 36,
LEFT: 37,
PAGE_DOWN: 34,
PAGE_UP: 33,
PERIOD: 190,
RIGHT: 39,
SPACE: 32,
TAB: 9,
UP: 38
};
/*!
* jQuery UI Unique ID 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: uniqueId
//>>group: Core
//>>description: Functions to generate and remove uniqueId's
//>>docs: http://api.jqueryui.com/uniqueId/
var uniqueId = $.fn.extend( {
uniqueId: ( function() {
var uuid = 0;
return function() {
return this.each( function() {
if ( !this.id ) {
this.id = "ui-id-" + ( ++uuid );
}
} );
};
} )(),
removeUniqueId: function() {
return this.each( function() {
if ( /^ui-id-\d+$/.test( this.id ) ) {
$( this ).removeAttr( "id" );
}
} );
}
} );
var safeActiveElement = $.ui.safeActiveElement = function( document ) {
var activeElement;
// Support: IE 9 only
// IE9 throws an "Unspecified error" accessing document.activeElement from an <iframe>
try {
activeElement = document.activeElement;
} catch ( error ) {
activeElement = document.body;
}
// Support: IE 9 - 11 only
// IE may return null instead of an element
// Interestingly, this only seems to occur when NOT in an iframe
if ( !activeElement ) {
activeElement = document.body;
}
// Support: IE 11 only
// IE11 returns a seemingly empty object in some cases when accessing
// document.activeElement from an <iframe>
if ( !activeElement.nodeName ) {
activeElement = document.body;
}
return activeElement;
};
/*!
* jQuery UI Menu 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: Menu
//>>group: Widgets
//>>description: Creates nestable menus.
//>>docs: http://api.jqueryui.com/menu/
//>>demos: http://jqueryui.com/menu/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/menu.css
//>>css.theme: ../../themes/base/theme.css
var widgetsMenu = $.widget( "ui.menu", {
version: "1.12.1",
defaultElement: "<ul>",
delay: 300,
options: {
icons: {
submenu: "ui-icon-caret-1-e"
},
items: "> *",
menus: "ul",
position: {
my: "left top",
at: "right top"
},
role: "menu",
// Callbacks
blur: null,
focus: null,
select: null
},
_create: function() {
this.activeMenu = this.element;
// Flag used to prevent firing of the click handler
// as the event bubbles up through nested menus
this.mouseHandled = false;
this.element
.uniqueId()
.attr( {
role: this.options.role,
tabIndex: 0
} );
this._addClass( "ui-menu", "ui-widget ui-widget-content" );
this._on( {
// Prevent focus from sticking to links inside menu after clicking
// them (focus should always stay on UL during navigation).
"mousedown .ui-menu-item": function( event ) {
event.preventDefault();
},
"click .ui-menu-item": function( event ) {
var target = $( event.target );
var active = $( $.ui.safeActiveElement( this.document[ 0 ] ) );
if ( !this.mouseHandled && target.not( ".ui-state-disabled" ).length ) {
this.select( event );
// Only set the mouseHandled flag if the event will bubble, see #9469.
if ( !event.isPropagationStopped() ) {
this.mouseHandled = true;
}
// Open submenu on click
if ( target.has( ".ui-menu" ).length ) {
this.expand( event );
} else if ( !this.element.is( ":focus" ) &&
active.closest( ".ui-menu" ).length ) {
// Redirect focus to the menu
this.element.trigger( "focus", [ true ] );
// If the active item is on the top level, let it stay active.
// Otherwise, blur the active item since it is no longer visible.
if ( this.active && this.active.parents( ".ui-menu" ).length === 1 ) {
clearTimeout( this.timer );
}
}
}
},
"mouseenter .ui-menu-item": function( event ) {
// Ignore mouse events while typeahead is active, see #10458.
// Prevents focusing the wrong item when typeahead causes a scroll while the mouse
// is over an item in the menu
if ( this.previousFilter ) {
return;
}
var actualTarget = $( event.target ).closest( ".ui-menu-item" ),
target = $( event.currentTarget );
// Ignore bubbled events on parent items, see #11641
if ( actualTarget[ 0 ] !== target[ 0 ] ) {
return;
}
// Remove ui-state-active class from siblings of the newly focused menu item
// to avoid a jump caused by adjacent elements both having a class with a border
this._removeClass( target.siblings().children( ".ui-state-active" ),
null, "ui-state-active" );
this.focus( event, target );
},
mouseleave: "collapseAll",
"mouseleave .ui-menu": "collapseAll",
focus: function( event, keepActiveItem ) {
// If there's already an active item, keep it active
// If not, activate the first item
var item = this.active || this.element.find( this.options.items ).eq( 0 );
if ( !keepActiveItem ) {
this.focus( event, item );
}
},
blur: function( event ) {
this._delay( function() {
var notContained = !$.contains(
this.element[ 0 ],
$.ui.safeActiveElement( this.document[ 0 ] )
);
if ( notContained ) {
this.collapseAll( event );
}
} );
},
keydown: "_keydown"
} );
this.refresh();
// Clicks outside of a menu collapse any open menus
this._on( this.document, {
click: function( event ) {
if ( this._closeOnDocumentClick( event ) ) {
this.collapseAll( event );
}
// Reset the mouseHandled flag
this.mouseHandled = false;
}
} );
},
_destroy: function() {
var items = this.element.find( ".ui-menu-item" )
.removeAttr( "role aria-disabled" ),
submenus = items.children( ".ui-menu-item-wrapper" )
.removeUniqueId()
.removeAttr( "tabIndex role aria-haspopup" );
// Destroy (sub)menus
this.element
.removeAttr( "aria-activedescendant" )
.find( ".ui-menu" ).addBack()
.removeAttr( "role aria-labelledby aria-expanded aria-hidden aria-disabled " +
"tabIndex" )
.removeUniqueId()
.show();
submenus.children().each( function() {
var elem = $( this );
if ( elem.data( "ui-menu-submenu-caret" ) ) {
elem.remove();
}
} );
},
_keydown: function( event ) {
var match, prev, character, skip,
preventDefault = true;
switch ( event.keyCode ) {
case $.ui.keyCode.PAGE_UP:
this.previousPage( event );
break;
case $.ui.keyCode.PAGE_DOWN:
this.nextPage( event );
break;
case $.ui.keyCode.HOME:
this._move( "first", "first", event );
break;
case $.ui.keyCode.END:
this._move( "last", "last", event );
break;
case $.ui.keyCode.UP:
this.previous( event );
break;
case $.ui.keyCode.DOWN:
this.next( event );
break;
case $.ui.keyCode.LEFT:
this.collapse( event );
break;
case $.ui.keyCode.RIGHT:
if ( this.active && !this.active.is( ".ui-state-disabled" ) ) {
this.expand( event );
}
break;
case $.ui.keyCode.ENTER:
case $.ui.keyCode.SPACE:
this._activate( event );
break;
case $.ui.keyCode.ESCAPE:
this.collapse( event );
break;
default:
preventDefault = false;
prev = this.previousFilter || "";
skip = false;
// Support number pad values
character = event.keyCode >= 96 && event.keyCode <= 105 ?
( event.keyCode - 96 ).toString() : String.fromCharCode( event.keyCode );
clearTimeout( this.filterTimer );
if ( character === prev ) {
skip = true;
} else {
character = prev + character;
}
match = this._filterMenuItems( character );
match = skip && match.index( this.active.next() ) !== -1 ?
this.active.nextAll( ".ui-menu-item" ) :
match;
// If no matches on the current filter, reset to the last character pressed
// to move down the menu to the first item that starts with that character
if ( !match.length ) {
character = String.fromCharCode( event.keyCode );
match = this._filterMenuItems( character );
}
if ( match.length ) {
this.focus( event, match );
this.previousFilter = character;
this.filterTimer = this._delay( function() {
delete this.previousFilter;
}, 1000 );
} else {
delete this.previousFilter;
}
}
if ( preventDefault ) {
event.preventDefault();
}
},
_activate: function( event ) {
if ( this.active && !this.active.is( ".ui-state-disabled" ) ) {
if ( this.active.children( "[aria-haspopup='true']" ).length ) {
this.expand( event );
} else {
this.select( event );
}
}
},
refresh: function() {
var menus, items, newSubmenus, newItems, newWrappers,
that = this,
icon = this.options.icons.submenu,
submenus = this.element.find( this.options.menus );
this._toggleClass( "ui-menu-icons", null, !!this.element.find( ".ui-icon" ).length );
// Initialize nested menus
newSubmenus = submenus.filter( ":not(.ui-menu)" )
.hide()
.attr( {
role: this.options.role,
"aria-hidden": "true",
"aria-expanded": "false"
} )
.each( function() {
var menu = $( this ),
item = menu.prev(),
submenuCaret = $( "<span>" ).data( "ui-menu-submenu-caret", true );
that._addClass( submenuCaret, "ui-menu-icon", "ui-icon " + icon );
item
.attr( "aria-haspopup", "true" )
.prepend( submenuCaret );
menu.attr( "aria-labelledby", item.attr( "id" ) );
} );
this._addClass( newSubmenus, "ui-menu", "ui-widget ui-widget-content ui-front" );
menus = submenus.add( this.element );
items = menus.find( this.options.items );
// Initialize menu-items containing spaces and/or dashes only as dividers
items.not( ".ui-menu-item" ).each( function() {
var item = $( this );
if ( that._isDivider( item ) ) {
that._addClass( item, "ui-menu-divider", "ui-widget-content" );
}
} );
// Don't refresh list items that are already adapted
newItems = items.not( ".ui-menu-item, .ui-menu-divider" );
newWrappers = newItems.children()
.not( ".ui-menu" )
.uniqueId()
.attr( {
tabIndex: -1,
role: this._itemRole()
} );
this._addClass( newItems, "ui-menu-item" )
._addClass( newWrappers, "ui-menu-item-wrapper" );
// Add aria-disabled attribute to any disabled menu item
items.filter( ".ui-state-disabled" ).attr( "aria-disabled", "true" );
// If the active item has been removed, blur the menu
if ( this.active && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) {
this.blur();
}
},
_itemRole: function() {
return {
menu: "menuitem",
listbox: "option"
}[ this.options.role ];
},
_setOption: function( key, value ) {
if ( key === "icons" ) {
var icons = this.element.find( ".ui-menu-icon" );
this._removeClass( icons, null, this.options.icons.submenu )
._addClass( icons, null, value.submenu );
}
this._super( key, value );
},
_setOptionDisabled: function( value ) {
this._super( value );
this.element.attr( "aria-disabled", String( value ) );
this._toggleClass( null, "ui-state-disabled", !!value );
},
focus: function( event, item ) {
var nested, focused, activeParent;
this.blur( event, event && event.type === "focus" );
this._scrollIntoView( item );
this.active = item.first();
focused = this.active.children( ".ui-menu-item-wrapper" );
this._addClass( focused, null, "ui-state-active" );
// Only update aria-activedescendant if there's a role
// otherwise we assume focus is managed elsewhere
if ( this.options.role ) {
this.element.attr( "aria-activedescendant", focused.attr( "id" ) );
}
// Highlight active parent menu item, if any
activeParent = this.active
.parent()
.closest( ".ui-menu-item" )
.children( ".ui-menu-item-wrapper" );
this._addClass( activeParent, null, "ui-state-active" );
if ( event && event.type === "keydown" ) {
this._close();
} else {
this.timer = this._delay( function() {
this._close();
}, this.delay );
}
nested = item.children( ".ui-menu" );
if ( nested.length && event && ( /^mouse/.test( event.type ) ) ) {
this._startOpening( nested );
}
this.activeMenu = item.parent();
this._trigger( "focus", event, { item: item } );
},
_scrollIntoView: function( item ) {
var borderTop, paddingTop, offset, scroll, elementHeight, itemHeight;
if ( this._hasScroll() ) {
borderTop = parseFloat( $.css( this.activeMenu[ 0 ], "borderTopWidth" ) ) || 0;
paddingTop = parseFloat( $.css( this.activeMenu[ 0 ], "paddingTop" ) ) || 0;
offset = item.offset().top - this.activeMenu.offset().top - borderTop - paddingTop;
scroll = this.activeMenu.scrollTop();
elementHeight = this.activeMenu.height();
itemHeight = item.outerHeight();
if ( offset < 0 ) {
this.activeMenu.scrollTop( scroll + offset );
} else if ( offset + itemHeight > elementHeight ) {
this.activeMenu.scrollTop( scroll + offset - elementHeight + itemHeight );
}
}
},
blur: function( event, fromFocus ) {
if ( !fromFocus ) {
clearTimeout( this.timer );
}
if ( !this.active ) {
return;
}
this._removeClass( this.active.children( ".ui-menu-item-wrapper" ),
null, "ui-state-active" );
this._trigger( "blur", event, { item: this.active } );
this.active = null;
},
_startOpening: function( submenu ) {
clearTimeout( this.timer );
// Don't open if already open fixes a Firefox bug that caused a .5 pixel
// shift in the submenu position when mousing over the caret icon
if ( submenu.attr( "aria-hidden" ) !== "true" ) {
return;
}
this.timer = this._delay( function() {
this._close();
this._open( submenu );
}, this.delay );
},
_open: function( submenu ) {
var position = $.extend( {
of: this.active
}, this.options.position );
clearTimeout( this.timer );
this.element.find( ".ui-menu" ).not( submenu.parents( ".ui-menu" ) )
.hide()
.attr( "aria-hidden", "true" );
submenu
.show()
.removeAttr( "aria-hidden" )
.attr( "aria-expanded", "true" )
.position( position );
},
collapseAll: function( event, all ) {
clearTimeout( this.timer );
this.timer = this._delay( function() {
// If we were passed an event, look for the submenu that contains the event
var currentMenu = all ? this.element :
$( event && event.target ).closest( this.element.find( ".ui-menu" ) );
// If we found no valid submenu ancestor, use the main menu to close all
// sub menus anyway
if ( !currentMenu.length ) {
currentMenu = this.element;
}
this._close( currentMenu );
this.blur( event );
// Work around active item staying active after menu is blurred
this._removeClass( currentMenu.find( ".ui-state-active" ), null, "ui-state-active" );
this.activeMenu = currentMenu;
}, this.delay );
},
// With no arguments, closes the currently active menu - if nothing is active
// it closes all menus. If passed an argument, it will search for menus BELOW
_close: function( startMenu ) {
if ( !startMenu ) {
startMenu = this.active ? this.active.parent() : this.element;
}
startMenu.find( ".ui-menu" )
.hide()
.attr( "aria-hidden", "true" )
.attr( "aria-expanded", "false" );
},
_closeOnDocumentClick: function( event ) {
return !$( event.target ).closest( ".ui-menu" ).length;
},
_isDivider: function( item ) {
// Match hyphen, em dash, en dash
return !/[^\-\u2014\u2013\s]/.test( item.text() );
},
collapse: function( event ) {
var newItem = this.active &&
this.active.parent().closest( ".ui-menu-item", this.element );
if ( newItem && newItem.length ) {
this._close();
this.focus( event, newItem );
}
},
expand: function( event ) {
var newItem = this.active &&
this.active
.children( ".ui-menu " )
.find( this.options.items )
.first();
if ( newItem && newItem.length ) {
this._open( newItem.parent() );
// Delay so Firefox will not hide activedescendant change in expanding submenu from AT
this._delay( function() {
this.focus( event, newItem );
} );
}
},
next: function( event ) {
this._move( "next", "first", event );
},
previous: function( event ) {
this._move( "prev", "last", event );
},
isFirstItem: function() {
return this.active && !this.active.prevAll( ".ui-menu-item" ).length;
},
isLastItem: function() {
return this.active && !this.active.nextAll( ".ui-menu-item" ).length;
},
_move: function( direction, filter, event ) {
var next;
if ( this.active ) {
if ( direction === "first" || direction === "last" ) {
next = this.active
[ direction === "first" ? "prevAll" : "nextAll" ]( ".ui-menu-item" )
.eq( -1 );
} else {
next = this.active
[ direction + "All" ]( ".ui-menu-item" )
.eq( 0 );
}
}
if ( !next || !next.length || !this.active ) {
next = this.activeMenu.find( this.options.items )[ filter ]();
}
this.focus( event, next );
},
nextPage: function( event ) {
var item, base, height;
if ( !this.active ) {
this.next( event );
return;
}
if ( this.isLastItem() ) {
return;
}
if ( this._hasScroll() ) {
base = this.active.offset().top;
height = this.element.height();
this.active.nextAll( ".ui-menu-item" ).each( function() {
item = $( this );
return item.offset().top - base - height < 0;
} );
this.focus( event, item );
} else {
this.focus( event, this.activeMenu.find( this.options.items )
[ !this.active ? "first" : "last" ]() );
}
},
previousPage: function( event ) {
var item, base, height;
if ( !this.active ) {
this.next( event );
return;
}
if ( this.isFirstItem() ) {
return;
}
if ( this._hasScroll() ) {
base = this.active.offset().top;
height = this.element.height();
this.active.prevAll( ".ui-menu-item" ).each( function() {
item = $( this );
return item.offset().top - base + height > 0;
} );
this.focus( event, item );
} else {
this.focus( event, this.activeMenu.find( this.options.items ).first() );
}
},
_hasScroll: function() {
return this.element.outerHeight() < this.element.prop( "scrollHeight" );
},
select: function( event ) {
// TODO: It should never be possible to not have an active item at this
// point, but the tests don't trigger mouseenter before click.
this.active = this.active || $( event.target ).closest( ".ui-menu-item" );
var ui = { item: this.active };
if ( !this.active.has( ".ui-menu" ).length ) {
this.collapseAll( event, true );
}
this._trigger( "select", event, ui );
},
_filterMenuItems: function( character ) {
var escapedCharacter = character.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" ),
regex = new RegExp( "^" + escapedCharacter, "i" );
return this.activeMenu
.find( this.options.items )
// Only match on items, not dividers or other content (#10571)
.filter( ".ui-menu-item" )
.filter( function() {
return regex.test(
$.trim( $( this ).children( ".ui-menu-item-wrapper" ).text() ) );
} );
}
} );
/*!
* jQuery UI Autocomplete 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: Autocomplete
//>>group: Widgets
//>>description: Lists suggested words as the user is typing.
//>>docs: http://api.jqueryui.com/autocomplete/
//>>demos: http://jqueryui.com/autocomplete/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/autocomplete.css
//>>css.theme: ../../themes/base/theme.css
$.widget( "ui.autocomplete", {
version: "1.12.1",
defaultElement: "<input>",
options: {
appendTo: null,
autoFocus: false,
delay: 300,
minLength: 1,
position: {
my: "left top",
at: "left bottom",
collision: "none"
},
source: null,
// Callbacks
change: null,
close: null,
focus: null,
open: null,
response: null,
search: null,
select: null
},
requestIndex: 0,
pending: 0,
_create: function() {
// Some browsers only repeat keydown events, not keypress events,
// so we use the suppressKeyPress flag to determine if we've already
// handled the keydown event. #7269
// Unfortunately the code for & in keypress is the same as the up arrow,
// so we use the suppressKeyPressRepeat flag to avoid handling keypress
// events when we know the keydown event was used to modify the
// search term. #7799
var suppressKeyPress, suppressKeyPressRepeat, suppressInput,
nodeName = this.element[ 0 ].nodeName.toLowerCase(),
isTextarea = nodeName === "textarea",
isInput = nodeName === "input";
// Textareas are always multi-line
// Inputs are always single-line, even if inside a contentEditable element
// IE also treats inputs as contentEditable
// All other element types are determined by whether or not they're contentEditable
this.isMultiLine = isTextarea || !isInput && this._isContentEditable( this.element );
this.valueMethod = this.element[ isTextarea || isInput ? "val" : "text" ];
this.isNewMenu = true;
this._addClass( "ui-autocomplete-input" );
this.element.attr( "autocomplete", "off" );
this._on( this.element, {
keydown: function( event ) {
if ( this.element.prop( "readOnly" ) ) {
suppressKeyPress = true;
suppressInput = true;
suppressKeyPressRepeat = true;
return;
}
suppressKeyPress = false;
suppressInput = false;
suppressKeyPressRepeat = false;
var keyCode = $.ui.keyCode;
switch ( event.keyCode ) {
case keyCode.PAGE_UP:
suppressKeyPress = true;
this._move( "previousPage", event );
break;
case keyCode.PAGE_DOWN:
suppressKeyPress = true;
this._move( "nextPage", event );
break;
case keyCode.UP:
suppressKeyPress = true;
this._keyEvent( "previous", event );
break;
case keyCode.DOWN:
suppressKeyPress = true;
this._keyEvent( "next", event );
break;
case keyCode.ENTER:
// when menu is open and has focus
if ( this.menu.active ) {
// #6055 - Opera still allows the keypress to occur
// which causes forms to submit
suppressKeyPress = true;
event.preventDefault();
this.menu.select( event );
}
break;
case keyCode.TAB:
if ( this.menu.active ) {
this.menu.select( event );
}
break;
case keyCode.ESCAPE:
if ( this.menu.element.is( ":visible" ) ) {
if ( !this.isMultiLine ) {
this._value( this.term );
}
this.close( event );
// Different browsers have different default behavior for escape
// Single press can mean undo or clear
// Double press in IE means clear the whole form
event.preventDefault();
}
break;
default:
suppressKeyPressRepeat = true;
// search timeout should be triggered before the input value is changed
this._searchTimeout( event );
break;
}
},
keypress: function( event ) {
if ( suppressKeyPress ) {
suppressKeyPress = false;
if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) {
event.preventDefault();
}
return;
}
if ( suppressKeyPressRepeat ) {
return;
}
// Replicate some key handlers to allow them to repeat in Firefox and Opera
var keyCode = $.ui.keyCode;
switch ( event.keyCode ) {
case keyCode.PAGE_UP:
this._move( "previousPage", event );
break;
case keyCode.PAGE_DOWN:
this._move( "nextPage", event );
break;
case keyCode.UP:
this._keyEvent( "previous", event );
break;
case keyCode.DOWN:
this._keyEvent( "next", event );
break;
}
},
input: function( event ) {
if ( suppressInput ) {
suppressInput = false;
event.preventDefault();
return;
}
this._searchTimeout( event );
},
focus: function() {
this.selectedItem = null;
this.previous = this._value();
},
blur: function( event ) {
if ( this.cancelBlur ) {
delete this.cancelBlur;
return;
}
clearTimeout( this.searching );
this.close( event );
this._change( event );
}
} );
this._initSource();
this.menu = $( "<ul>" )
.appendTo( this._appendTo() )
.menu( {
// disable ARIA support, the live region takes care of that
role: null
} )
.hide()
.menu( "instance" );
this._addClass( this.menu.element, "ui-autocomplete", "ui-front" );
this._on( this.menu.element, {
mousedown: function( event ) {
// prevent moving focus out of the text field
event.preventDefault();
// IE doesn't prevent moving focus even with event.preventDefault()
// so we set a flag to know when we should ignore the blur event
this.cancelBlur = true;
this._delay( function() {
delete this.cancelBlur;
// Support: IE 8 only
// Right clicking a menu item or selecting text from the menu items will
// result in focus moving out of the input. However, we've already received
// and ignored the blur event because of the cancelBlur flag set above. So
// we restore focus to ensure that the menu closes properly based on the user's
// next actions.
if ( this.element[ 0 ] !== $.ui.safeActiveElement( this.document[ 0 ] ) ) {
this.element.trigger( "focus" );
}
} );
},
menufocus: function( event, ui ) {
var label, item;
// support: Firefox
// Prevent accidental activation of menu items in Firefox (#7024 #9118)
if ( this.isNewMenu ) {
this.isNewMenu = false;
if ( event.originalEvent && /^mouse/.test( event.originalEvent.type ) ) {
this.menu.blur();
this.document.one( "mousemove", function() {
$( event.target ).trigger( event.originalEvent );
} );
return;
}
}
item = ui.item.data( "ui-autocomplete-item" );
if ( false !== this._trigger( "focus", event, { item: item } ) ) {
// use value to match what will end up in the input, if it was a key event
if ( event.originalEvent && /^key/.test( event.originalEvent.type ) ) {
this._value( item.value );
}
}
// Announce the value in the liveRegion
label = ui.item.attr( "aria-label" ) || item.value;
if ( label && $.trim( label ).length ) {
this.liveRegion.children().hide();
$( "<div>" ).text( label ).appendTo( this.liveRegion );
}
},
menuselect: function( event, ui ) {
var item = ui.item.data( "ui-autocomplete-item" ),
previous = this.previous;
// Only trigger when focus was lost (click on menu)
if ( this.element[ 0 ] !== $.ui.safeActiveElement( this.document[ 0 ] ) ) {
this.element.trigger( "focus" );
this.previous = previous;
// #6109 - IE triggers two focus events and the second
// is asynchronous, so we need to reset the previous
// term synchronously and asynchronously :-(
this._delay( function() {
this.previous = previous;
this.selectedItem = item;
} );
}
if ( false !== this._trigger( "select", event, { item: item } ) ) {
this._value( item.value );
}
// reset the term after the select event
// this allows custom select handling to work properly
this.term = this._value();
this.close( event );
this.selectedItem = item;
}
} );
this.liveRegion = $( "<div>", {
role: "status",
"aria-live": "assertive",
"aria-relevant": "additions"
} )
.appendTo( this.document[ 0 ].body );
this._addClass( this.liveRegion, null, "ui-helper-hidden-accessible" );
// Turning off autocomplete prevents the browser from remembering the
// value when navigating through history, so we re-enable autocomplete
// if the page is unloaded before the widget is destroyed. #7790
this._on( this.window, {
beforeunload: function() {
this.element.removeAttr( "autocomplete" );
}
} );
},
_destroy: function() {
clearTimeout( this.searching );
this.element.removeAttr( "autocomplete" );
this.menu.element.remove();
this.liveRegion.remove();
},
_setOption: function( key, value ) {
this._super( key, value );
if ( key === "source" ) {
this._initSource();
}
if ( key === "appendTo" ) {
this.menu.element.appendTo( this._appendTo() );
}
if ( key === "disabled" && value && this.xhr ) {
this.xhr.abort();
}
},
_isEventTargetInWidget: function( event ) {
var menuElement = this.menu.element[ 0 ];
return event.target === this.element[ 0 ] ||
event.target === menuElement ||
$.contains( menuElement, event.target );
},
_closeOnClickOutside: function( event ) {
if ( !this._isEventTargetInWidget( event ) ) {
this.close();
}
},
_appendTo: function() {
var element = this.options.appendTo;
if ( element ) {
element = element.jquery || element.nodeType ?
$( element ) :
this.document.find( element ).eq( 0 );
}
if ( !element || !element[ 0 ] ) {
element = this.element.closest( ".ui-front, dialog" );
}
if ( !element.length ) {
element = this.document[ 0 ].body;
}
return element;
},
_initSource: function() {
var array, url,
that = this;
if ( $.isArray( this.options.source ) ) {
array = this.options.source;
this.source = function( request, response ) {
response( $.ui.autocomplete.filter( array, request.term ) );
};
} else if ( typeof this.options.source === "string" ) {
url = this.options.source;
this.source = function( request, response ) {
if ( that.xhr ) {
that.xhr.abort();
}
that.xhr = $.ajax( {
url: url,
data: request,
dataType: "json",
success: function( data ) {
response( data );
},
error: function() {
response( [] );
}
} );
};
} else {
this.source = this.options.source;
}
},
_searchTimeout: function( event ) {
clearTimeout( this.searching );
this.searching = this._delay( function() {
// Search if the value has changed, or if the user retypes the same value (see #7434)
var equalValues = this.term === this._value(),
menuVisible = this.menu.element.is( ":visible" ),
modifierKey = event.altKey || event.ctrlKey || event.metaKey || event.shiftKey;
if ( !equalValues || ( equalValues && !menuVisible && !modifierKey ) ) {
this.selectedItem = null;
this.search( null, event );
}
}, this.options.delay );
},
search: function( value, event ) {
value = value != null ? value : this._value();
// Always save the actual value, not the one passed as an argument
this.term = this._value();
if ( value.length < this.options.minLength ) {
return this.close( event );
}
if ( this._trigger( "search", event ) === false ) {
return;
}
return this._search( value );
},
_search: function( value ) {
this.pending++;
this._addClass( "ui-autocomplete-loading" );
this.cancelSearch = false;
this.source( { term: value }, this._response() );
},
_response: function() {
var index = ++this.requestIndex;
return $.proxy( function( content ) {
if ( index === this.requestIndex ) {
this.__response( content );
}
this.pending--;
if ( !this.pending ) {
this._removeClass( "ui-autocomplete-loading" );
}
}, this );
},
__response: function( content ) {
if ( content ) {
content = this._normalize( content );
}
this._trigger( "response", null, { content: content } );
if ( !this.options.disabled && content && content.length && !this.cancelSearch ) {
this._suggest( content );
this._trigger( "open" );
} else {
// use ._close() instead of .close() so we don't cancel future searches
this._close();
}
},
close: function( event ) {
this.cancelSearch = true;
this._close( event );
},
_close: function( event ) {
// Remove the handler that closes the menu on outside clicks
this._off( this.document, "mousedown" );
if ( this.menu.element.is( ":visible" ) ) {
this.menu.element.hide();
this.menu.blur();
this.isNewMenu = true;
this._trigger( "close", event );
}
},
_change: function( event ) {
if ( this.previous !== this._value() ) {
this._trigger( "change", event, { item: this.selectedItem } );
}
},
_normalize: function( items ) {
// assume all items have the right format when the first item is complete
if ( items.length && items[ 0 ].label && items[ 0 ].value ) {
return items;
}
return $.map( items, function( item ) {
if ( typeof item === "string" ) {
return {
label: item,
value: item
};
}
return $.extend( {}, item, {
label: item.label || item.value,
value: item.value || item.label
} );
} );
},
_suggest: function( items ) {
var ul = this.menu.element.empty();
this._renderMenu( ul, items );
this.isNewMenu = true;
this.menu.refresh();
// Size and position menu
ul.show();
this._resizeMenu();
ul.position( $.extend( {
of: this.element
}, this.options.position ) );
if ( this.options.autoFocus ) {
this.menu.next();
}
// Listen for interactions outside of the widget (#6642)
this._on( this.document, {
mousedown: "_closeOnClickOutside"
} );
},
_resizeMenu: function() {
var ul = this.menu.element;
ul.outerWidth( Math.max(
// Firefox wraps long text (possibly a rounding bug)
// so we add 1px to avoid the wrapping (#7513)
ul.width( "" ).outerWidth() + 1,
this.element.outerWidth()
) );
},
_renderMenu: function( ul, items ) {
var that = this;
$.each( items, function( index, item ) {
that._renderItemData( ul, item );
} );
},
_renderItemData: function( ul, item ) {
return this._renderItem( ul, item ).data( "ui-autocomplete-item", item );
},
_renderItem: function( ul, item ) {
return $( "<li>" )
.append( $( "<div>" ).text( item.label ) )
.appendTo( ul );
},
_move: function( direction, event ) {
if ( !this.menu.element.is( ":visible" ) ) {
this.search( null, event );
return;
}
if ( this.menu.isFirstItem() && /^previous/.test( direction ) ||
this.menu.isLastItem() && /^next/.test( direction ) ) {
if ( !this.isMultiLine ) {
this._value( this.term );
}
this.menu.blur();
return;
}
this.menu[ direction ]( event );
},
widget: function() {
return this.menu.element;
},
_value: function() {
return this.valueMethod.apply( this.element, arguments );
},
_keyEvent: function( keyEvent, event ) {
if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) {
this._move( keyEvent, event );
// Prevents moving cursor to beginning/end of the text field in some browsers
event.preventDefault();
}
},
// Support: Chrome <=50
// We should be able to just use this.element.prop( "isContentEditable" )
// but hidden elements always report false in Chrome.
// https://code.google.com/p/chromium/issues/detail?id=313082
_isContentEditable: function( element ) {
if ( !element.length ) {
return false;
}
var editable = element.prop( "contentEditable" );
if ( editable === "inherit" ) {
return this._isContentEditable( element.parent() );
}
return editable === "true";
}
} );
$.extend( $.ui.autocomplete, {
escapeRegex: function( value ) {
return value.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" );
},
filter: function( array, term ) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex( term ), "i" );
return $.grep( array, function( value ) {
return matcher.test( value.label || value.value || value );
} );
}
} );
// Live region extension, adding a `messages` option
// NOTE: This is an experimental API. We are still investigating
// a full solution for string manipulation and internationalization.
$.widget( "ui.autocomplete", $.ui.autocomplete, {
options: {
messages: {
noResults: "No search results.",
results: function( amount ) {
return amount + ( amount > 1 ? " results are" : " result is" ) +
" available, use up and down arrow keys to navigate.";
}
}
},
__response: function( content ) {
var message;
this._superApply( arguments );
if ( this.options.disabled || this.cancelSearch ) {
return;
}
if ( content && content.length ) {
message = this.options.messages.results( content.length );
} else {
message = this.options.messages.noResults;
}
this.liveRegion.children().hide();
$( "<div>" ).text( message ).appendTo( this.liveRegion );
}
} );
var widgetsAutocomplete = $.ui.autocomplete;
})); | {
"pile_set_name": "Github"
} |
/**
* @file include/retdec/llvmir2hll/ir/bit_xor_op_expr.h
* @brief A bit-xor operator.
* @copyright (c) 2017 Avast Software, licensed under the MIT license
*/
#ifndef RETDEC_LLVMIR2HLL_IR_BIT_XOR_OP_EXPR_H
#define RETDEC_LLVMIR2HLL_IR_BIT_XOR_OP_EXPR_H
#include "retdec/llvmir2hll/ir/binary_op_expr.h"
#include "retdec/llvmir2hll/support/smart_ptr.h"
namespace retdec {
namespace llvmir2hll {
class Expression;
class Visitor;
/**
* @brief A bit-xor operator.
*
* This operator has the same meaning as the '^' operator in C.
*
* Instances of this class have reference object semantics.
*/
class BitXorOpExpr: public BinaryOpExpr {
public:
static ShPtr<BitXorOpExpr> create(ShPtr<Expression> op1,
ShPtr<Expression> op2);
virtual bool isEqualTo(ShPtr<Value> otherValue) const override;
virtual ShPtr<Value> clone() override;
/// @name Visitor Interface
/// @{
virtual void accept(Visitor *v) override;
/// @}
private:
// Since instances are created by calling the static function create(), the
// constructor can be private.
BitXorOpExpr(ShPtr<Expression> op1, ShPtr<Expression> op2);
};
} // namespace llvmir2hll
} // namespace retdec
#endif
| {
"pile_set_name": "Github"
} |
/*
KLayout Layout Viewer
Copyright (C) 2006-2020 Matthias Koefferlein
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.
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.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef HDR_layNetlistBrowser
#define HDR_layNetlistBrowser
#include "layPlugin.h"
#include "layColorPalette.h"
#include "ui_NetlistBrowserConfigPage.h"
#include "ui_NetlistBrowserConfigPage2.h"
#include "dbTrans.h"
#include <algorithm>
namespace lay
{
struct NetlistBrowserConfig
{
enum net_window_type { DontChange = 0, FitNet, Center, CenterSize };
};
class NetlistBrowserConfigPage
: public lay::ConfigPage,
private Ui::NetlistBrowserConfigPage
{
Q_OBJECT
public:
NetlistBrowserConfigPage (QWidget *parent);
virtual void setup (lay::Dispatcher *root);
virtual void commit (lay::Dispatcher *root);
public slots:
void window_changed (int);
};
class NetlistBrowserConfigPage2
: public lay::ConfigPage,
private Ui::NetlistBrowserConfigPage2
{
Q_OBJECT
public:
NetlistBrowserConfigPage2 (QWidget *parent);
virtual void setup (lay::Dispatcher *root);
virtual void commit (lay::Dispatcher *root);
public slots:
void color_button_clicked ();
private:
void update_colors ();
lay::ColorPalette m_palette;
};
class NetlistBrowserWindowModeConverter
{
public:
void from_string (const std::string &value, lay::NetlistBrowserConfig::net_window_type &mode);
std::string to_string (lay::NetlistBrowserConfig::net_window_type mode);
};
}
#endif
| {
"pile_set_name": "Github"
} |
%
% Scheduling (Building a house) in MiniZinc.
%
% This problem is from Mozart/Oz
% http://www.mozart-oz.org/home/doc/fdt/node47.html#section.scheduling.house
% """
% The task names, their description, duration (in days) and the company in
% charge are given in Figure 11.1. For example, b denotes the task involved
% with the carpentry for the roof. This task lasts for 3 days. Task a must be
% finished before the work for task b is started (indicated by the column
% Predecessor). The company in charge for task b is House Inc. The overall
% goal is to build the house as quickly as possible.
%
% Task Description Duration Predecessor Company
% a Erecting Walls 7 none Construction Inc.
% b Carpentry for Roof 3 a House Inc.
% c Roof 1 b House Inc.
% d Installations 8 a Construction Inc.
% e Facade Painting 2 c, d Construction Inc.
% f Windows 1 c, d House Inc.
% g Garden 1 c, d House Inc.
% h Ceilings 3 a Construction Inc.
% i Painting 2 f, h Builder Corp.
% j Moving in 1 i Builder Corp.
% """
%
% This MiniZinc model was created by Hakan Kjellerstrand, [email protected]
% See also my MiniZinc page: http://www.hakank.org/minizinc
%
include "globals.mzn";
% For output[]
int: num_tasks = 10;
array[1..num_tasks] of string: tasks =
["erecting_walls",
"carpentry_for_roof",
"roof",
"installations",
"facade_painting",
"windows",
"garden",
"ceilings",
"painting",
"moving_in"];
% for the precedences
int: erecting_walls = 1;
int: carpentry_for_roof = 2;
int: roof = 3;
int: installations = 4;
int: facade_painting = 5;
int: windows = 6;
int: garden = 7;
int: ceilings = 8;
int: painting = 9;
int: moving_in = 10;
array[1..num_tasks] of int: duration = [ 7, 3, 1, 8, 2, 1, 1, 3, 2, 1];
array[1..num_tasks] of int: height = [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1];
int: total_duration = sum(t in 1..num_tasks) (duration[t]);
% precendeces
int: num_precedences = 13;
array[1..num_precedences, 1..2] of int: precedences;
% variables
array[1..num_tasks] of var 1..total_duration: start;
array[1..num_tasks] of var 1..total_duration: end;
var 1..3: limitx;
var 1..total_duration: makespan;
% handle the precedences
predicate prec(int:x , int: y, array[int] of var int: s, array[int] of var int: d) =
s[x] + d[x] <= s[y]
;
% solve minimize makespan;
solve :: int_search(
start ++ [makespan, limitx],
% start ++ [makespan],
first_fail,
indomain_min,
complete)
% satisfy;
minimize makespan;
constraint
% to be minimized
maximum(makespan, end)/\
cumulative(start, duration, height, limitx) /\
forall(t in 1..num_tasks) (
end[t] = start[t] + duration[t]
)
/\
% precedences
forall(p in 1..num_precedences) (
prec(precedences[p,1], precedences[p,2], start, duration)
)
;
precedences = array2d(1..num_precedences, 1..2,
[
% a b
erecting_walls, carpentry_for_roof,
% b c
carpentry_for_roof, roof,
% a d
erecting_walls, installations,
% c e
roof, facade_painting,
% d e
installations, facade_painting,
% c f
roof, windows,
% d f
installations, windows,
% c g
roof, garden,
% d g
installations, garden,
% a h
erecting_walls, ceilings,
% f i
windows, painting,
% h i
ceilings, painting,
% i j
painting, moving_in
]);
% Nice output, only with the minizinc solver
output [
"makespan: " ++ show(makespan) ++ "\n"
] ++
[
show(tasks[t]) ++ ": " ++ show(start[t]) ++ " - " ++ show(duration[t]) ++ " --> " ++ show(start[t] + duration[t]) ++ "\n"
| t in 1..num_tasks
] ++ ["\n"];
| {
"pile_set_name": "Github"
} |
module.exports = {
'add': require('./add'),
'ceil': require('./ceil'),
'divide': require('./divide'),
'floor': require('./floor'),
'max': require('./max'),
'maxBy': require('./maxBy'),
'mean': require('./mean'),
'meanBy': require('./meanBy'),
'min': require('./min'),
'minBy': require('./minBy'),
'multiply': require('./multiply'),
'round': require('./round'),
'subtract': require('./subtract'),
'sum': require('./sum'),
'sumBy': require('./sumBy')
};
| {
"pile_set_name": "Github"
} |
//
// DragPopUpButton.m
// SmartPush
//
// Created by Jakey on 2017/2/22.
// Copyright © 2017年 www.skyfox.org. All rights reserved.
//
#import "DragPopUpButton.h"
@implementation DragPopUpButton
- (void)awakeFromNib {
[self registerForDraggedTypes:@[NSFilenamesPboardType]];
}
- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
{
NSPasteboard *pboard = [sender draggingPasteboard];
if ( [[pboard types] containsObject:NSURLPboardType] ) {
NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
if (files.count <= 0) {
return NO;
}
if (_dragPopUpButtonDragEnd) {
_dragPopUpButtonDragEnd([files objectAtIndex:0]);
}
}
return YES;
}
- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender {
if (!self.isEnabled) return NSDragOperationNone;
NSPasteboard *pboard;
NSDragOperation sourceDragMask;
sourceDragMask = [sender draggingSourceOperationMask];
pboard = [sender draggingPasteboard];
if ( [[pboard types] containsObject:NSColorPboardType] ) {
if (sourceDragMask & NSDragOperationCopy) {
return NSDragOperationCopy;
}
}
if ( [[pboard types] containsObject:NSFilenamesPboardType] ) {
if (sourceDragMask & NSDragOperationCopy) {
return NSDragOperationCopy;
}
}
return NSDragOperationNone;
}
-(void)dragPopUpButtonDragEnd:(DragPopUpButtonDragEnd)dragPopUpButtonDragEnd{
_dragPopUpButtonDragEnd = [dragPopUpButtonDragEnd copy];
}
@end
| {
"pile_set_name": "Github"
} |
// Copyright 2017-present the Material Components for iOS 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.
#import "MDCFlexibleHeaderColorThemer.h"
@implementation MDCFlexibleHeaderColorThemer
+ (void)applySemanticColorScheme:(nonnull id<MDCColorScheming>)colorScheme
toFlexibleHeaderView:(nonnull MDCFlexibleHeaderView *)flexibleHeaderView {
flexibleHeaderView.backgroundColor = colorScheme.primaryColor;
}
+ (void)applySurfaceVariantWithColorScheme:(nonnull id<MDCColorScheming>)colorScheme
toFlexibleHeaderView:(nonnull MDCFlexibleHeaderView *)flexibleHeaderView {
flexibleHeaderView.backgroundColor = colorScheme.surfaceColor;
}
+ (void)applyColorScheme:(id<MDCColorScheme>)colorScheme
toFlexibleHeaderView:(MDCFlexibleHeaderView *)flexibleHeaderView {
flexibleHeaderView.backgroundColor = colorScheme.primaryColor;
}
+ (void)applyColorScheme:(id<MDCColorScheme>)colorScheme
toMDCFlexibleHeaderController:(MDCFlexibleHeaderViewController *)flexibleHeaderController {
flexibleHeaderController.headerView.backgroundColor = colorScheme.primaryColor;
}
@end
| {
"pile_set_name": "Github"
} |
// RUN: %clang_cc1 -triple x86_64-apple-darwin9.0.0 -fsyntax-only -verify %s
@protocol P
- (void)proto_method __attribute__((availability(macosx,introduced=10.1,deprecated=10.2))); // expected-note 2 {{method 'proto_method' declared here}}
@end
@interface A <P>
- (void)method __attribute__((availability(macosx,introduced=10.1,deprecated=10.2))); // expected-note {{method 'method' declared here}}
- (void)overridden __attribute__((availability(macosx,introduced=10.3))); // expected-note{{overridden method is here}}
- (void)overridden2 __attribute__((availability(macosx,introduced=10.3)));
- (void)overridden3 __attribute__((availability(macosx,deprecated=10.3)));
- (void)overridden4 __attribute__((availability(macosx,deprecated=10.3))); // expected-note{{overridden method is here}}
- (void)overridden5 __attribute__((availability(macosx,unavailable)));
- (void)overridden6 __attribute__((availability(macosx,introduced=10.3))); // expected-note{{overridden method is here}}
@end
// rdar://11475360
@interface B : A
- (void)method; // NOTE: we expect 'method' to *not* inherit availability.
- (void)overridden __attribute__((availability(macosx,introduced=10.4))); // expected-warning{{overriding method introduced after overridden method on OS X (10.4 vs. 10.3)}}
- (void)overridden2 __attribute__((availability(macosx,introduced=10.2)));
- (void)overridden3 __attribute__((availability(macosx,deprecated=10.4)));
- (void)overridden4 __attribute__((availability(macosx,deprecated=10.2))); // expected-warning{{overriding method deprecated before overridden method on OS X (10.3 vs. 10.2)}}
- (void)overridden5 __attribute__((availability(macosx,introduced=10.3)));
- (void)overridden6 __attribute__((availability(macosx,unavailable))); // expected-warning{{overriding method cannot be unavailable on OS X when its overridden method is available}}
@end
void f(A *a, B *b) {
[a method]; // expected-warning{{'method' is deprecated: first deprecated in OS X 10.2}}
[b method]; // no-warning
[a proto_method]; // expected-warning{{'proto_method' is deprecated: first deprecated in OS X 10.2}}
[b proto_method]; // expected-warning{{'proto_method' is deprecated: first deprecated in OS X 10.2}}
}
// Test case for <rdar://problem/11627873>. Warn about
// using a deprecated method when that method is re-implemented in a
// subclass where the redeclared method is not deprecated.
@interface C
- (void) method __attribute__((availability(macosx,introduced=10.1,deprecated=10.2))); // expected-note {{method 'method' declared here}}
@end
@interface D : C
- (void) method;
@end
@interface E : D
- (void) method;
@end
@implementation D
- (void) method {
[super method]; // expected-warning {{'method' is deprecated: first deprecated in OS X 10.2}}
}
@end
@implementation E
- (void) method {
[super method]; // no-warning
}
@end
| {
"pile_set_name": "Github"
} |
package staticcheck
import (
"fmt"
"go/constant"
"go/types"
"net"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
"time"
"unicode/utf8"
"golang.org/x/tools/go/analysis"
"honnef.co/go/tools/code"
"honnef.co/go/tools/ir"
)
const (
MsgInvalidHostPort = "invalid port or service name in host:port pair"
MsgInvalidUTF8 = "argument is not a valid UTF-8 encoded string"
MsgNonUniqueCutset = "cutset contains duplicate characters"
)
type Call struct {
Pass *analysis.Pass
Instr ir.CallInstruction
Args []*Argument
Parent *ir.Function
invalids []string
}
func (c *Call) Invalid(msg string) {
c.invalids = append(c.invalids, msg)
}
type Argument struct {
Value Value
invalids []string
}
type Value struct {
Value ir.Value
}
func (arg *Argument) Invalid(msg string) {
arg.invalids = append(arg.invalids, msg)
}
type CallCheck func(call *Call)
func extractConsts(v ir.Value) []*ir.Const {
switch v := v.(type) {
case *ir.Const:
return []*ir.Const{v}
case *ir.MakeInterface:
return extractConsts(v.X)
default:
return nil
}
}
func ValidateRegexp(v Value) error {
for _, c := range extractConsts(v.Value) {
if c.Value == nil {
continue
}
if c.Value.Kind() != constant.String {
continue
}
s := constant.StringVal(c.Value)
if _, err := regexp.Compile(s); err != nil {
return err
}
}
return nil
}
func ValidateTimeLayout(v Value) error {
for _, c := range extractConsts(v.Value) {
if c.Value == nil {
continue
}
if c.Value.Kind() != constant.String {
continue
}
s := constant.StringVal(c.Value)
s = strings.Replace(s, "_", " ", -1)
s = strings.Replace(s, "Z", "-", -1)
_, err := time.Parse(s, s)
if err != nil {
return err
}
}
return nil
}
func ValidateURL(v Value) error {
for _, c := range extractConsts(v.Value) {
if c.Value == nil {
continue
}
if c.Value.Kind() != constant.String {
continue
}
s := constant.StringVal(c.Value)
_, err := url.Parse(s)
if err != nil {
return fmt.Errorf("%q is not a valid URL: %s", s, err)
}
}
return nil
}
func InvalidUTF8(v Value) bool {
for _, c := range extractConsts(v.Value) {
if c.Value == nil {
continue
}
if c.Value.Kind() != constant.String {
continue
}
s := constant.StringVal(c.Value)
if !utf8.ValidString(s) {
return true
}
}
return false
}
func UnbufferedChannel(v Value) bool {
// TODO(dh): this check of course misses many cases of unbuffered
// channels, such as any in phi or sigma nodes. We'll eventually
// replace this function.
val := v.Value
if ct, ok := val.(*ir.ChangeType); ok {
val = ct.X
}
mk, ok := val.(*ir.MakeChan)
if !ok {
return false
}
if k, ok := mk.Size.(*ir.Const); ok && k.Value.Kind() == constant.Int {
if v, ok := constant.Int64Val(k.Value); ok && v == 0 {
return true
}
}
return false
}
func Pointer(v Value) bool {
switch v.Value.Type().Underlying().(type) {
case *types.Pointer, *types.Interface:
return true
}
return false
}
func ConvertedFromInt(v Value) bool {
conv, ok := v.Value.(*ir.Convert)
if !ok {
return false
}
b, ok := conv.X.Type().Underlying().(*types.Basic)
if !ok {
return false
}
if (b.Info() & types.IsInteger) == 0 {
return false
}
return true
}
func validEncodingBinaryType(pass *analysis.Pass, typ types.Type) bool {
typ = typ.Underlying()
switch typ := typ.(type) {
case *types.Basic:
switch typ.Kind() {
case types.Uint8, types.Uint16, types.Uint32, types.Uint64,
types.Int8, types.Int16, types.Int32, types.Int64,
types.Float32, types.Float64, types.Complex64, types.Complex128, types.Invalid:
return true
case types.Bool:
return code.IsGoVersion(pass, 8)
}
return false
case *types.Struct:
n := typ.NumFields()
for i := 0; i < n; i++ {
if !validEncodingBinaryType(pass, typ.Field(i).Type()) {
return false
}
}
return true
case *types.Array:
return validEncodingBinaryType(pass, typ.Elem())
case *types.Interface:
// we can't determine if it's a valid type or not
return true
}
return false
}
func CanBinaryMarshal(pass *analysis.Pass, v Value) bool {
typ := v.Value.Type().Underlying()
if ttyp, ok := typ.(*types.Pointer); ok {
typ = ttyp.Elem().Underlying()
}
if ttyp, ok := typ.(interface {
Elem() types.Type
}); ok {
if _, ok := ttyp.(*types.Pointer); !ok {
typ = ttyp.Elem()
}
}
return validEncodingBinaryType(pass, typ)
}
func RepeatZeroTimes(name string, arg int) CallCheck {
return func(call *Call) {
arg := call.Args[arg]
if k, ok := arg.Value.Value.(*ir.Const); ok && k.Value.Kind() == constant.Int {
if v, ok := constant.Int64Val(k.Value); ok && v == 0 {
arg.Invalid(fmt.Sprintf("calling %s with n == 0 will return no results, did you mean -1?", name))
}
}
}
}
func validateServiceName(s string) bool {
if len(s) < 1 || len(s) > 15 {
return false
}
if s[0] == '-' || s[len(s)-1] == '-' {
return false
}
if strings.Contains(s, "--") {
return false
}
hasLetter := false
for _, r := range s {
if (r >= 'A' && r <= 'Z') || (r >= 'a' && r <= 'z') {
hasLetter = true
continue
}
if r >= '0' && r <= '9' {
continue
}
return false
}
return hasLetter
}
func validatePort(s string) bool {
n, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return validateServiceName(s)
}
return n >= 0 && n <= 65535
}
func ValidHostPort(v Value) bool {
for _, k := range extractConsts(v.Value) {
if k.Value == nil {
continue
}
if k.Value.Kind() != constant.String {
continue
}
s := constant.StringVal(k.Value)
_, port, err := net.SplitHostPort(s)
if err != nil {
return false
}
// TODO(dh): check hostname
if !validatePort(port) {
return false
}
}
return true
}
// ConvertedFrom reports whether value v was converted from type typ.
func ConvertedFrom(v Value, typ string) bool {
change, ok := v.Value.(*ir.ChangeType)
return ok && code.IsType(change.X.Type(), typ)
}
func UniqueStringCutset(v Value) bool {
for _, c := range extractConsts(v.Value) {
if c.Value == nil {
continue
}
if c.Value.Kind() != constant.String {
continue
}
s := constant.StringVal(c.Value)
rs := runeSlice(s)
if len(rs) < 2 {
continue
}
sort.Sort(rs)
for i, r := range rs[1:] {
if rs[i] == r {
return false
}
}
}
return true
}
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.