code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Views extends Application { /** * Index Page for this controller. * * Maps to the following URL * http://example.com/ * - or - * http://example.com/welcome/index * * So any other public methods not prefixed with an underscore will * map to /welcome/<method_name> * @see https://codeigniter.com/user_guide/general/urls.html */ public function index() { $this->data['pagetitle'] = 'Ordered TODO List'; $tasks = $this->tasks->all(); // get all the tasks $this->data['content'] = 'Ok'; // so we don't need pagebody $this->data['leftside'] = $this->makePrioritizedPanel($tasks); $this->data['rightside'] = $this->makeCategorizedPanel($tasks); $this->render('template_secondary'); } function makePrioritizedPanel($tasks) { $parms = ['display_tasks' => []]; // extract the undone tasks foreach ($tasks as $task) { if ($task->status != 2) $undone[] = $task; } // order them by priority usort($undone, "orderByPriority"); // substitute the priority name foreach ($undone as $task) $task->priority = $this->app->priority($task->priority); foreach ($undone as $task) $converted[] = (array) $task; // and then pass them on $parms = ['display_tasks' => $converted]; // INSERT the next two lines $role = $this->session->userdata('userrole'); $parms['completer'] = ($role == ROLE_OWNER) ? '/views/complete' : '#'; return $this->parser->parse('by_priority', $parms, true); } function makeCategorizedPanel($tasks) { $parms = ['display_tasks' => $this->tasks->getCategorizedTasks()]; return $this->parser->parse('by_category', $parms, true); } // complete flagged items function complete() { $role = $this->session->userdata('userrole'); if ($role != ROLE_OWNER) redirect('/work'); // loop over the post fields, looking for flagged tasks foreach ($this->input->post() as $key => $value) { if (substr($key, 0, 4) == 'task') { // find the associated task $taskid = substr($key, 4); $task = $this->tasks->get($taskid); $task->status = 2; // complete $this->tasks->update($task); } } $this->index(); } } // return -1, 0, or 1 of $a's priority is higher, equal to, or lower than $b's function orderByPriority($a, $b) { if ($a->priority > $b->priority) return -1; elseif ($a->priority < $b->priority) return 1; else return 0; } ?>
MVC-todo-list/starter-todo4
application/controllers/Views.php
PHP
mit
2,696
import Ember from 'ember'; export default Ember.Route.extend({ setupController: function(controller) { controller.set('setupRoutes', [ { label: false, links: [ { href: 'heatmap.index', text: 'Setup' }, { href: 'heatmap.properties', text: 'Properties' }, { href: 'heatmap.marker', text: 'Heatmap Marker' } ] } ]); } });
Matt-Jensen/ember-cli-g-maps
tests/dummy/app/pods/heatmap/route.js
JavaScript
mit
499
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel // // 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. #if DIRECTX11_1 namespace SharpDX.WIC { public partial class ImageEncoder { /// <summary> /// Creates a new image encoder object. /// </summary> /// <param name="factory">The WIC factory.</param> /// <param name="d2dDevice">The <see cref="Direct2D1.Device" /> object on which the corresponding image encoder is created.</param> /// <msdn-id>hh880849</msdn-id> /// <unmanaged>HRESULT IWICImagingFactory2::CreateImageEncoder([In] ID2D1Device* pD2DDevice,[In] IWICImageEncoder** ppWICImageEncoder)</unmanaged> /// <unmanaged-short>IWICImagingFactory2::CreateImageEncoder</unmanaged-short> public ImageEncoder(ImagingFactory2 factory, Direct2D1.Device d2dDevice) { factory.CreateImageEncoder(d2dDevice, this); } } } #endif
wyrover/SharpDX
Source/SharpDX.Direct2D1/WIC/ImageEncoder.cs
C#
mit
1,969
#include "StdAfx.h" #include "ComponentsList.h" #include "dotNetInstallerDlg.h" CComponentsList::CComponentsList() : m_pConfiguration(NULL) , m_pExecuteCallback(NULL) { } IMPLEMENT_DYNAMIC(CComponentsList, CCheckListBox) BEGIN_MESSAGE_MAP(CComponentsList, CCheckListBox) ON_CONTROL_REFLECT(CLBN_CHKCHANGE, OnCheckChange) ON_WM_LBUTTONDBLCLK() END_MESSAGE_MAP() void CComponentsList::OnCheckChange() { this->Invalidate(); } void CComponentsList::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct) { CDC* pDC = CDC::FromHandle(lpDrawItemStruct->hDC); if (((LONG)(lpDrawItemStruct->itemID) >= 0) && (lpDrawItemStruct->itemAction & (ODA_DRAWENTIRE | ODA_SELECT))) { int cyItem = GetItemHeight(lpDrawItemStruct->itemID); BOOL fDisabled = !IsWindowEnabled() || !IsEnabled(lpDrawItemStruct->itemID); COLORREF newTextColor = fDisabled ? RGB(0, 0, 0) : GetSysColor(COLOR_WINDOWTEXT); // light gray COLORREF oldTextColor = pDC->SetTextColor(newTextColor); COLORREF newBkColor = GetSysColor(COLOR_WINDOW); COLORREF oldBkColor = pDC->SetBkColor(newBkColor); if (newTextColor == newBkColor) newTextColor = RGB(0xC0, 0xC0, 0xC0); // dark gray if (!fDisabled && ((lpDrawItemStruct->itemState & ODS_SELECTED) != 0)) { pDC->SetTextColor(GetSysColor(COLOR_HIGHLIGHTTEXT)); pDC->SetBkColor(GetSysColor(COLOR_HIGHLIGHT)); } if (m_cyText == 0) VERIFY(cyItem >= CalcMinimumItemHeight()); CString strText; GetText(lpDrawItemStruct->itemID, strText); pDC->ExtTextOut(lpDrawItemStruct->rcItem.left + 5, lpDrawItemStruct->rcItem.top + max(0, (cyItem - m_cyText) / 2), ETO_OPAQUE, &(lpDrawItemStruct->rcItem), strText, strText.GetLength(), NULL); int nCheck = GetCheck(lpDrawItemStruct->itemID); if (fDisabled && nCheck == 0) { CRect checkbox(0, lpDrawItemStruct->rcItem.top, lpDrawItemStruct->rcItem.left, lpDrawItemStruct->rcItem.bottom); COLORREF newBkColor = GetSysColor(COLOR_WINDOW); CBrush brush(newBkColor); pDC->FillRect(& checkbox, & brush); } pDC->SetTextColor(oldTextColor); pDC->SetBkColor(oldBkColor); } if ((lpDrawItemStruct->itemAction & ODA_FOCUS) != 0) pDC->DrawFocusRect(&(lpDrawItemStruct->rcItem)); } void CComponentsList::PreDrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct) { CCheckListBox::PreDrawItem(lpDrawItemStruct); } void CComponentsList::AddComponent(const ComponentPtr& component) { int id = AddString(component->description.c_str()); SetItemDataPtr(id, get(component)); if (component->checked) SetCheck(id, 1); if (component->disabled) Enable(id, 0); CDC * pDC = GetDC(); ASSERT(pDC); CSize size = pDC->GetTextExtent(component->GetDisplayName().c_str()); if ((size.cx > 0) && (GetHorizontalExtent() < size.cx)) { SetHorizontalExtent(size.cx); } ReleaseDC(pDC); } void CComponentsList::OnLButtonDblClk(UINT nFlags, CPoint point) { if (nFlags & MK_CONTROL && nFlags && MK_LBUTTON) { BOOL bOutside = false; UINT uiItem = ItemFromPoint(point, bOutside); if (! bOutside) { ComponentPtr component = m_pConfiguration->GetComponentPtr(static_cast<Component*>(GetItemDataPtr(uiItem))); Exec(component); if (m_pExecuteCallback) { m_pExecuteCallback->LoadComponentsList(false); } } } else if (nFlags & MK_SHIFT && nFlags && MK_LBUTTON) { BOOL bOutside = false; UINT uiItem = ItemFromPoint(point, bOutside); if (! bOutside) { ComponentPtr component = m_pConfiguration->GetComponentPtr(static_cast<Component*>(GetItemDataPtr(uiItem))); SetCheck(uiItem, ! GetCheck(uiItem)); } } } void CComponentsList::Exec(const ComponentPtr& component) { try { if (m_pExecuteCallback) { m_pExecuteCallback->OnExecBegin(); } LOG(L"--- Component '" << component->id << L"' (" << component->GetDisplayName() << L"): EXECUTING"); if (m_pExecuteCallback && ! m_pExecuteCallback->OnComponentExecBegin(component)) return; component->Exec(); if (m_pExecuteCallback && ! m_pExecuteCallback->OnComponentExecWait(component)) return; component->Wait(); LOG(L"*** Component '" << component->id << L"' (" << component->GetDisplayName() << L"): SUCCESS"); if (m_pExecuteCallback && ! m_pExecuteCallback->OnComponentExecSuccess(component)) return; } catch(std::exception& ex) { LOG(L"*** Component '" << component->id << L"' (" << component->GetDisplayName() << L"): ERROR - " << DVLib::string2wstring(ex.what())); DniMessageBox::Show(DVLib::string2wstring(ex.what()).c_str(), MB_OK | MB_ICONSTOP); } } void CComponentsList::SetExecuteCallback(CdotNetInstallerDlg * pExec) { m_pExecuteCallback = pExec; } void CComponentsList::Load(InstallConfiguration * pConfiguration) { m_pConfiguration = pConfiguration; }
dblock/dotnetinstaller
dotNetInstaller/ComponentsList.cpp
C++
mit
5,456
/* * Copyright (c) 2012 Maciej Walkowiak * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package pl.maciejwalkowiak.plist.handler; import pl.maciejwalkowiak.plist.PlistSerializerImpl; import pl.maciejwalkowiak.plist.XMLHelper; import java.util.Map; /** * @author Maciej Walkowiak */ public class MapHandler extends AbstractHandler { public MapHandler(PlistSerializerImpl plistSerializer) { super(plistSerializer); } @Override String doHandle(Object object) { Map<String, Object> map = (Map<String, Object>) object; StringBuilder result = new StringBuilder(); for (Map.Entry<String, Object> entry : map.entrySet()) { result.append(XMLHelper.wrap(plistSerializer.getNamingStrategy().fieldNameToKey(entry.getKey())).with("key")); result.append(plistSerializer.serialize(entry.getValue())); } return XMLHelper.wrap(result).with("dict"); } public boolean supports(Object object) { return object instanceof Map; } }
bugix/java-plist-serializer
src/main/java/pl/maciejwalkowiak/plist/handler/MapHandler.java
Java
mit
1,980
package org.deviceconnect.android.libmedia.streaming.mpeg2ts; /** * フレームのタイプを定義します. */ enum FrameType { /** * 音声のフレームタイプを定義. */ AUDIO, /** * 映像のフレームタイプを定義. */ VIDEO, /** * 音声と映像の混合のフレームタイプを定義. */ MIXED }
DeviceConnect/DeviceConnect-Android
dConnectSDK/dConnectLibStreaming/libmedia/src/main/java/org/deviceconnect/android/libmedia/streaming/mpeg2ts/FrameType.java
Java
mit
380
package mariculture.core.helpers; import java.util.Random; import mariculture.core.tile.base.TileMultiBlock; import mariculture.core.util.Fluids; import mariculture.core.util.IItemDropBlacklist; import net.minecraft.block.Block; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.init.Blocks; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraft.world.WorldServer; import net.minecraftforge.common.util.FakePlayer; import net.minecraftforge.common.util.ForgeDirection; public class BlockHelper { public static boolean isWater(World world, int x, int y, int z) { return world.getBlock(x, y, z) == Blocks.water; } public static boolean isHPWater(World world, int x, int y, int z) { return world.getBlock(x, y, z) == Fluids.getFluidBlock("hp_water"); } public static boolean isLava(World world, int x, int y, int z) { return world.getBlock(x, y, z) == Blocks.lava; } public static boolean isFishLiveable(World world, int x, int y, int z) { if (world.provider.isHellWorld) return isLava(world, x, y, z); return isWater(world, x, y, z); } public static boolean isFishable(World world, int x, int y, int z) { return isWater(world, x, y, z) || isLava(world, x, y, z) && world.provider.isHellWorld; } public static boolean isAir(World world, int x, int y, int z) { if (world.getChunkProvider().chunkExists(x >> 4, z >> 4)) { try { return world.isAirBlock(x, y, z); } catch (Exception e) {} } return false; } public static void setBlock(World world, int x, int y, int z, Block block, int meta) { if (world.getChunkProvider().chunkExists(x >> 4, z >> 4)) { try { world.setBlock(x, y, z, block, meta, 3); } catch (Exception e) {} } } public static Block getBlock(World world, int x, int y, int z) { if (world.getChunkProvider().chunkExists(x >> 4, z >> 4)) { try { return world.getBlock(x, y, z); } catch (Exception e) {} } return Blocks.stone; } public static int getMeta(World world, int x, int y, int z) { if (world.getChunkProvider().chunkExists(x >> 4, z >> 4)) { try { return world.getBlockMetadata(x, y, z); } catch (Exception e) {} } return -1; } public static boolean chunkExists(World world, int x, int z) { return world.getChunkProvider().chunkExists(x >> 4, z >> 4); } public static String getName(ItemStack stack) { return stack != null ? stack.getItem().getItemStackDisplayName(stack) : ""; } public static String getName(TileEntity tile) { return tile != null ? getName(new ItemStack(tile.getBlockType(), 1, tile.getBlockMetadata())) : ""; } public static ForgeDirection rotate(ForgeDirection dir, int num) { if (dir == ForgeDirection.NORTH) return ForgeDirection.EAST; if (dir == ForgeDirection.EAST) return num == 2 ? ForgeDirection.NORTH : ForgeDirection.SOUTH; if (dir == ForgeDirection.SOUTH) return ForgeDirection.WEST; if (dir == ForgeDirection.WEST) return num == 6 ? ForgeDirection.UP : ForgeDirection.NORTH; if (dir == ForgeDirection.UP) return ForgeDirection.DOWN; return ForgeDirection.NORTH; } public static ForgeDirection rotate(ForgeDirection dir) { return rotate(dir, 6); } public static void dropItems(World world, int x, int y, int z) { Random rand = world.rand; TileEntity tile = world.getTileEntity(x, y, z); if (!(tile instanceof IInventory)) return; if (tile instanceof TileMultiBlock) { TileMultiBlock multi = (TileMultiBlock) tile; if (multi.master != null) if (!multi.isMaster()) return; } IInventory inventory = (IInventory) tile; for (int i = 0; i < inventory.getSizeInventory(); i++) { boolean drop = true; if (tile instanceof IItemDropBlacklist) { drop = ((IItemDropBlacklist) tile).doesDrop(i); } if (drop) { ItemStack item = inventory.getStackInSlot(i); if (item != null && item.stackSize > 0) { item = item.copy(); inventory.decrStackSize(i, 1); float rx = rand.nextFloat() * 0.6F + 0.1F; float ry = rand.nextFloat() * 0.6F + 0.1F; float rz = rand.nextFloat() * 0.6F + 0.1F; EntityItem entity_item = new EntityItem(world, x + rx, y + ry, z + rz, new ItemStack(item.getItem(), item.stackSize, item.getItemDamage())); if (item.hasTagCompound()) { entity_item.getEntityItem().setTagCompound((NBTTagCompound) item.getTagCompound().copy()); } float factor = 0.05F; entity_item.motionX = rand.nextGaussian() * factor; entity_item.motionY = rand.nextGaussian() * factor + 0.2F; entity_item.motionZ = rand.nextGaussian() * factor; world.spawnEntityInWorld(entity_item); item.stackSize = 0; } } } } private static boolean removeBlock(World world, EntityPlayerMP player, int x, int y, int z) { Block block = world.getBlock(x, y, z); int l = world.getBlockMetadata(x, y, z); block.onBlockHarvested(world, x, y, z, l, player); boolean flag = block.removedByPlayer(world, player, x, y, z, true); if (flag) { block.onBlockDestroyedByPlayer(world, x, y, z, l); } return flag; } public static void destroyBlock(World world, int x, int y, int z) { destroyBlock(world, x, y, z, null, null); } public static void destroyBlock(World world, int x, int y, int z, Block required, ItemStack held) { if (!(world instanceof WorldServer)) return; Block block = world.getBlock(x, y, z); if (required != null && block != required) return; if (block.getBlockHardness(world, x, y, z) < 0.0F) return; FakePlayer player = PlayerHelper.getFakePlayer(world); if (player != null && held != null) { player.setCurrentItemOrArmor(0, held.copy()); } int l = world.getBlockMetadata(x, y, z); world.playAuxSFXAtEntity(player, 2001, x, y, z, Block.getIdFromBlock(block) + (world.getBlockMetadata(x, y, z) << 12)); boolean flag = removeBlock(world, player, x, y, z); if (flag) { block.harvestBlock(world, player, x, y, z, l); } return; } }
svgorbunov/Mariculture
src/main/java/mariculture/core/helpers/BlockHelper.java
Java
mit
7,041
(function(){ "use strict"; KC3StrategyTabs.aircraft = new KC3StrategyTab("aircraft"); KC3StrategyTabs.aircraft.definition = { tabSelf: KC3StrategyTabs.aircraft, squadNames: {}, _items: {}, _holders: {}, _slotNums: {}, /* INIT Prepares static data needed ---------------------------------*/ init :function(){ }, /* RELOAD Prepares latest player data ---------------------------------*/ reload :function(){ var self = this; this._items = {}; this._holders = {}; this._slotNums = {}; KC3ShipManager.load(); KC3GearManager.load(); PlayerManager.loadBases(); // Get squad names if(typeof localStorage.planes == "undefined"){ localStorage.planes = "{}"; } this.squadNames = JSON.parse(localStorage.planes); // Compile equipment holders var ctr, ThisItem, MasterItem, ThisShip, MasterShip; for(ctr in KC3ShipManager.list){ this.checkShipSlotForItemHolder(0, KC3ShipManager.list[ctr]); this.checkShipSlotForItemHolder(1, KC3ShipManager.list[ctr]); this.checkShipSlotForItemHolder(2, KC3ShipManager.list[ctr]); this.checkShipSlotForItemHolder(3, KC3ShipManager.list[ctr]); // No plane is able to be equipped in ex-slot for now } for(ctr in PlayerManager.bases){ this.checkLbasSlotForItemHolder(PlayerManager.bases[ctr]); } for(ctr in PlayerManager.baseConvertingSlots){ this._holders["s"+PlayerManager.baseConvertingSlots[ctr]] = "LbasMoving"; } // Compile ships on Index var thisType, thisSlotitem, thisGearInstance; function GetMyHolder(){ return self._holders["s"+this.itemId]; } function NoHolder(){ return false; } for(ctr in KC3GearManager.list){ ThisItem = KC3GearManager.list[ctr]; MasterItem = ThisItem.master(); if(!MasterItem) continue; //if(KC3GearManager.carrierBasedAircraftType3Ids.indexOf(MasterItem.api_type[3]) == -1) continue; // Add holder to the item object temporarily via function return if(typeof this._holders["s"+ThisItem.itemId] != "undefined"){ ThisItem.MyHolder = GetMyHolder; }else{ ThisItem.MyHolder = NoHolder; } // Check if slotitem_type is filled if(typeof this._items["t"+MasterItem.api_type[3]] == "undefined"){ this._items["t"+MasterItem.api_type[3]] = []; } thisType = this._items["t"+MasterItem.api_type[3]]; // Check if slotitem_id is filled if(typeof this._items["t"+MasterItem.api_type[3]]["s"+MasterItem.api_id] == "undefined"){ this._items["t"+MasterItem.api_type[3]]["s"+MasterItem.api_id] = { id: ThisItem.masterId, type_id: MasterItem.api_type[3], english: ThisItem.name(), japanese: MasterItem.api_name, stats: { fp: MasterItem.api_houg, tp: MasterItem.api_raig, aa: MasterItem.api_tyku, ar: MasterItem.api_souk, as: MasterItem.api_tais, ev: MasterItem.api_houk, ls: MasterItem.api_saku, dv: MasterItem.api_baku, ht: MasterItem.api_houm, rn: MasterItem.api_leng, or: MasterItem.api_distance }, instances: [] }; } thisSlotitem = this._items["t"+MasterItem.api_type[3]]["s"+MasterItem.api_id]; thisSlotitem.instances.push(ThisItem); } // sort this_items var sortMasterItem = function(a, b){ var attr; switch( i ){ case 't6': case 6: attr = 'aa'; break; case 't7': case 7: attr = 'dv'; break; case 't8': case 8: attr = 'tp'; break; case 't9': case 9: attr = 'ls'; break; case 't10': case 10: attr = 'dv'; break; default: attr = 'aa'; break; } if( b.stats[attr] == a.stats[attr] ) return b.stats.ht - a.stats.ht; return b.stats[attr] - a.stats[attr]; }; var sortSlotItem = function(a,b){ return b.ace - a.ace; }; for( var i in this._items ){ // make elements in this._items true Array for( var j in this._items[i] ){ // sort item by ace this._items[i][j].instances.sort(sortSlotItem); this._items[i].push( this._items[i][j] ); delete this._items[i][j]; } // sort MasterItem by stat this._items[i].sort(sortMasterItem); } }, /* Check a ship's equipment slot of an item is equipped --------------------------------------------*/ checkShipSlotForItemHolder :function(slot, ThisShip){ if(ThisShip.items[slot] > 0){ this._holders["s"+ThisShip.items[slot]] = ThisShip; this._slotNums["s"+ThisShip.items[slot]] = slot; } }, /* Check LBAS slot of an aircraft is equipped --------------------------------------------*/ checkLbasSlotForItemHolder :function(LandBase){ for(var squad in LandBase.planes){ if(LandBase.planes[squad].api_slotid > 0){ this._holders["s"+LandBase.planes[squad].api_slotid] = LandBase; } } }, /* EXECUTE Places data onto the interface ---------------------------------*/ execute :function(){ var self = this; $(".tab_aircraft .item_type").on("click", function(){ KC3StrategyTabs.gotoTab(null, $(this).data("type")); }); $(".tab_aircraft .item_list").on("change", ".instance_name input", function(){ self.squadNames["p"+$(this).attr("data-gearId")] = $(this).val(); localStorage.planes = JSON.stringify(self.squadNames); }); if(!!KC3StrategyTabs.pageParams[1]){ this.showType(KC3StrategyTabs.pageParams[1]); } else { this.showType($(".tab_aircraft .item_type").first().data("type")); } }, /* Show slotitem type --------------------------------------------*/ showType :function(type_id){ $(".tab_aircraft .item_type").removeClass("active"); $(".tab_aircraft .item_type[data-type={0}]".format(type_id)).addClass("active"); $(".tab_aircraft .item_list").html(""); var ctr, ThisType, ItemElem, ThisSlotitem; var gearClickFunc = function(e){ KC3StrategyTabs.gotoTab("mstgear", $(this).attr("alt")); }; var lbasPlanesFilter = function(s){ return s.api_slotid === ThisPlane.itemId; }; for(ctr in this._items["t"+type_id]){ ThisSlotitem = this._items["t"+type_id][ctr]; ItemElem = $(".tab_aircraft .factory .slotitem").clone().appendTo(".tab_aircraft .item_list"); $(".icon img", ItemElem).attr("src", "../../assets/img/items/"+type_id+".png"); $(".icon img", ItemElem).attr("alt", ThisSlotitem.id); $(".icon img", ItemElem).click(gearClickFunc); $(".english", ItemElem).text(ThisSlotitem.english); $(".japanese", ItemElem).text(ThisSlotitem.japanese); this.slotitem_stat(ItemElem, ThisSlotitem, "fp"); this.slotitem_stat(ItemElem, ThisSlotitem, "tp"); this.slotitem_stat(ItemElem, ThisSlotitem, "aa"); this.slotitem_stat(ItemElem, ThisSlotitem, "ar"); this.slotitem_stat(ItemElem, ThisSlotitem, "as"); this.slotitem_stat(ItemElem, ThisSlotitem, "ev"); this.slotitem_stat(ItemElem, ThisSlotitem, "ls"); this.slotitem_stat(ItemElem, ThisSlotitem, "dv"); this.slotitem_stat(ItemElem, ThisSlotitem, "ht"); this.slotitem_stat(ItemElem, ThisSlotitem, "rn"); this.slotitem_stat(ItemElem, ThisSlotitem, "or"); var PlaneCtr, ThisPlane, PlaneBox, rankLines, ThisCapacity; for(PlaneCtr in ThisSlotitem.instances){ ThisPlane = ThisSlotitem.instances[PlaneCtr]; PlaneBox = $(".tab_aircraft .factory .instance").clone(); $(".instances", ItemElem).append(PlaneBox); $(".instance_icon img", PlaneBox).attr("src", "../../assets/img/items/"+type_id+".png"); if(ThisPlane.stars > 0){ $(".instance_star span", PlaneBox).text( ThisPlane.stars > 9 ? "m" : ThisPlane.stars); } else { $(".instance_star img", PlaneBox).hide(); } if(ThisPlane.ace > 0){ $(".instance_chev img", PlaneBox).attr("src", "../../assets/img/client/achev/"+ThisPlane.ace+".png"); }else{ $(".instance_chev img", PlaneBox).hide(); } $(".instance_name input", PlaneBox).attr("data-gearId", ThisPlane.itemId); if(typeof this.squadNames["p"+ThisPlane.itemId] != "undefined"){ $(".instance_name input", PlaneBox).val( this.squadNames["p"+ThisPlane.itemId] ); } if(ThisPlane.MyHolder()){ if(ThisPlane.MyHolder() instanceof KC3LandBase){ $(".holder_pic img", PlaneBox).attr("src", "../../../../assets/img/items/33.png" ); $(".holder_name", PlaneBox).text( "LBAS World "+ThisPlane.MyHolder().map ); $(".holder_level", PlaneBox).text( "#"+ThisPlane.MyHolder().rid ); ThisCapacity = ThisPlane.MyHolder().planes .filter(lbasPlanesFilter)[0].api_max_count; } else if(ThisPlane.MyHolder() === "LbasMoving"){ $(".holder_pic img", PlaneBox).attr("src", "../../../../assets/img/items/33.png" ); $(".holder_name", PlaneBox).text( "LBAS Moving" ); $(".holder_level", PlaneBox).text( "" ); ThisCapacity = ""; } else { $(".holder_pic img", PlaneBox).attr("src", KC3Meta.shipIcon(ThisPlane.MyHolder().masterId) ); $(".holder_name", PlaneBox).text( ThisPlane.MyHolder().name() ); $(".holder_level", PlaneBox).text("Lv."+ThisPlane.MyHolder().level); ThisCapacity = ThisPlane.MyHolder().slots[ this._slotNums["s"+ThisPlane.itemId] ]; } if(ThisCapacity > 0){ // Compute for veteranized fighter power var MyFighterPowerText = ""; if(ConfigManager.air_formula == 1){ MyFighterPowerText = ThisPlane.fighterPower(ThisCapacity); }else{ MyFighterPowerText = "~"+ThisPlane.fighterVeteran(ThisCapacity); } $(".instance_aaval", PlaneBox).text( MyFighterPowerText ); } $(".instance_aaval", PlaneBox).addClass("activeSquad"); $(".instance_slot", PlaneBox).text(ThisCapacity); }else{ $(".holder_pic", PlaneBox).hide(); $(".holder_name", PlaneBox).hide(); $(".holder_level", PlaneBox).hide(); $(".instance_aaval", PlaneBox).addClass("reserveSquad"); $(".instance_aaval", PlaneBox).text( ThisSlotitem.stats.aa ); } } } }, /* Determine if an item has a specific stat --------------------------------------------*/ slotitem_stat :function(ItemElem, SlotItem, statName){ if(SlotItem.stats[statName] !== 0 && (statName !== "or" || (statName === "or" && KC3GearManager.landBasedAircraftType3Ids.indexOf(SlotItem.type_id)>-1) ) ){ $(".stats .item_"+statName+" span", ItemElem).text(SlotItem.stats[statName]); }else{ $(".stats .item_"+statName, ItemElem).hide(); } } }; })();
c933103/KC3Kai
src/pages/strategy/tabs/aircraft/aircraft.js
JavaScript
mit
10,605
'use strict'; /* This is the primary module of the Ava bot, if you are not using docker to run the bot you can use another method to run this file as long as you make sure you have the correct dependencies */ const bot = require('./bot.js'); const log = require('./logger.js')(module); log.info('======== ava.js running ========'); // This step serves the important purpose of allowing a specific function to be called to start the bot bot.startup();
JamesLongman/ava-bot
lib/ava.js
JavaScript
mit
455
/** * @class Jaml * @author Ed Spencer (http://edspencer.net) * Jaml is a simple JavaScript library which makes HTML generation easy and pleasurable. * Examples: http://edspencer.github.com/jaml * Introduction: http://edspencer.net/2009/11/jaml-beautiful-html-generation-for-javascript.html */ Jaml = function() { return { templates: {}, /** * Registers a template by name * @param {String} name The name of the template * @param {Function} template The template function */ register: function(name, template) { this.templates[name] = template; }, /** * Renders the given template name with an optional data object * @param {String} name The name of the template to render * @param {Object} thisObj Optional data object * @param {Object} data Optional data object */ render: function(name, thisObj, data) { var template = this.templates[name], renderer = new Jaml.Template(template); return renderer.render.apply(renderer, Array.prototype.slice.call(arguments, 1)); } }; }();
edspencer/jaml
src/Jaml.js
JavaScript
mit
1,100
require_relative "http_client" require_relative 'artist' require_relative 'album' module Xiami class Song include Virtus.model(finalize: false) attribute :id, Integer attribute :name, String attribute :temporary_url, String attribute :artist, Artist attribute :album, 'Xiami::Album' attribute :lyrics_url, String class << self def search(query) Searcher.search(query: query) end def search_all(query) FullSearcher.search(query: query) end def fetch(song_url) song_id = song_url.match(/song\/([0-9]+)/)[1] rescue song_url fetch!(song_id) rescue nil end def fetch!(id) song = parse_xml_info!(id) rescue parse_html_page!(id) song.id = id song.fetch_all_album_arts! song end def parse_html_page!(id) html = HTTPClient.get_content("http://www.xiami.com/song/#{id}") Parser::SongHTMLParser.parse(html) end def parse_xml_info!(id) xml = HTTPClient.get_content("http://www.xiami.com/widget/xml-single/uid/0/sid/#{id}") Parser::SongXMLParser.parse(xml) end def parse_lyrics_info!(id) xml = HTTPClient.get_content("http://www.xiami.com/song/playlist/id/#{id}") Parser::LyricsXMLParser.parse(xml) end def parse_lyrics!(id) url = parse_lyrics_info!(id) HTTPClient.get_content(url) end end def fetch_all_album_arts! results = CoverFetcher.fetch_all(album.cover_url, HTTPClient.proxy) album.cover_urls = results[:cover_urls] album.cover_url = results[:cover_url] end def ==(another) return false if another.nil? self.id == another.id end def title name end def artist_name artist.name end def album_name album.name end end end
forresty/xiami
lib/xiami/song.rb
Ruby
mit
1,928
module.exports = { vert: [ 'uniform mat4 u_view_matrix;', 'attribute vec2 a_position;', 'attribute vec4 a_color;', 'varying vec4 v_color;', 'void main () {', ' gl_Position = u_view_matrix * vec4(a_position, 1.0, 1.0);', ' v_color = a_color;', '}' ].join('\n'), frag:[ 'precision lowp float;', 'varying vec4 v_color;', 'void main() {', ' gl_FragColor = v_color;', '}' ].join('\n') };
clark-stevenson/phaser
v3/src/renderer/webgl/shaders/UntexturedAndTintedShader.js
JavaScript
mit
509
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("02.ConcatenateTextFiles")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("02.ConcatenateTextFiles")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("af1279c8-1d89-4fe8-9bc7-b8edc5f9ca0c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
tddold/Telerik-Academy-2
Csharp-Part2/08.TextFiles/02.ConcatenateTextFiles/Properties/AssemblyInfo.cs
C#
mit
1,422
require "spec_helper" describe ChefSpec::Matchers::StateAttrsMatcher do subject { described_class.new(%i{a b}) } context "when the resource does not exist" do let(:resource) { nil } before { subject.matches?(resource) } it "does not match" do expect(subject).to_not be_matches(resource) end it "has the correct description" do expect(subject.description).to eq("have state attributes [:a, :b]") end it "has the correct failure message for should" do expect(subject.failure_message).to include <<-EOH.gsub(/^ {8}/, "") expected _something_ to have state attributes, but the _something_ you gave me was nil! Ensure the resource exists before making assertions: expect(resource).to be EOH end it "has the correct failure message for should not" do expect(subject.failure_message_when_negated).to include <<-EOH.gsub(/^ {8}/, "") expected _something_ to not have state attributes, but the _something_ you gave me was nil! Ensure the resource exists before making assertions: expect(resource).to be EOH end end context "when the resource exists" do let(:klass) { double("class", state_attrs: %i{a b}) } let(:resource) { double("resource", class: klass) } before { subject.matches?(resource) } it "has the correct description" do expect(subject.description).to eq("have state attributes [:a, :b]") end it "has the correct failure message for should" do expect(subject.failure_message).to eq("expected [:a, :b] to equal [:a, :b]") end it "has the correct failure message for should not" do expect(subject.failure_message_when_negated).to eq("expected [:a, :b] to not equal [:a, :b]") end it "matches when the state attributes are correct" do expect(subject).to be_matches(resource) end it "does not match when the state attributes are incorrect" do allow(klass).to receive(:state_attrs).and_return(%i{c d}) expect(subject).to_not be_matches(resource) end it "does not match when partial state attribute are incorrect" do allow(klass).to receive(:state_attrs).and_return(%i{b c}) expect(subject).to_not be_matches(resource) end end end
chefspec/chefspec
spec/unit/matchers/state_attrs_matcher_spec.rb
Ruby
mit
2,289
<?php /* * This file is part of the PagerBundle package. * * (c) Marcin Butlak <contact@maker-labs.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace MakerLabs\PagerBundle; use MakerLabs\PagerBundle\Adapter\PagerAdapterInterface; /** * Pager * * @author Marcin Butlak <contact@maker-labs.com> */ class Pager { /** * * @var integer */ protected $page = 1; /** * * @var integer */ protected $limit = 20; /** * Constructor * * @param PagerAdapterInterface $adapter The pager adapter * @param array $options Additional options */ public function __construct(PagerAdapterInterface $adapter, array $options = array()) { $this->adapter = $adapter; if (isset($options['limit'])) { $this->setLimit($options['limit']); } if (isset($options['page'])) { $this->setPage($options['page']); } } /** * Sets the current page number * * @param integer $page The current page number * @return Pager instance */ public function setPage($page) { $this->page = min($page > 0 ? $page : $this->getFirstPage(), $this->getLastPage()); return $this; } /** * Returns the current page number * * @return integer */ public function getPage() { return $this->page; } /** * Sets the results limit for one page * * @param integer $limit * @return Pager instance */ public function setLimit($limit) { $this->limit = $limit > 0 ? $limit : 1; $this->setPage($this->page); return $this; } /** * Returns the current results limit for one page * * @return integer */ public function getLimit() { return $this->limit; } /** * Returns the next page number * * @return integer */ public function getNextPage() { return $this->page < $this->getLastPage() ? $this->page + 1 : $this->getLastPage(); } /** * Returns the previous page number * * @return integer */ public function getPreviousPage() { return $this->page > $this->getFirstPage() ? $this->page - 1 : $this->getFirstPage(); } /** * Returns true if the current page is first * * @return boolean */ public function isFirstPage() { return $this->page == 1; } /** * Returns the first page number * * @return integer */ public function getFirstPage() { return 1; } /** * Returns true if the current page is last * * @return boolean */ public function isLastPage() { return $this->page == $this->getLastPage(); } /** * Returns the last page number * * @return integer */ public function getLastPage() { return $this->hasResults() ? ceil($this->adapter->count() / $this->limit) : $this->getFirstPage(); } /** * Returns true if the current result set requires pagination * * @return boolean */ public function isPaginable() { return $this->adapter->count() > $this->limit; } /** * Generates a page list * * @param integer $pages Number of pages to generate * @return array The page list */ public function getPages($pages = 10) { $tmp = $this->page - floor($pages / 2); $begin = $tmp > $this->getFirstPage() ? $tmp : $this->getFirstPage(); $end = min($begin + $pages - 1, $this->getLastPage()); return range($begin, $end, 1); } /** * Returns true if the current result set is not empty * * @return boolean */ public function hasResults() { return $this->adapter->count() > 0; } /** * * Returns results list for the current page and limit * * @return array */ public function getResults() { return $this->hasResults() ? $this->adapter->getResults(($this->page - 1) * $this->limit, $this->limit) : array(); } /** * Returns the current adapter instance * * @return PagerAdapterInterface */ public function getAdapter() { return $this->adapter; } }
soniar4i/Alood
src/MakerLabs/PagerBundle/Pager.php
PHP
mit
4,498
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.aop.config; import java.util.List; import org.w3c.dom.Node; import org.springframework.aop.framework.ProxyFactoryBean; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinitionHolder; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionReaderUtils; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.ManagedList; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.beans.factory.xml.BeanDefinitionDecorator; import org.springframework.beans.factory.xml.ParserContext; import org.springframework.util.ClassUtils; import org.springframework.util.StringUtils; /** * Base implementation for * {@link org.springframework.beans.factory.xml.BeanDefinitionDecorator BeanDefinitionDecorators} * wishing to add an {@link org.aopalliance.intercept.MethodInterceptor interceptor} * to the resulting bean. * * <p>This base class controls the creation of the {@link ProxyFactoryBean} bean definition * and wraps the original as an inner-bean definition for the {@code target} property * of {@link ProxyFactoryBean}. * * <p>Chaining is correctly handled, ensuring that only one {@link ProxyFactoryBean} definition * is created. If a previous {@link org.springframework.beans.factory.xml.BeanDefinitionDecorator} * already created the {@link org.springframework.aop.framework.ProxyFactoryBean} then the * interceptor is simply added to the existing definition. * * <p>Subclasses have only to create the {@code BeanDefinition} to the interceptor that * they wish to add. * * @author Rob Harrop * @author Juergen Hoeller * @since 2.0 * @see org.aopalliance.intercept.MethodInterceptor */ public abstract class AbstractInterceptorDrivenBeanDefinitionDecorator implements BeanDefinitionDecorator { @Override public final BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder definitionHolder, ParserContext parserContext) { BeanDefinitionRegistry registry = parserContext.getRegistry(); // get the root bean name - will be the name of the generated proxy factory bean String existingBeanName = definitionHolder.getBeanName(); BeanDefinition targetDefinition = definitionHolder.getBeanDefinition(); BeanDefinitionHolder targetHolder = new BeanDefinitionHolder(targetDefinition, existingBeanName + ".TARGET"); // delegate to subclass for interceptor definition BeanDefinition interceptorDefinition = createInterceptorDefinition(node); // generate name and register the interceptor String interceptorName = existingBeanName + '.' + getInterceptorNameSuffix(interceptorDefinition); BeanDefinitionReaderUtils.registerBeanDefinition( new BeanDefinitionHolder(interceptorDefinition, interceptorName), registry); BeanDefinitionHolder result = definitionHolder; if (!isProxyFactoryBeanDefinition(targetDefinition)) { // create the proxy definition RootBeanDefinition proxyDefinition = new RootBeanDefinition(); // create proxy factory bean definition proxyDefinition.setBeanClass(ProxyFactoryBean.class); proxyDefinition.setScope(targetDefinition.getScope()); proxyDefinition.setLazyInit(targetDefinition.isLazyInit()); // set the target proxyDefinition.setDecoratedDefinition(targetHolder); proxyDefinition.getPropertyValues().add("target", targetHolder); // create the interceptor names list proxyDefinition.getPropertyValues().add("interceptorNames", new ManagedList<String>()); // copy autowire settings from original bean definition. proxyDefinition.setAutowireCandidate(targetDefinition.isAutowireCandidate()); proxyDefinition.setPrimary(targetDefinition.isPrimary()); if (targetDefinition instanceof AbstractBeanDefinition) { proxyDefinition.copyQualifiersFrom((AbstractBeanDefinition) targetDefinition); } // wrap it in a BeanDefinitionHolder with bean name result = new BeanDefinitionHolder(proxyDefinition, existingBeanName); } addInterceptorNameToList(interceptorName, result.getBeanDefinition()); return result; } @SuppressWarnings("unchecked") private void addInterceptorNameToList(String interceptorName, BeanDefinition beanDefinition) { List<String> list = (List<String>) beanDefinition.getPropertyValues().getPropertyValue("interceptorNames").getValue(); list.add(interceptorName); } private boolean isProxyFactoryBeanDefinition(BeanDefinition existingDefinition) { return ProxyFactoryBean.class.getName().equals(existingDefinition.getBeanClassName()); } protected String getInterceptorNameSuffix(BeanDefinition interceptorDefinition) { return StringUtils.uncapitalize(ClassUtils.getShortName(interceptorDefinition.getBeanClassName())); } /** * Subclasses should implement this method to return the {@code BeanDefinition} * for the interceptor they wish to apply to the bean being decorated. */ protected abstract BeanDefinition createInterceptorDefinition(Node node); }
boggad/jdk9-sample
sample-catalog/spring-jdk9/src/spring.aop/org/springframework/aop/config/AbstractInterceptorDrivenBeanDefinitionDecorator.java
Java
mit
5,744
<?php /* * This file is part of the PHPExifTool package. * * (c) Alchemy <support@alchemy.fr> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\DICOM; use JMS\Serializer\Annotation\ExclusionPolicy; use PHPExiftool\Driver\AbstractTag; /** * @ExclusionPolicy("all") */ class UPSProgressInformationSequence extends AbstractTag { protected $Id = '0074,1002'; protected $Name = 'UPSProgressInformationSequence'; protected $FullName = 'DICOM::Main'; protected $GroupName = 'DICOM'; protected $g0 = 'DICOM'; protected $g1 = 'DICOM'; protected $g2 = 'Image'; protected $Type = '?'; protected $Writable = false; protected $Description = 'UPS Progress Information Sequence'; }
bburnichon/PHPExiftool
lib/PHPExiftool/Driver/Tag/DICOM/UPSProgressInformationSequence.php
PHP
mit
844
package luhn import "strings" func Valid(id string) bool { if len(strings.TrimSpace(id)) == 1 { return false } d := make([]int, 0, len(id)) for _, r := range id { if r == ' ' { continue } if r < '0' || r > '9' { return false } d = append(d, int(r-'0')) } return sum(d)%10 == 0 } func sum(d []int) (s int) { for i, x := range d { j := len(d) - i if j%2 == 0 { x *= 2 if x > 9 { x -= 9 } } s += x } return }
exercism/xgo
exercises/luhn/example.go
GO
mit
461
/* YUI 3.7.2 (build 5639) Copyright 2012 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('node-base', function (Y, NAME) { /** * @module node * @submodule node-base */ var methods = [ /** * Determines whether each node has the given className. * @method hasClass * @for Node * @param {String} className the class name to search for * @return {Boolean} Whether or not the element has the specified class */ 'hasClass', /** * Adds a class name to each node. * @method addClass * @param {String} className the class name to add to the node's class attribute * @chainable */ 'addClass', /** * Removes a class name from each node. * @method removeClass * @param {String} className the class name to remove from the node's class attribute * @chainable */ 'removeClass', /** * Replace a class with another class for each node. * If no oldClassName is present, the newClassName is simply added. * @method replaceClass * @param {String} oldClassName the class name to be replaced * @param {String} newClassName the class name that will be replacing the old class name * @chainable */ 'replaceClass', /** * If the className exists on the node it is removed, if it doesn't exist it is added. * @method toggleClass * @param {String} className the class name to be toggled * @param {Boolean} force Option to force adding or removing the class. * @chainable */ 'toggleClass' ]; Y.Node.importMethod(Y.DOM, methods); /** * Determines whether each node has the given className. * @method hasClass * @see Node.hasClass * @for NodeList * @param {String} className the class name to search for * @return {Array} An array of booleans for each node bound to the NodeList. */ /** * Adds a class name to each node. * @method addClass * @see Node.addClass * @param {String} className the class name to add to the node's class attribute * @chainable */ /** * Removes a class name from each node. * @method removeClass * @see Node.removeClass * @param {String} className the class name to remove from the node's class attribute * @chainable */ /** * Replace a class with another class for each node. * If no oldClassName is present, the newClassName is simply added. * @method replaceClass * @see Node.replaceClass * @param {String} oldClassName the class name to be replaced * @param {String} newClassName the class name that will be replacing the old class name * @chainable */ /** * If the className exists on the node it is removed, if it doesn't exist it is added. * @method toggleClass * @see Node.toggleClass * @param {String} className the class name to be toggled * @chainable */ Y.NodeList.importMethod(Y.Node.prototype, methods); /** * @module node * @submodule node-base */ var Y_Node = Y.Node, Y_DOM = Y.DOM; /** * Returns a new dom node using the provided markup string. * @method create * @static * @param {String} html The markup used to create the element * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @param {HTMLDocument} doc An optional document context * @return {Node} A Node instance bound to a DOM node or fragment * @for Node */ Y_Node.create = function(html, doc) { if (doc && doc._node) { doc = doc._node; } return Y.one(Y_DOM.create(html, doc)); }; Y.mix(Y_Node.prototype, { /** * Creates a new Node using the provided markup string. * @method create * @param {String} html The markup used to create the element. * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @param {HTMLDocument} doc An optional document context * @return {Node} A Node instance bound to a DOM node or fragment */ create: Y_Node.create, /** * Inserts the content before the reference node. * @method insert * @param {String | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @param {Int | Node | HTMLElement | String} where The position to insert at. * Possible "where" arguments * <dl> * <dt>Y.Node</dt> * <dd>The Node to insert before</dd> * <dt>HTMLElement</dt> * <dd>The element to insert before</dd> * <dt>Int</dt> * <dd>The index of the child element to insert before</dd> * <dt>"replace"</dt> * <dd>Replaces the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts before the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts content before the node</dd> * <dt>"after"</dt> * <dd>Inserts content after the node</dd> * </dl> * @chainable */ insert: function(content, where) { this._insert(content, where); return this; }, _insert: function(content, where) { var node = this._node, ret = null; if (typeof where == 'number') { // allow index where = this._node.childNodes[where]; } else if (where && where._node) { // Node where = where._node; } if (content && typeof content != 'string') { // allow Node or NodeList/Array instances content = content._node || content._nodes || content; } ret = Y_DOM.addHTML(node, content, where); return ret; }, /** * Inserts the content as the firstChild of the node. * @method prepend * @param {String | Node | HTMLElement} content The content to insert * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @chainable */ prepend: function(content) { return this.insert(content, 0); }, /** * Inserts the content as the lastChild of the node. * @method append * @param {String | Node | HTMLElement} content The content to insert * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @chainable */ append: function(content) { return this.insert(content, null); }, /** * @method appendChild * @param {String | HTMLElement | Node} node Node to be appended * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @return {Node} The appended node */ appendChild: function(node) { return Y_Node.scrubVal(this._insert(node)); }, /** * @method insertBefore * @param {String | HTMLElement | Node} newNode Node to be appended * @param {HTMLElement | Node} refNode Node to be inserted before * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @return {Node} The inserted node */ insertBefore: function(newNode, refNode) { return Y.Node.scrubVal(this._insert(newNode, refNode)); }, /** * Appends the node to the given node. * @method appendTo * @param {Node | HTMLElement} node The node to append to * @chainable */ appendTo: function(node) { Y.one(node).append(this); return this; }, /** * Replaces the node's current content with the content. * Note that this passes to innerHTML and is not escaped. * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content or `set('text')` to add as text. * @method setContent * @deprecated Use setHTML * @param {String | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert * @chainable */ setContent: function(content) { this._insert(content, 'replace'); return this; }, /** * Returns the node's current content (e.g. innerHTML) * @method getContent * @deprecated Use getHTML * @return {String} The current content */ getContent: function(content) { return this.get('innerHTML'); } }); /** * Replaces the node's current html content with the content provided. * Note that this passes to innerHTML and is not escaped. * Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text. * @method setHTML * @param {String | HTML | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert * @chainable */ Y.Node.prototype.setHTML = Y.Node.prototype.setContent; /** * Returns the node's current html content (e.g. innerHTML) * @method getHTML * @return {String} The html content */ Y.Node.prototype.getHTML = Y.Node.prototype.getContent; Y.NodeList.importMethod(Y.Node.prototype, [ /** * Called on each Node instance * @for NodeList * @method append * @see Node.append */ 'append', /** * Called on each Node instance * @for NodeList * @method insert * @see Node.insert */ 'insert', /** * Called on each Node instance * @for NodeList * @method appendChild * @see Node.appendChild */ 'appendChild', /** * Called on each Node instance * @for NodeList * @method insertBefore * @see Node.insertBefore */ 'insertBefore', /** * Called on each Node instance * @for NodeList * @method prepend * @see Node.prepend */ 'prepend', /** * Called on each Node instance * Note that this passes to innerHTML and is not escaped. * Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text. * @for NodeList * @method setContent * @deprecated Use setHTML */ 'setContent', /** * Called on each Node instance * @for NodeList * @method getContent * @deprecated Use getHTML */ 'getContent', /** * Called on each Node instance * Note that this passes to innerHTML and is not escaped. * Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text. * @for NodeList * @method setHTML * @see Node.setHTML */ 'setHTML', /** * Called on each Node instance * @for NodeList * @method getHTML * @see Node.getHTML */ 'getHTML' ]); /** * @module node * @submodule node-base */ var Y_Node = Y.Node, Y_DOM = Y.DOM; /** * Static collection of configuration attributes for special handling * @property ATTRS * @static * @type object */ Y_Node.ATTRS = { /** * Allows for getting and setting the text of an element. * Formatting is preserved and special characters are treated literally. * @config text * @type String */ text: { getter: function() { return Y_DOM.getText(this._node); }, setter: function(content) { Y_DOM.setText(this._node, content); return content; } }, /** * Allows for getting and setting the text of an element. * Formatting is preserved and special characters are treated literally. * @config for * @type String */ 'for': { getter: function() { return Y_DOM.getAttribute(this._node, 'for'); }, setter: function(val) { Y_DOM.setAttribute(this._node, 'for', val); return val; } }, 'options': { getter: function() { return this._node.getElementsByTagName('option'); } }, /** * Returns a NodeList instance of all HTMLElement children. * @readOnly * @config children * @type NodeList */ 'children': { getter: function() { var node = this._node, children = node.children, childNodes, i, len; if (!children) { childNodes = node.childNodes; children = []; for (i = 0, len = childNodes.length; i < len; ++i) { if (childNodes[i].tagName) { children[children.length] = childNodes[i]; } } } return Y.all(children); } }, value: { getter: function() { return Y_DOM.getValue(this._node); }, setter: function(val) { Y_DOM.setValue(this._node, val); return val; } } }; Y.Node.importMethod(Y.DOM, [ /** * Allows setting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method setAttribute * @for Node * @for NodeList * @chainable * @param {string} name The attribute name * @param {string} value The value to set */ 'setAttribute', /** * Allows getting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method getAttribute * @for Node * @for NodeList * @param {string} name The attribute name * @return {string} The attribute value */ 'getAttribute' ]); /** * @module node * @submodule node-base */ var Y_Node = Y.Node; var Y_NodeList = Y.NodeList; /** * List of events that route to DOM events * @static * @property DOM_EVENTS * @for Node */ Y_Node.DOM_EVENTS = { abort: 1, beforeunload: 1, blur: 1, change: 1, click: 1, close: 1, command: 1, contextmenu: 1, dblclick: 1, DOMMouseScroll: 1, drag: 1, dragstart: 1, dragenter: 1, dragover: 1, dragleave: 1, dragend: 1, drop: 1, error: 1, focus: 1, key: 1, keydown: 1, keypress: 1, keyup: 1, load: 1, message: 1, mousedown: 1, mouseenter: 1, mouseleave: 1, mousemove: 1, mousemultiwheel: 1, mouseout: 1, mouseover: 1, mouseup: 1, mousewheel: 1, orientationchange: 1, reset: 1, resize: 1, select: 1, selectstart: 1, submit: 1, scroll: 1, textInput: 1, unload: 1 }; // Add custom event adaptors to this list. This will make it so // that delegate, key, available, contentready, etc all will // be available through Node.on Y.mix(Y_Node.DOM_EVENTS, Y.Env.evt.plugins); Y.augment(Y_Node, Y.EventTarget); Y.mix(Y_Node.prototype, { /** * Removes event listeners from the node and (optionally) its subtree * @method purge * @param {Boolean} recurse (optional) Whether or not to remove listeners from the * node's subtree * @param {String} type (optional) Only remove listeners of the specified type * @chainable * */ purge: function(recurse, type) { Y.Event.purgeElement(this._node, recurse, type); return this; } }); Y.mix(Y.NodeList.prototype, { _prepEvtArgs: function(type, fn, context) { // map to Y.on/after signature (type, fn, nodes, context, arg1, arg2, etc) var args = Y.Array(arguments, 0, true); if (args.length < 2) { // type only (event hash) just add nodes args[2] = this._nodes; } else { args.splice(2, 0, this._nodes); } args[3] = context || this; // default to NodeList instance as context return args; }, /** Subscribe a callback function for each `Node` in the collection to execute in response to a DOM event. NOTE: Generally, the `on()` method should be avoided on `NodeLists`, in favor of using event delegation from a parent Node. See the Event user guide for details. Most DOM events are associated with a preventable default behavior, such as link clicks navigating to a new page. Callbacks are passed a `DOMEventFacade` object as their first argument (usually called `e`) that can be used to prevent this default behavior with `e.preventDefault()`. See the `DOMEventFacade` API for all available properties and methods on the object. By default, the `this` object will be the `NodeList` that the subscription came from, <em>not the `Node` that received the event</em>. Use `e.currentTarget` to refer to the `Node`. Returning `false` from a callback is supported as an alternative to calling `e.preventDefault(); e.stopPropagation();`. However, it is recommended to use the event methods. @example Y.all(".sku").on("keydown", function (e) { if (e.keyCode === 13) { e.preventDefault(); // Use e.currentTarget to refer to the individual Node var item = Y.MyApp.searchInventory( e.currentTarget.get('value') ); // etc ... } }); @method on @param {String} type The name of the event @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching that subscription @for NodeList **/ on: function(type, fn, context) { return Y.on.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an one-time event listener to each Node bound to the NodeList. * @method once * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {EventHandle} A subscription handle capable of detaching that * subscription * @for NodeList */ once: function(type, fn, context) { return Y.once.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an event listener to each Node bound to the NodeList. * The handler is called only after all on() handlers are called * and the event is not prevented. * @method after * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {EventHandle} A subscription handle capable of detaching that * subscription * @for NodeList */ after: function(type, fn, context) { return Y.after.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an one-time event listener to each Node bound to the NodeList * that will be called only after all on() handlers are called and the * event is not prevented. * * @method onceAfter * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {EventHandle} A subscription handle capable of detaching that * subscription * @for NodeList */ onceAfter: function(type, fn, context) { return Y.onceAfter.apply(Y, this._prepEvtArgs.apply(this, arguments)); } }); Y_NodeList.importMethod(Y.Node.prototype, [ /** * Called on each Node instance * @method detach * @see Node.detach * @for NodeList */ 'detach', /** Called on each Node instance * @method detachAll * @see Node.detachAll * @for NodeList */ 'detachAll' ]); /** Subscribe a callback function to execute in response to a DOM event or custom event. Most DOM events are associated with a preventable default behavior such as link clicks navigating to a new page. Callbacks are passed a `DOMEventFacade` object as their first argument (usually called `e`) that can be used to prevent this default behavior with `e.preventDefault()`. See the `DOMEventFacade` API for all available properties and methods on the object. If the event name passed as the first parameter is not a whitelisted DOM event, it will be treated as a custom event subscriptions, allowing `node.fire('customEventName')` later in the code. Refer to the Event user guide for the full DOM event whitelist. By default, the `this` object in the callback will refer to the subscribed `Node`. Returning `false` from a callback is supported as an alternative to calling `e.preventDefault(); e.stopPropagation();`. However, it is recommended to use the event methods. @example Y.one("#my-form").on("submit", function (e) { e.preventDefault(); // proceed with ajax form submission instead... }); @method on @param {String} type The name of the event @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching that subscription @for Node **/ Y.mix(Y.Node.ATTRS, { offsetHeight: { setter: function(h) { Y.DOM.setHeight(this._node, h); return h; }, getter: function() { return this._node.offsetHeight; } }, offsetWidth: { setter: function(w) { Y.DOM.setWidth(this._node, w); return w; }, getter: function() { return this._node.offsetWidth; } } }); Y.mix(Y.Node.prototype, { sizeTo: function(w, h) { var node; if (arguments.length < 2) { node = Y.one(w); w = node.get('offsetWidth'); h = node.get('offsetHeight'); } this.setAttrs({ offsetWidth: w, offsetHeight: h }); } }); /** * @module node * @submodule node-base */ var Y_Node = Y.Node; Y.mix(Y_Node.prototype, { /** * Makes the node visible. * If the "transition" module is loaded, show optionally * animates the showing of the node using either the default * transition effect ('fadeIn'), or the given named effect. * @method show * @for Node * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ show: function(callback) { callback = arguments[arguments.length - 1]; this.toggleView(true, callback); return this; }, /** * The implementation for showing nodes. * Default is to toggle the style.display property. * @method _show * @protected * @chainable */ _show: function() { this.setStyle('display', ''); }, _isHidden: function() { return Y.DOM.getStyle(this._node, 'display') === 'none'; }, /** * Displays or hides the node. * If the "transition" module is loaded, toggleView optionally * animates the toggling of the node using either the default * transition effect ('fadeIn'), or the given named effect. * @method toggleView * @for Node * @param {Boolean} [on] An optional boolean value to force the node to be shown or hidden * @param {Function} [callback] An optional function to run after the transition completes. * @chainable */ toggleView: function(on, callback) { this._toggleView.apply(this, arguments); return this; }, _toggleView: function(on, callback) { callback = arguments[arguments.length - 1]; // base on current state if not forcing if (typeof on != 'boolean') { on = (this._isHidden()) ? 1 : 0; } if (on) { this._show(); } else { this._hide(); } if (typeof callback == 'function') { callback.call(this); } return this; }, /** * Hides the node. * If the "transition" module is loaded, hide optionally * animates the hiding of the node using either the default * transition effect ('fadeOut'), or the given named effect. * @method hide * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ hide: function(callback) { callback = arguments[arguments.length - 1]; this.toggleView(false, callback); return this; }, /** * The implementation for hiding nodes. * Default is to toggle the style.display property. * @method _hide * @protected * @chainable */ _hide: function() { this.setStyle('display', 'none'); } }); Y.NodeList.importMethod(Y.Node.prototype, [ /** * Makes each node visible. * If the "transition" module is loaded, show optionally * animates the showing of the node using either the default * transition effect ('fadeIn'), or the given named effect. * @method show * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @for NodeList * @chainable */ 'show', /** * Hides each node. * If the "transition" module is loaded, hide optionally * animates the hiding of the node using either the default * transition effect ('fadeOut'), or the given named effect. * @method hide * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ 'hide', /** * Displays or hides each node. * If the "transition" module is loaded, toggleView optionally * animates the toggling of the nodes using either the default * transition effect ('fadeIn'), or the given named effect. * @method toggleView * @param {Boolean} [on] An optional boolean value to force the nodes to be shown or hidden * @param {Function} [callback] An optional function to run after the transition completes. * @chainable */ 'toggleView' ]); if (!Y.config.doc.documentElement.hasAttribute) { // IE < 8 Y.Node.prototype.hasAttribute = function(attr) { if (attr === 'value') { if (this.get('value') !== "") { // IE < 8 fails to populate specified when set in HTML return true; } } return !!(this._node.attributes[attr] && this._node.attributes[attr].specified); }; } // IE throws an error when calling focus() on an element that's invisible, not // displayed, or disabled. Y.Node.prototype.focus = function () { try { this._node.focus(); } catch (e) { Y.log('error focusing node: ' + e.toString(), 'error', 'node'); } return this; }; // IE throws error when setting input.type = 'hidden', // input.setAttribute('type', 'hidden') and input.attributes.type.value = 'hidden' Y.Node.ATTRS.type = { setter: function(val) { if (val === 'hidden') { try { this._node.type = 'hidden'; } catch(e) { this.setStyle('display', 'none'); this._inputType = 'hidden'; } } else { try { // IE errors when changing the type from "hidden' this._node.type = val; } catch (e) { Y.log('error setting type: ' + val, 'info', 'node'); } } return val; }, getter: function() { return this._inputType || this._node.type; }, _bypassProxy: true // don't update DOM when using with Attribute }; if (Y.config.doc.createElement('form').elements.nodeType) { // IE: elements collection is also FORM node which trips up scrubVal. Y.Node.ATTRS.elements = { getter: function() { return this.all('input, textarea, button, select'); } }; } /** * Provides methods for managing custom Node data. * * @module node * @main node * @submodule node-data */ Y.mix(Y.Node.prototype, { _initData: function() { if (! ('_data' in this)) { this._data = {}; } }, /** * @method getData * @for Node * @description Retrieves arbitrary data stored on a Node instance. * If no data is associated with the Node, it will attempt to retrieve * a value from the corresponding HTML data attribute. (e.g. node.getData('foo') * will check node.getAttribute('data-foo')). * @param {string} name Optional name of the data field to retrieve. * If no name is given, all data is returned. * @return {any | Object} Whatever is stored at the given field, * or an object hash of all fields. */ getData: function(name) { this._initData(); var data = this._data, ret = data; if (arguments.length) { // single field if (name in data) { ret = data[name]; } else { // initialize from HTML attribute ret = this._getDataAttribute(name); } } else if (typeof data == 'object' && data !== null) { // all fields ret = {}; Y.Object.each(data, function(v, n) { ret[n] = v; }); ret = this._getDataAttributes(ret); } return ret; }, _getDataAttributes: function(ret) { ret = ret || {}; var i = 0, attrs = this._node.attributes, len = attrs.length, prefix = this.DATA_PREFIX, prefixLength = prefix.length, name; while (i < len) { name = attrs[i].name; if (name.indexOf(prefix) === 0) { name = name.substr(prefixLength); if (!(name in ret)) { // only merge if not already stored ret[name] = this._getDataAttribute(name); } } i += 1; } return ret; }, _getDataAttribute: function(name) { var name = this.DATA_PREFIX + name, node = this._node, attrs = node.attributes, data = attrs && attrs[name] && attrs[name].value; return data; }, /** * @method setData * @for Node * @description Stores arbitrary data on a Node instance. * This is not stored with the DOM node. * @param {string} name The name of the field to set. If no val * is given, name is treated as the data and overrides any existing data. * @param {any} val The value to be assigned to the field. * @chainable */ setData: function(name, val) { this._initData(); if (arguments.length > 1) { this._data[name] = val; } else { this._data = name; } return this; }, /** * @method clearData * @for Node * @description Clears internally stored data. * @param {string} name The name of the field to clear. If no name * is given, all data is cleared. * @chainable */ clearData: function(name) { if ('_data' in this) { if (typeof name != 'undefined') { delete this._data[name]; } else { delete this._data; } } return this; } }); Y.mix(Y.NodeList.prototype, { /** * @method getData * @for NodeList * @description Retrieves arbitrary data stored on each Node instance * bound to the NodeList. * @see Node * @param {string} name Optional name of the data field to retrieve. * If no name is given, all data is returned. * @return {Array} An array containing all of the data for each Node instance. * or an object hash of all fields. */ getData: function(name) { var args = (arguments.length) ? [name] : []; return this._invoke('getData', args, true); }, /** * @method setData * @for NodeList * @description Stores arbitrary data on each Node instance bound to the * NodeList. This is not stored with the DOM node. * @param {string} name The name of the field to set. If no name * is given, name is treated as the data and overrides any existing data. * @param {any} val The value to be assigned to the field. * @chainable */ setData: function(name, val) { var args = (arguments.length > 1) ? [name, val] : [name]; return this._invoke('setData', args); }, /** * @method clearData * @for NodeList * @description Clears data on all Node instances bound to the NodeList. * @param {string} name The name of the field to clear. If no name * is given, all data is cleared. * @chainable */ clearData: function(name) { var args = (arguments.length) ? [name] : []; return this._invoke('clearData', [name]); } }); }, '3.7.2', {"requires": ["event-base", "node-core", "dom-base"]});
spadin/coverphoto
node_modules/grunt-contrib/node_modules/grunt-contrib-yuidoc/node_modules/yuidocjs/node_modules/yui/node-base/node-base-debug.js
JavaScript
mit
33,629
## Copyright (c) 2001-2010, Scott D. Peckham ## January 2009 (converted from IDL) ## November 2009 (collected into cfg_files.py ## May 2010 (added read_key_value_pair()) ## July 2010 (added read_list() import numpy #--------------------------------------------------------------------- # # unit_test() # # skip_header() # get_yes_words() # read_words() # read_list() # (7/27/10) # # read_key_value_pair() # (5/7/10) # read_line_after_key() # read_words_after_key() # read_list_after_key() # read_value() # # var_type_code() # read_input_option() # read_output_option() # (boolean and string) # #--------------------------------------------------------------------- def unit_test(): import d8_base comp = d8_base.d8_component() #------------------------------ comp.CCA = False comp.directory = '/Applications/Erode/Data/Test1/' comp.data_prefix = 'Test1' comp.case_prefix = 'Test1' comp.read_config_file() print 'comp.method =', comp.method print 'comp.method_name =', comp.method_name print 'comp.dt =', comp.dt print 'comp.dt.dtype =', comp.dt.dtype print 'comp.LINK_FLATS =', comp.LINK_FLATS print 'comp.LR_PERIODIC =', comp.LR_PERIODIC print 'comp.TB_PERIODIC =', comp.TB_PERIODIC print 'comp.SAVE_DW_PIXELS =', comp.SAVE_DW_PIXELS print 'Finished with cfg_files.unit_test().' print ' ' # unit_test() #--------------------------------------------------------------------- def skip_header(file_unit, n_lines=4): #------------------------- # Skip over header lines #------------------------- for k in xrange(n_lines): line = file_unit.readline() # skip_header() #--------------------------------------------------------------------- def get_yes_words(): yes_words = ['1', 'true', 'on', 'yes', 'ok'] return yes_words # get_yes_words() #--------------------------------------------------------------------- def read_words(file_unit, word_delim=None): #---------------------------------------------------- # Note: If (word_delim is None), then the "split()" # method for strings will use any whitespace # string as a separator. #---------------------------------------------------- line = file_unit.readline() words = line.split( word_delim ) return words # read_words() #--------------------------------------------------------------------- def read_list(file_unit, dtype_list=None, dtype='string', word_delim=None): #------------------------------------------------------------- # Notes: Example (read boolean and string/filename): # vlist = read_list_after_key(file_unit, # ['boolean', 'string']) #------------------------------------------------------------- words = read_words(file_unit, word_delim=word_delim) #---------------------------------------------- # If "dtype_list" is None, then assume that # every element in the list has type "dtype". #---------------------------------------------------- # NB! "dtype_list" cannot default to "[]", because # then values set from a previous call to this # function are remembered and used. #---------------------------------------------------- ## if (dtype_list == []): ## if (len(dtype_list) == 0): if (dtype_list is None): dtype_list = [] for k in xrange(len(words)): dtype_list.append( dtype.lower() ) elif (len(dtype_list) > len(words)): print 'ERROR in cfg_files.read_list_after_key().' print ' Not enough values in the line.' return k = 0 yes_words = get_yes_words() var_list = [] for type_str in dtype_list: vtype = type_str.lower() word = words[k].strip() if (vtype == 'string'): var = word elif (vtype == 'boolean'): var = (word in yes_words) else: value = eval( word ) exec('var = numpy.' + vtype + '( value )') var_list.append( var ) k += 1 return var_list # read_list() #--------------------------------------------------------------------- def read_key_value_pair(file_unit, key_delim=':', SILENT=True): line = file_unit.readline() #-------------------------------------- # Extract the variable name or label, # which may contain blank spaces #-------------------------------------- p = line.find( key_delim ) if (p == -1): if not(SILENT): print 'ERROR in cfg_files.read_line_after_key():' print ' Key-value delimiter not found.' return ('', '') key = line[:p] value = line[p + 1:] value = value.strip() # (strip leading & trailing whitespace) return (key, value) # read_key_value_pair() #--------------------------------------------------------------------- def read_line_after_key(file_unit, key_delim=':'): line = file_unit.readline() #-------------------------------------- # Extract the variable name or label, # which may contain blank spaces #-------------------------------------- p = line.find( key_delim ) if (p == -1): print 'ERROR in cfg_files.read_line_after_key():' print ' Key-value delimiter not found.' return '' label = line[:p] line = line[p + 1:] return line.strip() # (strip leading and trailing whitespace) # read_line_after_key() #--------------------------------------------------------------------- def read_words_after_key(file_unit, key_delim=':', word_delim=None, n_words=None): #---------------------------------------------------- # Note: If (word_delim is None), then the "split()" # method for strings will use any whitespace # string as a separator. #---------------------------------------------------- line = read_line_after_key( file_unit, key_delim=key_delim) #------------------------------- # Extract variables as strings #------------------------------- words = line.split( word_delim ) #----------------------------------- # Option to check for enough words #----------------------------------- if (n_words is None): return words if (len(words) < n_words): print 'ERROR in read_words_after_key():' print ' Not enough words found.' return words # read_words_after_key() #--------------------------------------------------------------------- def read_list_after_key(file_unit, dtype_list=None, dtype='string', key_delim=':', word_delim=None): ## print 'before: dtype =', dtype ## print 'before: dtype_list =', dtype_list #------------------------------------------------------------- # Notes: Example (read boolean and string/filename): # vlist = read_list_after_key(file_unit, # ['boolean', 'string']) #------------------------------------------------------------- words = read_words_after_key(file_unit, key_delim=key_delim, word_delim=word_delim) #---------------------------------------------- # If "dtype_list" is None, then assume that # every element in the list has type "dtype". #---------------------------------------------------- # NB! "dtype_list" cannot default to "[]", because # then values set from a previous call to this # function are remembered and used. #---------------------------------------------------- ## if (dtype_list == []): ## if (len(dtype_list) == 0): if (dtype_list is None): dtype_list = [] for k in xrange(len(words)): dtype_list.append( dtype.lower() ) elif (len(dtype_list) > len(words)): print 'ERROR in cfg_files.read_list_after_key().' print ' Not enough values in the line.' return ## print 'after: dtype =', dtype ## print 'after: dtype_list =', dtype_list ## print '--------------------------------' k = 0 yes_words = get_yes_words() var_list = [] for type_str in dtype_list: vtype = type_str.lower() word = words[k].strip() if (vtype == 'string'): var = word elif (vtype == 'boolean'): var = (word in yes_words) else: value = eval( word ) exec('var = numpy.' + vtype + '( value )') var_list.append( var ) k += 1 return var_list # read_list_after_key() #--------------------------------------------------------------------- def read_value(file_unit, dtype='string', key_delim=':'): #-------------------------------------------------------------- # Notes: Valid "var_types" are: # 'file', 'string', 'boolean' and any numpy dtype, # such as: # 'uint8', 'int16', 'int32', 'float32', 'float64' # If (var_type eq 'file'), then we want to read everything # after the ":", which may contain space characters in # the interior (e.g a directory), but with leading and # trailing spaces removed. #-------------------------------------------------------------- vtype = dtype.lower() if (vtype == 'file'): return read_line_after_key(file_unit, key_delim=key_delim) words = read_words_after_key( file_unit ) #-------------------- # Return a string ? #-------------------- if (vtype == 'string'): return words[0] #------------------------------------- # Return a boolean (True or False) ? #------------------------------------- if (vtype == 'boolean'): yes_words = get_yes_words() return (words[0].lower() in yes_words) #------------------------------------ # Try to convert string to a number #------------------------------------ try: value = eval(words[0]) except: print 'ERROR in cfg_files.read_value():' print ' Unable to convert string to number.' return words[0] #---------------------------------- # Return number of requested type #---------------------------------- exec('result = numpy.' + vtype + '( value )') return result # read_value() #--------------------------------------------------------------------- def var_type_code(var_type): cmap = {'scalar': 0, \ 'time_series': 1, \ 'time series': 1, \ 'grid' : 2, \ 'grid_stack' : 3, \ 'grid stack' : 3, \ 'grid_sequence': 3, \ 'grid sequence': 3 } code = cmap[ var_type.lower() ] return numpy.int16( code ) # var_type_code() #--------------------------------------------------------------------- def read_input_option(file_unit, key_delim=':', word_delim=None): words= read_words_after_key( file_unit, key_delim=key_delim, word_delim=word_delim ) #----------------------------------------------- # TopoFlow "var types" are: # Scalar, Time_Series, Grid, Grid_Sequence #----------------------------------------------- var_type = words[0].lower() if (var_type == 'scalar'): type_code = numpy.int16(0) scalar = numpy.float64( eval( words[1] ) ) filename = '' # (or use None ??) else: type_code = var_type_code( var_type ) scalar = None filename = words[1] return (type_code, scalar, filename) # read_input_option() #--------------------------------------------------------------------- def read_output_option(file_unit, key_delim=':', word_delim=None): #------------------------------- # Extract variables as strings #------------------------------- words = read_words_after_key( file_unit, key_delim=key_delim, word_delim=word_delim ) count = len(words) if (count == 0): print 'ERROR in cfg_files.read_output_option():' print ' No value found after delimiter.' return '' if (count == 1): print 'ERROR in cfg_files.read_output_option():' print ' No filename provided after option.' return '' yes_words = ['1','true','yes','on'] option = (words[0].lower() in yes_words) filename = words[1] return option, filename # read_output_option() #---------------------------------------------------------------------
mdpiper/topoflow
topoflow/utils/cfg_files.py
Python
mit
12,732
// Copyright (c) 2003 Compaq Corporation. All rights reserved. // Portions Copyright (c) 2003 Microsoft Corporation. All rights reserved. // Last modified on Mon 30 Apr 2007 at 13:33:37 PST by lamport // modified on Fri Sep 22 13:54:35 PDT 2000 by yuanyu package tlc2.tool.liveness; import tla2sany.semantic.LevelConstants; import tlc2.output.EC; import tlc2.tool.ITool; import tlc2.tool.TLCState; import util.Assert; /** * Handles always ([]) * * @author Leslie Lamport, Yuan Yu, Simon Zambrovski * @version $Id$ */ class LNAll extends LiveExprNode { /** * */ private static final String ALWAYS = "[]"; private final LiveExprNode body; public LNAll(LiveExprNode body) { this.body = body; } public final LiveExprNode getBody() { return this.body; } public final int getLevel() { return LevelConstants.TemporalLevel; } @Override public final boolean containAction() { return this.body.containAction(); } @Override public final boolean isPositiveForm() { return this.body.isPositiveForm(); } public final boolean eval(ITool tool, TLCState s1, TLCState s2) { Assert.fail(EC.TLC_LIVE_CANNOT_EVAL_FORMULA, ALWAYS); return false; // make compiler happy } public final void toString(StringBuffer sb, String padding) { sb.append(ALWAYS); this.getBody().toString(sb, padding + " "); } /* Return A if this expression is of form []<>A. */ public LiveExprNode getAEBody() { LiveExprNode allBody = getBody(); if (allBody instanceof LNEven) { return ((LNEven) allBody).getBody(); } return super.getAEBody(); } public void extractPromises(TBPar promises) { getBody().extractPromises(promises); } public int tagExpr(int tag) { return getBody().tagExpr(tag); } public final LiveExprNode makeBinary() { return new LNAll(getBody().makeBinary()); } public LiveExprNode flattenSingleJunctions() { return new LNAll(getBody().flattenSingleJunctions()); } public LiveExprNode simplify() { LiveExprNode body1 = getBody().simplify(); if (body1 instanceof LNAll) { body1 = ((LNAll) body1).getBody(); } return new LNAll(body1); } public boolean isGeneralTF() { LiveExprNode allBody = getBody(); if (allBody instanceof LNEven) { return false; } return super.isGeneralTF(); } public LiveExprNode pushNeg() { return new LNEven(getBody().pushNeg()); } public LiveExprNode pushNeg(boolean hasNeg) { if (hasNeg) { return new LNEven(getBody().pushNeg(true)); } else { return new LNAll(getBody().pushNeg(false)); } } public boolean equals(LiveExprNode exp) { if (exp instanceof LNAll) { return getBody().equals(((LNAll) exp).getBody()); } return false; } /* (non-Javadoc) * @see tlc2.tool.liveness.LiveExprNode#toDotViz() */ public String toDotViz() { return ALWAYS + getBody().toDotViz(); } }
lemmy/tlaplus
tlatools/org.lamport.tlatools/src/tlc2/tool/liveness/LNAll.java
Java
mit
2,829
import os import shutil import subprocess def which(program): def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: for path in os.environ["PATH"].split(os.pathsep): path = path.strip('"') exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file return None def install(omp=False, mpi=False, phdf5=False, dagmc=False): # Create build directory and change to it shutil.rmtree('build', ignore_errors=True) os.mkdir('build') os.chdir('build') # Build in debug mode by default cmake_cmd = ['cmake', '-Ddebug=on'] # Turn off OpenMP if specified if not omp: cmake_cmd.append('-Dopenmp=off') # Use MPI wrappers when building in parallel if mpi: os.environ['CXX'] = 'mpicxx' # Tell CMake to prefer parallel HDF5 if specified if phdf5: if not mpi: raise ValueError('Parallel HDF5 must be used in ' 'conjunction with MPI.') cmake_cmd.append('-DHDF5_PREFER_PARALLEL=ON') else: cmake_cmd.append('-DHDF5_PREFER_PARALLEL=OFF') if dagmc: cmake_cmd.append('-Ddagmc=ON') # Build in coverage mode for coverage testing cmake_cmd.append('-Dcoverage=on') # Build and install cmake_cmd.append('..') print(' '.join(cmake_cmd)) subprocess.check_call(cmake_cmd) subprocess.check_call(['make', '-j4']) subprocess.check_call(['sudo', 'make', 'install']) def main(): # Convert Travis matrix environment variables into arguments for install() omp = (os.environ.get('OMP') == 'y') mpi = (os.environ.get('MPI') == 'y') phdf5 = (os.environ.get('PHDF5') == 'y') dagmc = (os.environ.get('DAGMC') == 'y') # Build and install install(omp, mpi, phdf5, dagmc) if __name__ == '__main__': main()
liangjg/openmc
tools/ci/travis-install.py
Python
mit
2,019
<?php return array ( 'generalDesc' => array ( 'NationalNumberPattern' => '[2-9]\\d{6}', 'PossibleNumberPattern' => '\\d{7}', 'ExampleNumber' => '', ), 'fixedLine' => array ( 'NationalNumberPattern' => ' (?: 2(?: [034789]\\d| 1[0-7] )| 4(?: [013-8]\\d| 2[4-7] )| [56]\\d{2}| 8(?: 14| 3[129] ) )\\d{4} ', 'PossibleNumberPattern' => '\\d{7}', 'ExampleNumber' => '2012345', ), 'mobile' => array ( 'NationalNumberPattern' => ' (?: 25\\d| 4(?: 2[12389]| 9\\d )| 7\\d{2}| 87[15-8]| 9[1-8]\\d )\\d{4} ', 'PossibleNumberPattern' => '\\d{7}', 'ExampleNumber' => '2512345', ), 'tollFree' => array ( 'NationalNumberPattern' => '80[012]\\d{4}', 'PossibleNumberPattern' => '\\d{7}', 'ExampleNumber' => '8001234', ), 'premiumRate' => array ( 'NationalNumberPattern' => '30\\d{5}', 'PossibleNumberPattern' => '\\d{7}', 'ExampleNumber' => '3012345', ), 'sharedCost' => array ( 'NationalNumberPattern' => 'NA', 'PossibleNumberPattern' => 'NA', 'ExampleNumber' => '', ), 'noInternationalDialling' => array ( 'NationalNumberPattern' => 'NA', 'PossibleNumberPattern' => 'NA', 'ExampleNumber' => '', ), 'id' => 'MU', 'countryCode' => 230, 'internationalPrefix' => '0(?:[2-7]0|33)', 'preferredInternationalPrefix' => '020', 'sameMobileAndFixedLinePattern' => false, 'numberFormat' => array ( 0 => array ( 'pattern' => '([2-9]\\d{2})(\\d{4})', 'format' => '$1 $2', 'leadingDigitsPatterns' => array ( ), 'nationalPrefixFormattingRule' => '', 'domesticCarrierCodeFormattingRule' => '', ), ), 'intlNumberFormat' => array ( ), 'mainCountryForCode' => NULL, 'leadingZeroPossible' => NULL, );
kokone/wp-phone-number
libphonenumber/data/PhoneNumberMetadata_MU.php
PHP
mit
2,103
package org.cdlib.xtf.textIndexer; /** * Copyright (c) 2006, Regents of the University of California * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of the University of California nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Acknowledgements: * * A significant amount of new and/or modified code in this module * was made possible by a grant from the Andrew W. Mellon Foundation, * as part of the Melvyl Recommender Project. */ import java.io.File; import org.apache.lucene.index.IndexReader; import org.apache.lucene.spelt.SpellWriter; import org.apache.lucene.util.ProgressTracker; import org.cdlib.xtf.util.Path; import org.cdlib.xtf.util.Trace; //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /** * This class provides a simple mechanism for generating a spelling correction * dictionary after new documents have been added or updated. <br><br> * * To use this class, simply instantiate a copy, and call the * {@link IdxTreeDictMaker#processDir(File) processDir()} * method on a directory containing an index. Note that the directory passed * may also be a root directory with many index sub-directories if desired. */ public class IdxTreeDictMaker { //////////////////////////////////////////////////////////////////////////// /** * Create an <code>IdxTreeDictMaker</code> instance and call this method to * create spelling dictionaries for one or more Lucene indices. <br><br> * * @param dir The index database directory to scan. May be a * directory containing a single index, or the root * directory of a tree containing multiple indices. * <br><br> * * @.notes This method also calls itself recursively to process * potential index sub-directories below the passed * directory. */ public void processDir(File dir) throws Exception { // If the file we were passed was in fact a directory... if (dir.getAbsoluteFile().isDirectory()) { // And it contains an index, optimize it. if (IndexReader.indexExists(dir.getAbsoluteFile())) makeDict(dir); else { // Get the list of files it contains. String[] files = dir.getAbsoluteFile().list(); // And process each of them. for (int i = 0; i < files.length; i++) processDir(new File(dir, files[i])); } return; } // if( dir.isDirectory() ) // The current file is not a directory, so skip it. } // processDir() //////////////////////////////////////////////////////////////////////////// /** * Performs the actual work of creating a spelling dictionary. * <br><br> * * @param mainIdxDir The index database directory to scan. This * directory must contain a single Lucene index. * <br><br> * * @throws Exception Passes back any exceptions generated by Lucene * during the dictionary generation process. * <br><br> */ public void makeDict(File mainIdxDir) throws Exception { // Detect if spelling data is present. String indexPath = Path.normalizePath(mainIdxDir.toString()); String spellIdxPath = indexPath + "spellDict/"; String wordQueuePath = spellIdxPath + "newWords.txt"; String pairQueuePath = spellIdxPath + "newPairs.txt"; if (new File(wordQueuePath).length() < 1 && new File(pairQueuePath).length() < 1) { return; } // Tell what index we're working on... String mainIdxPath = Path.normalizePath(mainIdxDir.toString()); Trace.info("Index: [" + mainIdxPath + "] ... "); Trace.tab(); Trace.tab(); // for phase SpellWriter spellWriter = null; try { // Open the SpellWriter. We don't have to specify a stopword set for // this phase (it's only used during queuing.) // spellWriter = SpellWriter.open(new File(spellIdxPath)); spellWriter.setMinWordFreq(3); // Perform the update. spellWriter.flushQueuedWords(new ProgressTracker() { public void report(int pctDone, String descrip) { String pctTxt = Integer.toString(pctDone); while (pctTxt.length() < 3) pctTxt = " " + pctTxt; Trace.info("[" + pctTxt + "%] " + descrip); } }); } // try( to open the specified index ) catch (Exception e) { Trace.error("*** Dictionary Creation Halted Due to Error:" + e); throw e; } finally { spellWriter.close(); } Trace.untab(); // for phase Trace.untab(); Trace.info("Done."); } // makeDict() } // class IdxTreeDictMaker
CDLUC3/dash-xtf
xtf/WEB-INF/src/org/cdlib/xtf/textIndexer/IdxTreeDictMaker.java
Java
mit
6,314
<?php require_once(lib_path.'PHPMailer_5.2.1/class.phpmailer.php'); class Email{ /** * sendMsg * * Envia um e-mail utilizando a bibliteca PHPMailer. * * @version 1.0 * @param string $to E-mail do destinatário. * @param string $subject Assunto do e-mail. * @param string $msg Mensagem do e-mail (html). * @param string $configs Array com as configurações do envio. * Índice 'SMTPAuth' - Informa se a conexão com o SMTP será autenticada. * Índice 'SMTPSecure' - Define o padrão de segurança (SSL, TLS, STARTTLS). * Índice 'Host' - Host smtp para envio do e-mail. * Índice 'SMTPAuth' - Informa se a conexão com o SMTP será autenticada. * Índice 'Port' - Porta do SMTP para envio do e-mail. * Índice 'Username' - Usuário para autenticação do SMTP. * Índice 'Password' - Senha para autenticação do SMTP. * Índice 'AddReplyTo' - E-mail e nome para resposta do e-mail. * array( 0 => e-mail, 1 => nome) * Índice 'SetFrom' - E-mail e nome do remetente do e-mail. * array( 0 => e-mail, 1 => nome) * @param string $msg Mensagem do e-mail (html). * @param string $msg Mensagem do e-mail (html). * @param string $msg Mensagem do e-mail (html). * @return boolean / mensagens de erros Retorna true caso o e-mail tenha sido enviado ou as mensagens de erro caso não tenha sido enviado. */ public static function sendMsg($to,$subject,$msg,$configs = '',$debug = 1){ $configs = ($configs == '' || $configs == null)?Config::$email['default']: $configs; $configs = (is_string($configs))?Config::$email[$configs]: $configs; $mail = new PHPMailer(true); // True para a função enviar exceções de erros $mail->IsSMTP(); // Definindo a classe para utilizar SMTP. try { $mail->SMTPDebug = $debug; // Ativar informações de debug $mail->SMTPAuth = $configs['SMTPAuth']; // Informa se a conexão com o SMTP será autenticada. $mail->SMTPSecure = $configs['SMTPSecure'];// Define o padrão de segurança (SSL, TLS, STARTTLS). $mail->Host = $configs['Host']; // Host smtp para envio do e-mail. $mail->Port = $configs['Port'];; // Porta do SMTP para envio do e-mail. $mail->Username = $configs['Username']; // Usuário para autenticação do SMTP. $mail->Password = $configs['Password']; // Senha para autenticação do SMTP. $mail->AddAddress($to, ""); $mail->AddReplyTo($configs['AddReplyTo'][0], $configs['AddReplyTo'][1]); $mail->SetFrom($configs['SetFrom'][0], $configs['SetFrom'][1]); $mail->Subject = $subject; $mail->AltBody = 'Para ver essa mensagem utilize um programa compatível com e-mails em formato HTML!'; // optional - MsgHTML will create an alternate automatically $mail->MsgHTML($msg); $mail->Send(); return true; } catch (phpmailerException $e) { return $e->errorMessage(); // Mensagens de erro das exceções geradas pelo phpmailer. } catch (Exception $e) { return $e->getMessage(); // Mensagens de exceções geradas durante a execução da função. } } } ?>
AndrePessoa/Topo
topo/app/core/email.class.php
PHP
mit
3,191
'use strict'; var assert = require('assert') var Promise = require('promise') var connect = require('../') var client = connect({ version: 3, cache: 'file', auth: '90993e4e47b0fdd1f51f4c67b17368c62a3d6097' // github-basic-js-test }); describe('async', function () { it('can make simple api requests', function (done) { this.timeout(5000) client.get('/users/:user/gists', {user: 'ForbesLindesay'}, function (err, res) { if (err) return done(err) assert(Array.isArray(res)) res.forEach(function (gist) { assert(typeof gist.url === 'string') assert(typeof gist.public === 'boolean') }) done() }) }) it('can have a `host` option passed in', function (done) { this.timeout(5000) client.headBuffer('https://github.com/ForbesLindesay/github-basic', done) }) it('can make streaming requests', function (done) { this.timeout(20000) client.getStream('/repos/:owner/:repo/subscribers', { owner: 'visionmedia', repo: 'jade', per_page: 100 }).buffer(function (err, res) { if (err) return done(err) assert(Array.isArray(res)) assert(res.length > 150) done() }) }) it('can make streaming requests for commits', function (done) { this.timeout(20000) client.getStream('/repos/:owner/:repo/commits', { owner: 'ForbesLindesay', repo: 'browserify-middleware', per_page: 100 }).buffer(function (err, res) { if (err) return done(err) assert(Array.isArray(res)) assert(res.length > 140) done() }) }) it('can make streaming requests with just one page', function (done) { this.timeout(20000) client.getStream('/repos/:owner/:repo/subscribers', { owner: 'ForbesLindesay', repo: 'github-basic', per_page: 100 }).buffer(function (err, res) { if (err) return done(err) assert(Array.isArray(res)) done() }) }) describe('helpers', function () { describe('exists(user, repo)', function () { it('returns `true` if a repo exists', function (done) { client.exists('ForbesLindesay', 'pull-request', function (err, res) { if (err) return done(err); assert(res === true); done(); }); }); it('returns `false` if a repo does not exist', function (done) { client.exists('ForbesLindesay', 'i-wont-ever-create-this', function (err, res) { if (err) return done(err); assert(res === false); done(); }); }); }); var branch = (new Date()).toISOString().replace(/[^0-9a-zA-Z]+/g, '') + 'async'; describe('fork(user, repo, options)', function () { it('forks `user/repo` to the current user', function (done) { this.timeout(60000); client.fork('ForbesLindesay', 'pull-request-test', function (err, res) { if (err) return done(err); client.exists('github-basic-js-test', 'pull-request-test', function (err, res) { if (err) return done(err); assert(res === true); done(); }); }); }); }); describe('branch(user, repo, form, to, options)', function () { it('creates a new branch `to` in `user/repo` based on `from`', function (done) { this.timeout(10000); client.branch('github-basic-js-test', 'pull-request-test', 'master', branch, function (err, res) { if (err) return done(err); client.head('/repos/github-basic-js-test/pull-request-test/git/refs/heads/:branch', {branch: branch}, done); }); }); }); describe('commit(commit, options)', function () { it('commits an update to a branch', function (done) { this.timeout(15000) var commit = { branch: branch, message: 'test commit', updates: [{path: 'test-file.txt', content: 'lets-add-a-file wahooo'}] }; client.commit('github-basic-js-test', 'pull-request-test', commit, function (err, res) { if (err) return done(err); client.head('https://github.com/github-basic-js-test/pull-request-test/blob/' + branch + '/test-file.txt', done); }); }); }); describe('pull(from, to, message, options)', function () { it('creates a pull request', function (done) { this.timeout(15000) var from = { user: 'github-basic-js-test', repo: 'pull-request-test', branch: branch }; var to = { user: 'github-basic-js-test', repo: 'pull-request-test', branch: 'master' }; var message = { title: branch, body: 'A test pull request' }; client.pull(from, to, message, function (err, res) { if (err) return done(err); ///repos/github-basic-js-test/pull-request-test/pulls/1 client.head('/repos/github-basic-js-test/pull-request-test/pulls/' + res.number, done); }); }); }); }); });
scriptit/github-basic
test/async.js
JavaScript
mit
5,038
class PeopleController < HasAccountsController def index set_collection_ivar resource_class.search( params[:by_text], :star => true, :page => params[:page] ) end def show # Invoice scoping by state @invoices = resource.invoices.where("type != 'Salary'").invoice_state(params[:invoice_state]) show! end # has_many :phone_numbers def new_phone_number if resource_id = params[:id] @person = Person.find(resource_id) else @person = resource_class.new end @vcard = @person.vcard @item = @vcard.contacts.build respond_with @item end end
hauledev/has_account_engine
spec/dummy/app/controllers/people_controller.rb
Ruby
mit
624
// moment.js locale configuration // locale : Russian [ru] // author : Viktorminator : https://github.com/Viktorminator // Author : Menelion Elensúle : https://github.com/Oire // author : Коренберг Марк : https://github.com/socketpair function plural(word, num) { var forms = word.split('_'); return num % 10 === 1 && num % 100 !== 11 ? forms[0] : (num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20) ? forms[1] : forms[2]); } function relativeTimeWithPlural(num, withoutSuffix, key) { var format = { mm: withoutSuffix ? 'минута_минуты_минут' : 'минуту_минуты_минут', hh: 'час_часа_часов', dd: 'день_дня_дней', MM: 'месяц_месяца_месяцев', yy: 'год_года_лет' }; if (key === 'm') { return withoutSuffix ? 'минута' : 'минуту'; } else { return num + " " + plural(format[key], +num); } } var monthsParse = [/^янв/i, /^фев/i, /^мар/i, /^апр/i, /^ма[йя]/i, /^июн/i, /^июл/i, /^авг/i, /^сен/i, /^окт/i, /^ноя/i, /^дек/i]; // http://new.gramota.ru/spravka/rules/139-prop : § 103 // Сокращения месяцев: http://new.gramota.ru/spravka/buro/search-answer?s=242637 // CLDR data: http://www.unicode.org/cldr/charts/28/summary/ru.html#1753 export var ru = { abbr: 'ru', months: { format: 'января_февраля_марта_апреля_мая_июня_июля_августа_сентября_октября_ноября_декабря'.split('_'), standalone: 'январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь'.split('_') }, monthsShort: { // по CLDR именно "июл." и "июн.", но какой смысл менять букву на точку ? format: 'янв._февр._мар._апр._мая_июня_июля_авг._сент._окт._нояб._дек.'.split('_'), standalone: 'янв._февр._март_апр._май_июнь_июль_авг._сент._окт._нояб._дек.'.split('_') }, weekdays: { standalone: 'воскресенье_понедельник_вторник_среда_четверг_пятница_суббота'.split('_'), format: 'воскресенье_понедельник_вторник_среду_четверг_пятницу_субботу'.split('_'), isFormat: /\[ ?[Вв] ?(?:прошлую|следующую|эту)? ?\] ?dddd/ }, weekdaysShort: 'вс_пн_вт_ср_чт_пт_сб'.split('_'), weekdaysMin: 'вс_пн_вт_ср_чт_пт_сб'.split('_'), monthsParse: monthsParse, longMonthsParse: monthsParse, shortMonthsParse: monthsParse, // полные названия с падежами, по три буквы, для некоторых, по 4 буквы, сокращения с точкой и без точки monthsRegex: /^(январ[ья]|янв\.?|феврал[ья]|февр?\.?|марта?|мар\.?|апрел[ья]|апр\.?|ма[йя]|июн[ья]|июн\.?|июл[ья]|июл\.?|августа?|авг\.?|сентябр[ья]|сент?\.?|октябр[ья]|окт\.?|ноябр[ья]|нояб?\.?|декабр[ья]|дек\.?)/i, // копия предыдущего monthsShortRegex: /^(январ[ья]|янв\.?|феврал[ья]|февр?\.?|марта?|мар\.?|апрел[ья]|апр\.?|ма[йя]|июн[ья]|июн\.?|июл[ья]|июл\.?|августа?|авг\.?|сентябр[ья]|сент?\.?|октябр[ья]|окт\.?|ноябр[ья]|нояб?\.?|декабр[ья]|дек\.?)/i, // полные названия с падежами monthsStrictRegex: /^(январ[яь]|феврал[яь]|марта?|апрел[яь]|ма[яй]|июн[яь]|июл[яь]|августа?|сентябр[яь]|октябр[яь]|ноябр[яь]|декабр[яь])/i, // Выражение, которое соотвествует только сокращённым формам monthsShortStrictRegex: /^(янв\.|февр?\.|мар[т.]|апр\.|ма[яй]|июн[ья.]|июл[ья.]|авг\.|сент?\.|окт\.|нояб?\.|дек\.)/i, longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD.MM.YYYY', LL: 'D MMMM YYYY г.', LLL: 'D MMMM YYYY г., HH:mm', LLLL: 'dddd, D MMMM YYYY г., HH:mm' }, relativeTime: { future: 'через %s', past: '%s назад', s: 'несколько секунд', m: relativeTimeWithPlural, mm: relativeTimeWithPlural, h: 'час', hh: relativeTimeWithPlural, d: 'день', dd: relativeTimeWithPlural, M: 'месяц', MM: relativeTimeWithPlural, y: 'год', yy: relativeTimeWithPlural }, meridiemParse: /ночи|утра|дня|вечера/i, isPM: function (input) { return /^(дня|вечера)$/.test(input); }, meridiem: function (hour) { if (hour < 4) { return 'ночи'; } else if (hour < 12) { return 'утра'; } else if (hour < 17) { return 'дня'; } else { return 'вечера'; } }, dayOfMonthOrdinalParse: /\d{1,2}-(й|го|я)/, ordinal: function (num, period) { switch (period) { case 'M': case 'd': case 'DDD': return num + "-\u0439"; case 'D': return num + "-\u0433\u043E"; case 'w': case 'W': return num + "-\u044F"; default: return num.toString(10); } }, week: { dow: 1, doy: 4 // The week that contains Jan 4th is the first week of the year. } }; //# sourceMappingURL=ru.js.map
CatsPoo/ShiftOnline
angular.src/node_modules/ngx-bootstrap/bs-moment/i18n/ru.js
JavaScript
mit
6,071
var express = require('express'); var router = express.Router(); var request = require('request'); // Setup Redis Client var redis = require("redis"); var client = redis.createClient(process.env.REDISCACHE_SSLPORT, process.env.REDISCACHE_HOSTNAME, { auth_pass: process.env.REDISCACHE_PRIMARY_KEY, tls: { servername: process.env.REDISCACHE_HOSTNAME } }); /* GET dashboard. */ router.get('/', function (req, res) { // Query the API for incident data getIncidents().then(function (incidents) { // Render view res.render('dashboard', { title: 'Outage Dashboard', incidents: incidents }); }); }); module.exports = router; function getIncidents() { return new Promise(function (resolve, reject) { // Check cache for incidentData key client.get('incidentData', function (error, reply) { if (reply) { // Cached key exists console.log('Cached key found'); // Parse results var incidents; if (reply === 'undefined') { // No results, return null incidents = null; } else { incidents = JSON.parse(reply); } // Resolve Promise with incident data resolve(incidents); } else { // Cached key does not exist console.log('Cached key not found'); // Define URL to use for the API var apiUrl = `${process.env.INCIDENT_API_URL}/incidents`; // Make a GET request with the Request libary request(apiUrl, { json: true }, function (error, results, body) { // Store results in cache client.set("incidentData", JSON.stringify(body), 'EX', 60, function (error, reply) { console.log('Stored results in cache'); }); // Resolve Promise with incident data resolve(body); }); } }); }); }
AzureCAT-GSI/DevCamp
HOL/node/03-azuread-office365/start/routes/dashboard.js
JavaScript
mit
2,173
require 'rails_helper' RSpec.describe PusherController, :type => :controller do describe "GET webhook" do it "returns http success" do get :webhook expect(response).to be_success end end end
nnluukhtn/coffee_run
spec/controllers/pusher_controller_spec.rb
Ruby
mit
218
 namespace S22.Xmpp.Extensions { /// <summary> /// Defines possible values for the mood of an XMPP user. /// </summary> /// <remarks>Refer to XEP-0107 for a detailed listing and description of the /// various mood values.</remarks> public enum Mood { /// <summary> /// Impressed with fear or apprehension; in fear; apprehensive. /// </summary> Afraid, /// <summary> /// Astonished; confounded with fear, surprise or wonder. /// </summary> Amazed, /// <summary> /// Inclined to love; having a propensity to love, or to sexual enjoyment; /// loving, fond, affectionate, passionate, lustful, sexual, etc. /// </summary> Amarous, /// <summary> /// Displaying or feeling anger, i.e., a strong feeling of displeasure, hostility /// or antagonism towards someone or something, usually combined with an urge /// to harm. /// </summary> Angry, /// <summary> /// To be disturbed or irritated, especially by continued or repeated acts. /// </summary> Annoyed, /// <summary> /// Full of anxiety or disquietude; greatly concerned or solicitous, esp. /// respecting something future or unknown; being in painful suspense. /// </summary> Anxious, /// <summary> /// To be stimulated in one's feelings, especially to be sexually stimulated. /// </summary> Aroused, /// <summary> /// Feeling shame or guilt. /// </summary> Ashamed, /// <summary> /// Suffering from boredom; uninterested, without attention. /// </summary> Bored, /// <summary> /// Strong in the face of fear; courageous. /// </summary> Brave, /// <summary> /// Peaceful, quiet. /// </summary> Calm, /// <summary> /// Taking care or caution; tentative. /// </summary> Cautious, /// <summary> /// Feeling the sensation of coldness, especially to the point of discomfort. /// </summary> Cold, /// <summary> /// Feeling very sure of or positive about something, especially about one's /// own capabilities. /// </summary> Confident, /// <summary> /// Chaotic, jumbled or muddled. /// </summary> Confused, /// <summary> /// Feeling introspective or thoughtful. /// </summary> Contemplative, /// <summary> /// Pleased at the satisfaction of a want or desire; satisfied. /// </summary> Contented, /// <summary> /// Grouchy, irritable; easily upset. /// </summary> Cranky, /// <summary> /// Feeling out of control; feeling overly excited or enthusiastic. /// </summary> Crazy, /// <summary> /// Feeling original, expressive, or imaginative. /// </summary> Creative, /// <summary> /// Inquisitive; tending to ask questions, investigate, or explore. /// </summary> Curious, /// <summary> /// Feeling sad and dispirited. /// </summary> Dejected, /// <summary> /// Severely despondent and unhappy. /// </summary> Depressed, /// <summary> /// Defeated of expectation or hope; let down. /// </summary> Disappointed, /// <summary> /// Filled with disgust; irritated and out of patience. /// </summary> Disgusted, /// <summary> /// Feeling a sudden or complete loss of courage in the face of trouble or danger. /// </summary> Dismayed, /// <summary> /// Having one's attention diverted; preoccupied. /// </summary> Distracted, /// <summary> /// Having a feeling of shameful discomfort. /// </summary> Embarrassed, /// <summary> /// Feeling pain by the excellence or good fortune of another. /// </summary> Envious, /// <summary> /// Having great enthusiasm. /// </summary> Excited, /// <summary> /// In the mood for flirting. /// </summary> Flirtatious, /// <summary> /// Suffering from frustration; dissatisfied, agitated, or discontented because /// one is unable to perform an action or fulfill a desire. /// </summary> Frustrated, /// <summary> /// Feeling appreciation or thanks. /// </summary> Grateful, /// <summary> /// Feeling very sad about something, especially something lost; mournful; /// sorrowful. /// </summary> Grieving, /// <summary> /// Unhappy and irritable. /// </summary> Grumpy, /// <summary> /// Feeling responsible for wrongdoing; feeling blameworthy. /// </summary> Guilty, /// <summary> /// Experiencing the effect of favourable fortune; having the feeling arising /// from the consciousness of well-being or of enjoyment; enjoying good of /// any kind, as peace, tranquillity, comfort; contented; joyous. /// </summary> Happy, /// <summary> /// Having a positive feeling, belief, or expectation that something wished /// for can or will happen. /// </summary> Hopeful, /// <summary> /// Feeling the sensation of heat, especially to the point of discomfort. /// </summary> Hot, /// <summary> /// Having or showing a modest or low estimate of one's own importance; /// feeling lowered in dignity or importance. /// </summary> Humbled, /// <summary> /// Feeling deprived of dignity or self-respect. /// </summary> Humiliated, /// <summary> /// Having a physical need for food. /// </summary> Hungry, /// <summary> /// Wounded, injured, or pained, whether physically or emotionally. /// </summary> Hurt, /// <summary> /// Favourably affected by something or someone. /// </summary> Impressed, /// <summary> /// Feeling amazement at something or someone; or feeling a combination /// of fear and reverence. /// </summary> InAwe, /// <summary> /// Feeling strong affection, care, liking, or attraction. /// </summary> InLove, /// <summary> /// Showing anger or indignation, especially at something unjust or wrong. /// </summary> Indignant, /// <summary> /// Showing great attention to something or someone; having or showing /// interest. /// </summary> Interested, /// <summary> /// Under the influence of alcohol; drunk. /// </summary> Intoxicated, /// <summary> /// Feeling as if one cannot be defeated, overcome or denied. /// </summary> Invincible, /// <summary> /// Fearful of being replaced in position or affection. /// </summary> Jealous, /// <summary> /// Feeling isolated, empty, or abandoned. /// </summary> Lonely, /// <summary> /// Unable to find one's way, either physically or emotionally. /// </summary> Lost, /// <summary> /// Feeling as if one will be favored by luck. /// </summary> Lucky, /// <summary> /// Causing or intending to cause intentional harm; bearing ill will /// towards another; cruel; malicious. /// </summary> Mean, /// <summary> /// Given to sudden or frequent changes of mind or feeling; temperamental. /// </summary> Moody, /// <summary> /// Easily agitated or alarmed; apprehensive or anxious. /// </summary> Nervous, /// <summary> /// Not having a strong mood or emotional state. /// </summary> Neutral, /// <summary> /// Feeling emotionally hurt, displeased, or insulted. /// </summary> Offended, /// <summary> /// Feeling resentful anger caused by an extremely violent or vicious attack, /// or by an offensive, immoral, or indecent act. /// </summary> Outraged, /// <summary> /// Interested in play; fun, recreational, unserious, lighthearted; joking, /// silly. /// </summary> Playful, /// <summary> /// Feeling a sense of one's own worth or accomplishment. /// </summary> Proud, /// <summary> /// Having an easy-going mood; not stressed; calm. /// </summary> Relaxed, /// <summary> /// Feeling uplifted because of the removal of stress or discomfort. /// </summary> Relieved, /// <summary> /// Feeling regret or sadness for doing something wrong. /// </summary> Remorseful, /// <summary> /// Without rest; unable to be still or quiet; uneasy; continually moving. /// </summary> Restless, /// <summary> /// Feeling sorrow; sorrowful, mournful. /// </summary> Sad, /// <summary> /// Mocking and ironical. /// </summary> Sarcastic, /// <summary> /// Pleased at the fulfillment of a need or desire. /// </summary> Satisfied, /// <summary> /// Without humor or expression of happiness; grave in manner or disposition; /// earnest; thoughtful; solemn. /// </summary> Serious, /// <summary> /// Surprised, startled, confused, or taken aback. /// </summary> Shocked, /// <summary> /// Feeling easily frightened or scared; timid; reserved or coy. /// </summary> Shy, /// <summary> /// Feeling in poor health; ill. /// </summary> Sick, /// <summary> /// Feeling the need for sleep. /// </summary> Sleepy, /// <summary> /// Acting without planning; natural; impulsive. /// </summary> Spontaneous, /// <summary> /// Suffering emotional pressure. /// </summary> Stressed, /// <summary> /// Capable of producing great physical force; or, emotionally forceful, /// able, determined, unyielding. /// </summary> Strong, /// <summary> /// Experiencing a feeling caused by something unexpected. /// </summary> Surprised, /// <summary> /// Showing appreciation or gratitude. /// </summary> Thankful, /// <summary> /// Feeling the need to drink. /// </summary> Thirsty, /// <summary> /// In need of rest or sleep. /// </summary> Tired, /// <summary> /// [Feeling any emotion not defined here.] /// </summary> Undefined, /// <summary> /// Lacking in force or ability, either physical or emotional. /// </summary> Weak, /// <summary> /// Thinking about unpleasant things that have happened or that might /// happen; feeling afraid and unhappy. /// </summary> Worried } }
smiley22/S22.Xmpp
Extensions/XEP-0107/Mood.cs
C#
mit
9,671
using System.Windows.Controls; namespace HeroesMatchTracker.Views.RawData { /// <summary> /// Interaction logic for RawMatchReplaysControl.xaml /// </summary> public partial class RawMatchReplaysControl : UserControl { public RawMatchReplaysControl() { InitializeComponent(); } } }
koliva8245/HeroesParserData
HeroesMatchTracker/Views/RawData/RawMatchReplaysControl.xaml.cs
C#
mit
346
<?php return [ 'nav-back' => '回上一頁', 'nav-new' => '新增資料夾', 'nav-upload' => '上傳檔案', 'nav-thumbnails' => '縮圖顯示', 'nav-list' => '列表顯示', 'menu-rename' => '重新命名', 'menu-delete' => '刪除', 'menu-view' => '預覽', 'menu-download' => '下載', 'menu-resize' => '縮放', 'menu-crop' => '裁剪', 'title-page' => '檔案管理', 'title-panel' => '檔案管理', 'title-upload' => '上傳檔案', 'title-view' => '預覽檔案', 'title-root' => '我的檔案', 'title-shares' => '共享的檔案', 'title-item' => '項目名稱', 'title-size' => '檔案大小', 'title-type' => '檔案類型', 'title-modified' => '上次修改', 'title-action' => '操作', 'type-folder' => '資料夾', 'message-empty' => '空的資料夾', 'message-choose' => '選擇檔案', 'message-delete' => '確定要刪除此項目嗎?', 'message-name' => '資料夾名稱:', 'message-rename' => '重新命名為:', 'message-extension_not_found' => '請安裝 gd 或 imagick 以使用縮放、裁剪、及縮圖功能', 'error-rename' => '名稱重複,請重新輸入!', 'error-file-empty' => '請選擇檔案!', 'error-file-exist' => '相同檔名的檔案已存在!', 'error-file-size' => '檔案過大,無法上傳! (檔案大小上限: :max)', 'error-delete' => '資料夾未清空,無法刪除!', 'error-folder-name' => '請輸入資料夾名稱!', 'error-folder-exist'=> '相同名稱的資料夾已存在!', 'error-folder-alnum'=> '資料夾名稱只能包含英數字!', 'error-mime' => 'Mime 格式錯誤 : ', 'error-instance' => '上傳檔案的 instance 應為 UploadedFile', 'error-invalid' => '驗證失敗,上傳未成功', 'btn-upload' => '上傳', 'btn-uploading' => '上傳中...', 'btn-close' => '關閉', 'btn-crop' => '裁剪', 'btn-cancel' => '取消', 'btn-resize' => '縮放', 'resize-ratio' => '比例:', 'resize-scaled' => '是否已縮放:', 'resize-true' => '是', 'resize-old-height' => '原始高度:', 'resize-old-width' => '原始寬度:', 'resize-new-height' => '目前高度:', 'resize-new-width' => '目前寬度:', 'locale-bootbox' => 'zh_TW', ];
crocodic-studio/simple-stock-manager
vendor/unisharp/laravel-filemanager/src/lang/zh-TW/lfm.php
PHP
mit
2,606
System.register([], function (_export, _context) { "use strict"; var p; return { setters: [], execute: function () { _export("p", p = 4); _export("p", p); } }; });
ModuleLoader/es-module-loader
test/fixtures/register-modules/rebinding.js
JavaScript
mit
197
#!/usr/bin/env python """ Apply a surface field to a shape """ from __future__ import print_function import argparse import time import sys import re from numpy import linspace from icqsol.shapes.icqShapeManager import ShapeManager from icqsol import util # time stamp tid = re.sub(r'\.', '', str(time.time())) description = 'Apply a surface field to a shape' parser = argparse.ArgumentParser(description=description) parser.add_argument('--input', dest='input', default='', help='Input file (PLY or VTK)') parser.add_argument('--expression', dest='expression', default='sin(pi*x)*cos(pi*y)*z', help='Expression of x, y, z, and t') parser.add_argument('--refine', dest='refine', default=0.0, type=float, help='Maximum edge length (use 0 if no refinement)') parser.add_argument('--name', dest='name', default='myField', help='Set the name of the field') parser.add_argument('--times', dest='times', default='', help='Comma separated list of time values') parser.add_argument('--location', dest='location', default='point', help='"point" or "cell"') parser.add_argument('--ascii', dest='ascii', action='store_true', help='Save data in ASCII format (default is binary)') parser.add_argument('--output', dest='output', default='addSurfaceFieldFromExpressionToShape-{0}.vtk'.format(tid), help='VTK Output file.') args = parser.parse_args() if not args.expression: print('ERROR: must specify --expression <expression>') sys.exit(2) if not args.input: print('ERROR: must specify input file: --input <file>') sys.exit(3) # make sure the field name contains no spaces args.name = re.sub('\s', '_', args.name) # Get the format of the input - either vtk or ply. file_format = util.getFileFormat(args.input) if file_format == util.PLY_FORMAT: shape_mgr = ShapeManager(file_format=util.PLY_FORMAT) else: # We have a VTK file, so Get the dataset type. vtk_dataset_type = util.getVtkDatasetType(args.input) shape_mgr = ShapeManager(file_format=util.VTK_FORMAT, vtk_dataset_type=vtk_dataset_type) pdata = shape_mgr.loadAsVtkPolyData(args.input) times = [0.0] if args.times: times = eval(args.times) maxEdgeLength = float('inf') if args.refine > 0: maxEdgeLength = args.refine pdataOut = shape_mgr.addSurfaceFieldFromExpressionToVtkPolyData(pdata, args.name, args.expression, times, max_edge_length=maxEdgeLength, location=args.location) if args.output: # Always produce VTK POLYDATA. shape_mgr.setWriter(file_format=util.VTK_FORMAT, vtk_dataset_type=util.POLYDATA) if args.ascii: file_type = util.ASCII else: file_type = util.BINARY shape_mgr.saveVtkPolyData(vtk_poly_data=pdataOut, file_name=args.output, file_type=file_type)
gregvonkuster/icqsol
examples/addSurfaceFieldFromExpression.py
Python
mit
3,166
using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using Tailviewer.Api; namespace Tailviewer.Core.Filters.ExpressionEngine { internal sealed class IsExpression<T> : IExpression<bool> { private static readonly IEqualityComparer<T> Comparer; private readonly IExpression<T> _lhs; private readonly IExpression<T> _rhs; static IsExpression() { // The default comparer sucks for custom value types as it will cause boxing on every invocation // (https://www.jacksondunstan.com/articles/5148), so we will use our own comparers for types known // to us. if (typeof(T) == typeof(LevelFlags)) { Comparer = (IEqualityComparer<T>)(object)new LevelFlagsComparer(); } else { Comparer = EqualityComparer<T>.Default; } } public IsExpression(IExpression<T> lhs, IExpression<T> rhs) { _lhs = lhs; _rhs = rhs; } #region Implementation of IExpression public Type ResultType => typeof(bool); public bool Evaluate(IReadOnlyList<IReadOnlyLogEntry> logEntry) { var lhs = _lhs.Evaluate(logEntry); var rhs = _rhs.Evaluate(logEntry); return Comparer.Equals(lhs, rhs); } object IExpression.Evaluate(IReadOnlyList<IReadOnlyLogEntry> logEntry) { return Evaluate(logEntry); } #endregion #region Equality members private bool Equals(IsExpression<T> other) { return Equals(_lhs, other._lhs) && Equals(_rhs, other._rhs); } public override bool Equals(object obj) { return ReferenceEquals(this, obj) || obj is IsExpression<T> other && Equals(other); } public override int GetHashCode() { unchecked { return ((_lhs != null ? _lhs.GetHashCode() : 0) * 397) ^ (_rhs != null ? _rhs.GetHashCode() : 0); } } public static bool operator ==(IsExpression<T> left, IsExpression<T> right) { return Equals(left, right); } public static bool operator !=(IsExpression<T> left, IsExpression<T> right) { return !Equals(left, right); } #endregion #region Overrides of Object public override string ToString() { return string.Format("{0} {1} {2}", _lhs, Tokenizer.ToString(TokenType.Is), _rhs); } #endregion [Pure] public static IsExpression<T> Create(IExpression<T> lhs, IExpression<T> rhs) { return new IsExpression<T>(lhs, rhs); } } }
Kittyfisto/Tailviewer
src/Tailviewer.Core/Filters/ExpressionEngine/IsExpression.cs
C#
mit
2,319
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle 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 3 of the License, or // (at your option) any later version. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Strings for component 'enrol_imsenterprise', language 'ru', branch 'MOODLE_20_STABLE' * * @package enrol_imsenterprise * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); $string['aftersaving...'] = 'После сохранения своих настроек Вы, возможно, пожелаете'; $string['allowunenrol'] = 'Разрешить данным IMS <strong>отчислять</strong> студентов/преподавателей'; $string['allowunenrol_desc'] = 'При включенном параметре, участник будет отчислен из курса, если это указано в данных организации.'; $string['basicsettings'] = 'Основные настройки'; $string['coursesettings'] = 'Настройки данных курса'; $string['createnewcategories'] = 'Создавать новые (скрытые) категории курсов, если они не найдены в Moodle'; $string['createnewcategories_desc'] = 'Если элемент <org><orgunit> присутствует в данных создаваемого курса, то эта информация будет использоваться для определения категории, если курс должен быть создан с нуля. Плагин НЕ будет изменять категории существующих курсов. Если нет категории с нужным названием, то будет создана скрытая категория.'; $string['createnewcourses'] = 'Создавать новые (скрытые) курсы, если они не найдены в Moodle'; $string['createnewcourses_desc'] = 'При включенном параметре плагин IMS может создать новые курсы для любого из найденных в данных IMS, но не в базе данных в Moodle. Любой вновь созданный курс изначально скрыт.'; $string['createnewusers'] = 'Создать учетные записи для пользователей, еще не зарегистрированных в Moodle'; $string['createnewusers_desc'] = 'IMS Enterprise - типичные данные для регистрации, характеризующие группу пользователей. При включенном параметре учетная запись может быть создана для любого пользователя, отсутствующего в базе данных Moodle. Пользователей сначала ищут по их «ID-номеру», потом - по их логину в Moodle. Пароли не импортируются с помощью плагина IMS Enterprise. Для аутентификации пользователей рекомендуется использовать плагин аутентификации'; $string['cronfrequency'] = 'Частота обработки'; $string['deleteusers'] = 'Удалять учетные записи пользователей, если это указано в данных IMS'; $string['deleteusers_desc'] = 'При включенном параметре в данных IMS можно указать удаление учетных записей пользователей (если в параметре «recstatus» выбран п.3, который означает удаление аккаунта). Как это принято в Moodle, запись пользователя не удаляется из базы данных Moodle, но устанавливается флаг, который помечает аккаунт как удаленный.'; $string['doitnow'] = 'Выполнить импорт IMS прямо сейчас'; $string['filelockedmail'] = 'Процесс cron не может удалить IMS-файл ({$a}), используемый вами для записи на курсы. Обычно это означает, что неправильно установлены права доступа к этому файлу. Пожалуйста, исправьте права доступа так, чтобы система Moodle могла удалять этот файл. В противном случае один и тот же файл будет обрабатываться повторно.'; $string['filelockedmailsubject'] = 'Серьезная ошибка: Файл регистрации'; $string['fixcasepersonalnames'] = 'Изменить личные имена пользователей в Верхний Регистр'; $string['fixcaseusernames'] = 'Изменить логины в нижний регистр'; $string['ignore'] = 'Игнорировать'; $string['importimsfile'] = 'Импорт файла IMS Enterprise'; $string['imsrolesdescription'] = 'Спецификация IMS Enterprise включает в себя 8 различных типов роль. Пожалуйста, выберите, как Вы хотите назначить их в Moodle, при этом любая из них может быть проигнорирована.'; $string['location'] = 'Расположение файла'; $string['logtolocation'] = 'Расположение файла журнала (пусто, если протоколирование не ведется)'; $string['mailadmins'] = 'Уведомить администратора по электронной почте'; $string['mailusers'] = 'Уведомить пользователей по электронной почте'; $string['miscsettings'] = 'Разное'; $string['pluginname'] = 'Файл IMS Enterprise'; $string['pluginname_desc'] = 'Этот способ записи будет неоднократно проверять и обрабатывать специально-форматированный текстовый файл в указанном Вами месте. Файл должен следовать спецификации IMS Enterprise и содержать XML-элементы person, group и membership.'; $string['processphoto'] = 'Добавить данные о фотографии пользователя в профиль'; $string['processphotowarning'] = 'Внимание: обработка изображений может добавить значительную нагрузку на сервер. Рекомендуется не активировать эту опцию, если ожидается обработка большого количества студентов.'; $string['restricttarget'] = 'Обрабатывать данные только если указана следующая цель'; $string['restricttarget_desc'] = 'Файл данных IMS Enterprise может быть предназначен для нескольких «целей» - разных систем обучения или различных систем внутри школы/университета. В файле можно указать, что данные предназначены для одной или нескольких целевых именованных систем, именуя их в тегах <target>, содержащихся в теге <properties>. Обычно Вам не нужно беспокоиться об этом. Оставьте поле пустым и Moodle всегда будет обрабатывать данные файла, независимо от того, задана ли цель или нет. В противном случае введите в поле точное название, которое будет присутствовать внутри тега <target>.'; $string['roles'] = 'Роли'; $string['sourcedidfallback'] = 'Использовать идентификатор «sourcedid» для персонального идентификатора, если поле «userid» не найдено'; $string['sourcedidfallback_desc'] = 'В данных IMS поле <sourcedid> является постоянным ID-кодом человека, используемый в исходной системе. Поле <userid> - это отдельное поле, которое содержит ID-код, используемый пользователем при входе. Во многих случаях эти два кода могут быть одинаковы - но не всегда. Некоторые системы не могут выводить информацию из поля <userid>. В этом случае Вы должны включить этот параметр - разрешить использовать поле <sourcedid> в качестве ID-номера пользователя Moodle. В противном случае оставьте этот параметр отключенным.'; $string['truncatecoursecodes'] = 'Обрезать коды курсов до этой длины'; $string['truncatecoursecodes_desc'] = 'В некоторых случаях перед обработкой Вы можете обрезать коды курсов до указанной длины. Для этого введите нужное количество символов в этом поле. В противном случае оставьте это поле пустым и никаких сокращений не будет.'; $string['usecapitafix'] = 'Отметьте это поле, если используется «Capita» (его формат XML немного неверный)'; $string['usecapitafix_desc'] = 'При получении «Capita» была найдена одна небольшая ошибка в XML-выводе из системы студенческих данных. При использовании «Capita» Вы должны включить этот параметр; в противном случае оставьте его не отмеченным.'; $string['usersettings'] = 'Настройки данных пользователя'; $string['zeroisnotruncation'] = '0 указывает на отсутствие усечения';
tesler/cspt-moodle
moodle/lang/ru/enrol_imsenterprise.php
PHP
mit
11,218
module.exports = { //get global stats 'GET /stat': { controller: "StatController", action: "getGlobalStat" } }
badfuture/huoshui-backend-api
api/routes/statRoute.js
JavaScript
mit
126
/** * Node Native Module for Lib Sodium * * @Author Pedro Paixao * @email paixaop at gmail dot com * @License MIT */ #include "node_sodium.h" /** * int crypto_shorthash( * unsigned char *out, * const unsigned char *in, * unsigned long long inlen, * const unsigned char *key) * * Parameters: * [out] out result of hash * [in] in input buffer * [in] inlen size of input buffer * [in] key key buffer * * A lot of applications and programming language implementations have been * recently found to be vulnerable to denial-of-service attacks when a hash * function with weak security guarantees, like Murmurhash 3, was used to * construct a hash table. * In order to address this, Sodium provides the �shorthash� function, * currently implemented using SipHash-2-4. This very fast hash function * outputs short, but unpredictable (without knowing the secret key) values * suitable for picking a list in a hash table for a given key. */ NAPI_METHOD(crypto_shorthash) { Napi::Env env = info.Env(); ARGS(1, "argument message must be a buffer"); ARG_TO_UCHAR_BUFFER(message); ARG_TO_UCHAR_BUFFER_LEN(key, crypto_shorthash_KEYBYTES); NEW_BUFFER_AND_PTR(hash, crypto_shorthash_BYTES); if( crypto_shorthash(hash_ptr, message, message_size, key) == 0 ) { return hash; } else { return NAPI_NULL; } } /** * Register function calls in node binding */ void register_crypto_shorthash(Napi::Env env, Napi::Object exports) { // Short Hash EXPORT(crypto_shorthash); EXPORT_INT(crypto_shorthash_BYTES); EXPORT_INT(crypto_shorthash_KEYBYTES); EXPORT_STRING(crypto_shorthash_PRIMITIVE); }
paixaop/node-sodium
src/crypto_shorthash.cc
C++
mit
1,709
# frozen_string_literal: true Capybara::SpecHelper.spec '#scroll_to', requires: [:scroll] do before do @session.visit('/scroll') end it 'can scroll an element to the top of the viewport' do el = @session.find(:css, '#scroll') @session.scroll_to(el, align: :top) expect(el.evaluate_script('this.getBoundingClientRect().top')).to be_within(1).of(0) end it 'can scroll an element to the bottom of the viewport' do el = @session.find(:css, '#scroll') @session.scroll_to(el, align: :bottom) el_bottom = el.evaluate_script('this.getBoundingClientRect().bottom') viewport_bottom = el.evaluate_script('document.documentElement.clientHeight') expect(el_bottom).to be_within(1).of(viewport_bottom) end it 'can scroll an element to the center of the viewport' do el = @session.find(:css, '#scroll') @session.scroll_to(el, align: :center) el_center = el.evaluate_script('(function(rect){return (rect.top + rect.bottom)/2})(this.getBoundingClientRect())') viewport_bottom = el.evaluate_script('document.documentElement.clientHeight') expect(el_center).to be_within(2).of(viewport_bottom / 2) end it 'can scroll the window to the vertical top' do @session.scroll_to :bottom @session.scroll_to :top expect(@session.evaluate_script('[window.scrollX || window.pageXOffset, window.scrollY || window.pageYOffset]')).to eq [0, 0] end it 'can scroll the window to the vertical bottom' do @session.scroll_to :bottom max_scroll = @session.evaluate_script('document.documentElement.scrollHeight - document.documentElement.clientHeight') expect(@session.evaluate_script('[window.scrollX || window.pageXOffset, window.scrollY || window.pageYOffset]')).to eq [0, max_scroll] end it 'can scroll the window to the vertical center' do @session.scroll_to :center max_scroll = @session.evaluate_script('document.documentElement.scrollHeight - document.documentElement.clientHeight') expect(@session.evaluate_script('[window.scrollX || window.pageXOffset, window.scrollY || window.pageYOffset]')).to eq [0, max_scroll / 2] end it 'can scroll the window to specific location' do @session.scroll_to 100, 100 expect(@session.evaluate_script('[window.scrollX || window.pageXOffset, window.scrollY || window.pageYOffset]')).to eq [100, 100] end it 'can scroll an element to the top of the scrolling element' do scrolling_element = @session.find(:css, '#scrollable') el = scrolling_element.find(:css, '#inner') scrolling_element.scroll_to(el, align: :top) scrolling_element_top = scrolling_element.evaluate_script('this.getBoundingClientRect().top') expect(el.evaluate_script('this.getBoundingClientRect().top')).to be_within(3).of(scrolling_element_top) end it 'can scroll an element to the bottom of the scrolling element' do scrolling_element = @session.find(:css, '#scrollable') el = scrolling_element.find(:css, '#inner') scrolling_element.scroll_to(el, align: :bottom) el_bottom = el.evaluate_script('this.getBoundingClientRect().bottom') scroller_bottom = scrolling_element.evaluate_script('this.getBoundingClientRect().top + this.clientHeight') expect(el_bottom).to be_within(1).of(scroller_bottom) end it 'can scroll an element to the center of the scrolling element' do scrolling_element = @session.find(:css, '#scrollable') el = scrolling_element.find(:css, '#inner') scrolling_element.scroll_to(el, align: :center) el_center = el.evaluate_script('(function(rect){return (rect.top + rect.bottom)/2})(this.getBoundingClientRect())') scrollable_center = scrolling_element.evaluate_script('(this.clientHeight / 2) + this.getBoundingClientRect().top') expect(el_center).to be_within(1).of(scrollable_center) end it 'can scroll the scrolling element to the top' do scrolling_element = @session.find(:css, '#scrollable') scrolling_element.scroll_to :bottom scrolling_element.scroll_to :top expect(scrolling_element.evaluate_script('[this.scrollLeft, this.scrollTop]')).to eq [0, 0] end it 'can scroll the scrolling element to the bottom' do scrolling_element = @session.find(:css, '#scrollable') scrolling_element.scroll_to :bottom max_scroll = scrolling_element.evaluate_script('this.scrollHeight - this.clientHeight') expect(scrolling_element.evaluate_script('[this.scrollLeft, this.scrollTop]')).to eq [0, max_scroll] end it 'can scroll the scrolling element to the vertical center' do scrolling_element = @session.find(:css, '#scrollable') scrolling_element.scroll_to :center max_scroll = scrolling_element.evaluate_script('this.scrollHeight - this.clientHeight') expect(scrolling_element.evaluate_script('[this.scrollLeft, this.scrollTop]')).to eq [0, max_scroll / 2] end it 'can scroll the scrolling element to specific location' do scrolling_element = @session.find(:css, '#scrollable') scrolling_element.scroll_to 100, 100 expect(scrolling_element.evaluate_script('[this.scrollLeft, this.scrollTop]')).to eq [100, 100] end it 'can scroll the window by a specific amount' do @session.scroll_to(:current, offset: [50, 75]) expect(@session.evaluate_script('[window.scrollX || window.pageXOffset, window.scrollY || window.pageYOffset]')).to eq [50, 75] end it 'can scroll the scroll the scrolling element by a specific amount' do scrolling_element = @session.find(:css, '#scrollable') scrolling_element.scroll_to 100, 100 scrolling_element.scroll_to(:current, offset: [-50, 50]) expect(scrolling_element.evaluate_script('[this.scrollLeft, this.scrollTop]')).to eq [50, 150] end end
jnicklas/capybara
lib/capybara/spec/session/scroll_spec.rb
Ruby
mit
5,689
package main import ( "context" "encoding/json" "log" "os" "path/filepath" "time" "github.com/mafredri/cdp" "github.com/mafredri/cdp/devtool" "github.com/mafredri/cdp/protocol/page" "github.com/mafredri/cdp/rpcc" ) func main() { dir, err := os.Getwd() if err != nil { log.Fatal(err) } if err := run(context.TODO(), dir); err != nil { log.Fatal(err) } } func run(ctx context.Context, dir string) error { var cancel context.CancelFunc ctx, cancel = context.WithTimeout(ctx, 10*time.Second) defer cancel() devt := devtool.New("http://localhost:9222") pt, err := devt.Get(ctx, devtool.Page) if err != nil { return err } conn, err := rpcc.Dial(pt.WebSocketDebuggerURL) if err != nil { return err } defer conn.Close() c := cdp.NewClient(conn) input, err := os.Create(filepath.Join(dir, "log.input")) if err != nil { return err } consoleAPICalled, err := c.Runtime.ConsoleAPICalled(ctx) if err != nil { return err } go func() { defer consoleAPICalled.Close() for { ev, err := consoleAPICalled.Recv() if err != nil { return } // Reset fields that would cause noise in diffs. ev.ExecutionContextID = 0 ev.Timestamp = 0 ev.StackTrace = nil for i, arg := range ev.Args { arg.ObjectID = nil ev.Args[i] = arg } if err = json.NewEncoder(input).Encode(ev); err != nil { log.Println(err) return } } }() domLoadTimeout := 5 * time.Second // First page load is to trigger console log behavior without object // previews. if err := navigate(c.Page, "file:///"+dir+"/log.html", domLoadTimeout); err != nil { return err } // Enable console log events. if err := c.Runtime.Enable(ctx); err != nil { return err } // Re-load the page to receive console logs with previews. if err := navigate(c.Page, "file:///"+dir+"/log.html", domLoadTimeout); err != nil { return err } time.Sleep(250 * time.Millisecond) if err := input.Close(); err != nil { return err } return nil } // navigate to the URL and wait for DOMContentEventFired. An error is // returned if timeout happens before DOMContentEventFired. func navigate(pc cdp.Page, url string, timeout time.Duration) error { ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() // Enable the Page domain events. if err := pc.Enable(ctx); err != nil { return err } // Open client for DOMContentEventFired to pause execution until // DOM has fully loaded. domContentEventFired, err := pc.DOMContentEventFired(ctx) if err != nil { return err } defer domContentEventFired.Close() _, err = pc.Navigate(ctx, page.NewNavigateArgs(url)) if err != nil { return err } _, err = domContentEventFired.Recv() return err }
mafredri/cdp
protocol/runtime/testdata/log_input_gen.go
GO
mit
2,730
<?php namespace BeSimple\SoapClient\Tests\AxisInterop; class TestCase extends \PHPUnit_Framework_TestCase { protected function setUp() { $ch = curl_init('http://localhost:8080/'); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_NOBODY, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); if (curl_exec($ch) === false) { $this->markTestSkipped( 'The Axis server is not started on port 8080.' ); } curl_close($ch); } }
MarkThink/OROCRM
vendor/bundles/besimple/soap/src/BeSimple/SoapClient/Tests/AxisInterop/TestCase.php
PHP
mit
602
'use strict'; var digits = require('./../../../utils/number').digits; // TODO this could be improved by simplifying seperated constants under associative and commutative operators function factory(type, config, load, typed, math) { var util = load(require('./util')); var isCommutative = util.isCommutative; var isAssociative = util.isAssociative; var allChildren = util.allChildren; var createMakeNodeFunction = util.createMakeNodeFunction; var ConstantNode = math.expression.node.ConstantNode; var OperatorNode = math.expression.node.OperatorNode; var FunctionNode = math.expression.node.FunctionNode; function simplifyConstant(expr) { var res = foldFraction(expr); return type.isNode(res) ? res : _toNode(res); } function _eval(fnname, args) { try { return _toNumber(math[fnname].apply(null, args)); } catch (ignore) { // sometimes the implicit type conversion causes the evaluation to fail, so we'll try again after removing Fractions args = args.map(function(x){ if (type.isFraction(x)) { return x.valueOf(); } return x; }); return _toNumber(math[fnname].apply(null, args)); } } var _toNode = typed({ 'Fraction': _fractionToNode, 'number': function(n) { if (n < 0) { return unaryMinusNode(new ConstantNode(-n)); } return new ConstantNode(n); }, 'BigNumber': function(n) { if (n < 0) { return unaryMinusNode(new ConstantNode(n.negated().toString(), 'number')); } return new ConstantNode(n.toString(), 'number'); }, 'Complex': function(s) { throw 'Cannot convert Complex number to Node'; } }); // convert a number to a fraction only if it can be expressed exactly function _exactFraction(n) { if (isFinite(n)) { var f = math.fraction(n); if (f.valueOf() === n) { return f; } } return n; } // Convert numbers to a preferred number type in preference order: Fraction, number, Complex // BigNumbers are left alone var _toNumber = typed({ 'string': function(s) { if (config.number === 'BigNumber') { return math.bignumber(s); } else if (config.number === 'Fraction') { return math.fraction(s); } else { return _exactFraction(parseFloat(s)); } }, 'Fraction': function(s) { return s; }, 'BigNumber': function(s) { return s; }, 'number': function(s) { return _exactFraction(s); }, 'Complex': function(s) { if (s.im !== 0) { return s; } return _exactFraction(s.re); }, }); function unaryMinusNode(n) { return new OperatorNode('-', 'unaryMinus', [n]); } function _fractionToNode(f) { var n; var vn = f.s*f.n; if (vn < 0) { n = new OperatorNode('-', 'unaryMinus', [new ConstantNode(-vn)]) } else { n = new ConstantNode(vn); } if (f.d === 1) { return n; } return new OperatorNode('/', 'divide', [n, new ConstantNode(f.d)]); } /* * Create a binary tree from a list of Fractions and Nodes. * Tries to fold Fractions by evaluating them until the first Node in the list is hit, so * `args` should be sorted to have the Fractions at the start (if the operator is commutative). * @param args - list of Fractions and Nodes * @param fn - evaluator for the binary operation evaluator that accepts two Fractions * @param makeNode - creates a binary OperatorNode/FunctionNode from a list of child Nodes * if args.length is 1, returns args[0] * @return - Either a Node representing a binary expression or Fraction */ function foldOp(fn, args, makeNode) { return args.reduce(function(a, b) { if (!type.isNode(a) && !type.isNode(b)) { try { return _eval(fn, [a,b]); } catch (ignoreandcontinue) {} a = _toNode(a); b = _toNode(b); } else if (!type.isNode(a)) { a = _toNode(a); } else if (!type.isNode(b)) { b = _toNode(b); } return makeNode([a, b]); }); } // destroys the original node and returns a folded one function foldFraction(node) { switch(node.type) { case 'SymbolNode': return node; case 'ConstantNode': if (node.valueType === 'number') { return _toNumber(node.value); } return node; case 'FunctionNode': if (math[node.name] && math[node.name].rawArgs) { return node; } // Process operators as OperatorNode var operatorFunctions = [ 'add', 'multiply' ]; if (operatorFunctions.indexOf(node.name) === -1) { var args = node.args.map(foldFraction); // If all args are numbers if (!args.some(type.isNode)) { try { return _eval(node.name, args); } catch (ignoreandcontine) {} } // Convert all args to nodes and construct a symbolic function call args = args.map(function(arg) { return type.isNode(arg) ? arg : _toNode(arg); }); return new FunctionNode(node.name, args); } else { // treat as operator } /* falls through */ case 'OperatorNode': var fn = node.fn.toString(); var args; var res; var makeNode = createMakeNodeFunction(node); if (node.args.length === 1) { args = [foldFraction(node.args[0])]; if (!type.isNode(args[0])) { res = _eval(fn, args); } else { res = makeNode(args); } } else if (isAssociative(node)) { args = allChildren(node); args = args.map(foldFraction); if (isCommutative(fn)) { // commutative binary operator var consts = [], vars = []; for (var i=0; i < args.length; i++) { if (!type.isNode(args[i])) { consts.push(args[i]); } else { vars.push(args[i]); } } if (consts.length > 1) { res = foldOp(fn, consts, makeNode); vars.unshift(res); res = foldOp(fn, vars, makeNode); } else { // we won't change the children order since it's not neccessary res = foldOp(fn, args, makeNode); } } else { // non-commutative binary operator res = foldOp(fn, args, makeNode); } } else { // non-associative binary operator args = node.args.map(foldFraction); res = foldOp(fn, args, makeNode); } return res; case 'ParenthesisNode': // remove the uneccessary parenthesis return foldFraction(node.content); case 'AccessorNode': /* falls through */ case 'ArrayNode': /* falls through */ case 'AssignmentNode': /* falls through */ case 'BlockNode': /* falls through */ case 'FunctionAssignmentNode': /* falls through */ case 'IndexNode': /* falls through */ case 'ObjectNode': /* falls through */ case 'RangeNode': /* falls through */ case 'UpdateNode': /* falls through */ case 'ConditionalNode': /* falls through */ default: throw 'Unimplemented node type in simplifyConstant: '+node.type; } } return simplifyConstant; } exports.math = true; exports.name = 'simplifyConstant'; exports.path = 'algebra.simplify'; exports.factory = factory;
ocadni/citychrone
node_modules/mathjs/lib/function/algebra/simplify/simplifyConstant.js
JavaScript
mit
7,764
<?php /* If you see this text in your browser, PHP is not configured correctly on this hosting provider. Contact your hosting provider regarding PHP configuration for your site. PHP file generated by Adobe Muse CC 2017.1.0.379 */ function formthrottle_check() { if (!is_writable('.')) { return '8'; } try { if (in_array("sqlite",PDO::getAvailableDrivers(),TRUE)) { $db = new PDO('sqlite:muse-throttle-db.sqlite3'); if ( file_exists('muse-throttle-db') ) { unlink('muse-throttle-db'); } } else if (function_exists("sqlite_open")) { $db = new PDO('sqlite2:muse-throttle-db'); if ( file_exists('muse-throttle-db.sqlite3') ) { unlink('muse-throttle-db.sqlite3'); } } else { return '4'; } } catch( PDOException $Exception ) { return '9'; } $retCode ='5'; if ($db) { $res = $db->query("SELECT 1 FROM sqlite_master WHERE type='table' AND name='Submission_History';"); if (!$res or $res->fetchColumn() == 0) { $created = $db->exec("CREATE TABLE Submission_History (IP VARCHAR(39), Submission_Date TIMESTAMP)"); if($created == 0) { $created = $db->exec("INSERT INTO Submission_History (IP,Submission_Date) VALUES ('256.256.256.256', DATETIME('now'))"); } if ($created != 1) { $retCode = '2'; } } if($retCode == '5') { $res = $db->query("SELECT COUNT(1) FROM Submission_History;"); if ($res && $res->fetchColumn() > 0) { $retCode = '0'; } else $retCode = '3'; } // Close file db connection $db = null; } else $retCode = '4'; return $retCode; } function formthrottle_too_many_submissions($ip) { $tooManySubmissions = false; try { if (in_array("sqlite",PDO::getAvailableDrivers(),TRUE)) { $db = new PDO('sqlite:muse-throttle-db.sqlite3'); } else if (function_exists("sqlite_open")) { $db = new PDO('sqlite2:muse-throttle-db'); } else { return false; } } catch( PDOException $Exception ) { return $tooManySubmissions; } if ($db) { $res = $db->query("SELECT 1 FROM sqlite_master WHERE type='table' AND name='Submission_History';"); if (!$res or $res->fetchColumn() == 0) { $db->exec("CREATE TABLE Submission_History (IP VARCHAR(39), Submission_Date TIMESTAMP)"); } $db->exec("DELETE FROM Submission_History WHERE Submission_Date < DATETIME('now','-2 hours')"); $stmt = $db->prepare("INSERT INTO Submission_History (IP,Submission_Date) VALUES (:ip, DATETIME('now'))"); $stmt->bindParam(':ip', $ip); $stmt->execute(); $stmt->closeCursor(); $stmt = $db->prepare("SELECT COUNT(1) FROM Submission_History WHERE IP = :ip;"); $stmt->bindParam(':ip', $ip); $stmt->execute(); if ($stmt->fetchColumn() > 25) $tooManySubmissions = true; // Close file db connection $db = null; } return $tooManySubmissions; } ?>
valesbc/valesbc.github.io
scripts/form_throttle.php
PHP
mit
2,961
/** * @author Richard Davey <rich@photonstorm.com> * @copyright 2022 Photon Storm Ltd. * @license {@link https://opensource.org/licenses/MIT|MIT License} */ /** * Rotates the vertices of a Face to the given angle. * * The actual vertex positions are adjusted, not their transformed positions. * * Therefore, this updates the vertex data directly. * * @function Phaser.Geom.Mesh.RotateFace * @since 3.50.0 * * @param {Phaser.Geom.Mesh.Face} face - The Face to rotate. * @param {number} angle - The angle to rotate to, in radians. * @param {number} [cx] - An optional center of rotation. If not given, the Face in-center is used. * @param {number} [cy] - An optional center of rotation. If not given, the Face in-center is used. */ var RotateFace = function (face, angle, cx, cy) { var x; var y; // No point of rotation? Use the inCenter instead, then. if (cx === undefined && cy === undefined) { var inCenter = face.getInCenter(); x = inCenter.x; y = inCenter.y; } var c = Math.cos(angle); var s = Math.sin(angle); var v1 = face.vertex1; var v2 = face.vertex2; var v3 = face.vertex3; var tx = v1.x - x; var ty = v1.y - y; v1.set(tx * c - ty * s + x, tx * s + ty * c + y); tx = v2.x - x; ty = v2.y - y; v2.set(tx * c - ty * s + x, tx * s + ty * c + y); tx = v3.x - x; ty = v3.y - y; v3.set(tx * c - ty * s + x, tx * s + ty * c + y); }; module.exports = RotateFace;
photonstorm/phaser
src/geom/mesh/RotateFace.js
JavaScript
mit
1,512
/******************************************************************************* * Copyright (c) 2013-2016 LAAS-CNRS (www.laas.fr) * 7 Colonel Roche 31077 Toulouse - France * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Initial Contributors: * Thierry Monteil : Project manager, technical co-manager * Mahdi Ben Alaya : Technical co-manager * Samir Medjiah : Technical co-manager * Khalil Drira : Strategy expert * Guillaume Garzone : Developer * François Aïssaoui : Developer * * New contributors : *******************************************************************************/ package org.eclipse.om2m.core.controller; import org.eclipse.om2m.commons.exceptions.NotImplementedException; import org.eclipse.om2m.commons.exceptions.OperationNotAllowed; import org.eclipse.om2m.commons.resource.RequestPrimitive; import org.eclipse.om2m.commons.resource.ResponsePrimitive; /** * Controller for polling channel URI * */ public class PollingChannelUriController extends Controller { @Override public ResponsePrimitive doCreate(RequestPrimitive request) { throw new OperationNotAllowed("Create on PollingChannelUri is not allowed"); } @Override public ResponsePrimitive doRetrieve(RequestPrimitive request) { throw new NotImplementedException("Retrieve operation on PollingChannelURI is not implemented"); } @Override public ResponsePrimitive doUpdate(RequestPrimitive request) { throw new OperationNotAllowed("Update on PollingChannelUri is not allowed"); } @Override public ResponsePrimitive doDelete(RequestPrimitive request) { throw new OperationNotAllowed("Delete on PollingChannelUri is not allowed"); } }
cloudcomputinghust/IoT
docker/oneM2M/CSE_IPE/org.eclipse.om2m/org.eclipse.om2m.core/src/main/java/org/eclipse/om2m/core/controller/PollingChannelUriController.java
Java
mit
1,885
/*! * iCheck v1.0.3, http://git.io/arlzeA * =================================== * Powerful jQuery and Zepto plugin for checkboxes and radio buttons customization * * (c) 2013 Damir Sultanov, http://fronteed.com * MIT Licensed */ (function($) { // Cached vars var _iCheck = 'iCheck', _iCheckHelper = _iCheck + '-helper', _checkbox = 'checkbox', _radio = 'radio', _checked = 'checked', _unchecked = 'un' + _checked, _disabled = 'disabled', _determinate = 'determinate', _indeterminate = 'in' + _determinate, _update = 'update', _type = 'type', _click = 'click', _touch = 'touchbegin.i touchend.i', _add = 'addClass', _remove = 'removeClass', _callback = 'trigger', _label = 'label', _cursor = 'cursor', _mobile = /ip(hone|od|ad)|android|blackberry|windows phone|opera mini|silk/i.test(navigator.userAgent) || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1); // Plugin init $.fn[_iCheck] = function(options, fire) { // Walker var handle = 'input[type="' + _checkbox + '"], input[type="' + _radio + '"]', stack = $(), walker = function(object) { object.each(function() { var self = $(this); if (self.is(handle)) { stack = stack.add(self); } else { stack = stack.add(self.find(handle)); } }); }; // Check if we should operate with some method if (/^(check|uncheck|toggle|indeterminate|determinate|disable|enable|update|destroy)$/i.test(options)) { // Normalize method's name options = options.toLowerCase(); // Find checkboxes and radio buttons walker(this); return stack.each(function() { var self = $(this); if (options == 'destroy') { tidy(self, 'ifDestroyed'); } else { operate(self, true, options); } // Fire method's callback if ($.isFunction(fire)) { fire(); } }); // Customization } else if (typeof options == 'object' || !options) { // Check if any options were passed var settings = $.extend({ checkedClass: _checked, disabledClass: _disabled, indeterminateClass: _indeterminate, labelHover: true }, options), selector = settings.handle, hoverClass = settings.hoverClass || 'hover', focusClass = settings.focusClass || 'focus', activeClass = settings.activeClass || 'active', labelHover = !!settings.labelHover, labelHoverClass = settings.labelHoverClass || 'hover', // Setup clickable area area = ('' + settings.increaseArea).replace('%', '') | 0; // Selector limit if (selector == _checkbox || selector == _radio) { handle = 'input[type="' + selector + '"]'; } // Clickable area limit if (area < -50) { area = -50; } // Walk around the selector walker(this); return stack.each(function() { var self = $(this); // If already customized tidy(self); var node = this, id = node.id, // Layer styles offset = -area + '%', size = 100 + (area * 2) + '%', layer = { position: 'absolute', top: offset, left: offset, display: 'block', width: size, height: size, margin: 0, padding: 0, background: '#fff', border: 0, opacity: 0 }, // Choose how to hide input hide = _mobile ? { position: 'absolute', visibility: 'hidden' } : area ? layer : { position: 'absolute', opacity: 0 }, // Get proper class className = node[_type] == _checkbox ? settings.checkboxClass || 'i' + _checkbox : settings.radioClass || 'i' + _radio, // Find assigned labels label = $(_label + '[for="' + id + '"]').add(self.closest(_label)), // Check ARIA option aria = !!settings.aria, // Set ARIA placeholder ariaID = _iCheck + '-' + Math.random().toString(36).substr(2,6), // Parent & helper parent = '<div class="' + className + '" ' + (aria ? 'role="' + node[_type] + '" ' : ''), helper; // Set ARIA "labelledby" if (aria) { label.each(function() { parent += 'aria-labelledby="'; if (this.id) { parent += this.id; } else { this.id = ariaID; parent += ariaID; } parent += '"'; }); } // Wrap input parent = self.wrap(parent + '/>')[_callback]('ifCreated').parent().append(settings.insert); // Layer addition helper = $('<ins class="' + _iCheckHelper + '"/>').css(layer).appendTo(parent); // Finalize customization self.data(_iCheck, {o: settings, s: self.attr('style')}).css(hide); !!settings.inheritClass && parent[_add](node.className || ''); !!settings.inheritID && id && parent.attr('id', _iCheck + '-' + id); parent.css('position') == 'static' && parent.css('position', 'relative'); operate(self, true, _update); // Label events if (label.length) { label.on(_click + '.i mouseover.i mouseout.i ' + _touch, function(event) { var type = event[_type], item = $(this); // Do nothing if input is disabled if (!node[_disabled]) { // Click if (type == _click) { if ($(event.target).is('a')) { return; } operate(self, false, true); // Hover state } else if (labelHover) { // mouseout|touchend if (/ut|nd/.test(type)) { parent[_remove](hoverClass); item[_remove](labelHoverClass); } else { parent[_add](hoverClass); item[_add](labelHoverClass); } } if (_mobile) { event.stopPropagation(); } else { return false; } } }); } // Input events self.on(_click + '.i focus.i blur.i keyup.i keydown.i keypress.i', function(event) { var type = event[_type], key = event.keyCode; // Click if (type == _click) { return false; // Keydown } else if (type == 'keydown' && key == 32) { if (!(node[_type] == _radio && node[_checked])) { if (node[_checked]) { off(self, _checked); } else { on(self, _checked); } } return false; // Keyup } else if (type == 'keyup' && node[_type] == _radio) { !node[_checked] && on(self, _checked); // Focus/blur } else if (/us|ur/.test(type)) { parent[type == 'blur' ? _remove : _add](focusClass); } }); // Helper events helper.on(_click + ' mousedown mouseup mouseover mouseout ' + _touch, function(event) { var type = event[_type], // mousedown|mouseup toggle = /wn|up/.test(type) ? activeClass : hoverClass; // Do nothing if input is disabled if (!node[_disabled]) { // Click if (type == _click) { operate(self, false, true); // Active and hover states } else { // State is on if (/wn|er|in/.test(type)) { // mousedown|mouseover|touchbegin parent[_add](toggle); // State is off } else { parent[_remove](toggle + ' ' + activeClass); } // Label hover if (label.length && labelHover && toggle == hoverClass) { // mouseout|touchend label[/ut|nd/.test(type) ? _remove : _add](labelHoverClass); } } if (_mobile) { event.stopPropagation(); } else { return false; } } }); }); } else { return this; } }; // Do something with inputs function operate(input, direct, method) { var node = input[0], state = /er/.test(method) ? _indeterminate : /bl/.test(method) ? _disabled : _checked, active = method == _update ? { checked: node[_checked], disabled: node[_disabled], indeterminate: input.attr(_indeterminate) == 'true' || input.attr(_determinate) == 'false' } : node[state]; // Check, disable or indeterminate if (/^(ch|di|in)/.test(method) && !active) { on(input, state); // Uncheck, enable or determinate } else if (/^(un|en|de)/.test(method) && active) { off(input, state); // Update } else if (method == _update) { // Handle states for (var each in active) { if (active[each]) { on(input, each, true); } else { off(input, each, true); } } } else if (!direct || method == 'toggle') { // Helper or label was clicked if (!direct) { input[_callback]('ifClicked'); } // Toggle checked state if (active) { if (node[_type] !== _radio) { off(input, state); } } else { on(input, state); } } } // Add checked, disabled or indeterminate state function on(input, state, keep) { var node = input[0], parent = input.parent(), checked = state == _checked, indeterminate = state == _indeterminate, disabled = state == _disabled, callback = indeterminate ? _determinate : checked ? _unchecked : 'enabled', regular = option(input, callback + capitalize(node[_type])), specific = option(input, state + capitalize(node[_type])); // Prevent unnecessary actions if (node[state] !== true) { // Toggle assigned radio buttons if (!keep && state == _checked && node[_type] == _radio && node.name) { var form = input.closest('form'), inputs = 'input[name="' + node.name + '"]'; inputs = form.length ? form.find(inputs) : $(inputs); inputs.each(function() { if (this !== node && $(this).data(_iCheck)) { off($(this), state); } }); } // Indeterminate state if (indeterminate) { // Add indeterminate state node[state] = true; // Remove checked state if (node[_checked]) { off(input, _checked, 'force'); } // Checked or disabled state } else { // Add checked or disabled state if (!keep) { node[state] = true; } // Remove indeterminate state if (checked && node[_indeterminate]) { off(input, _indeterminate, false); } } // Trigger callbacks callbacks(input, checked, state, keep); } // Add proper cursor if (node[_disabled] && !!option(input, _cursor, true)) { parent.find('.' + _iCheckHelper).css(_cursor, 'default'); } // Add state class parent[_add](specific || option(input, state) || ''); // Set ARIA attribute if (!!parent.attr('role') && !indeterminate) { parent.attr('aria-' + (disabled ? _disabled : _checked), 'true'); } // Remove regular state class parent[_remove](regular || option(input, callback) || ''); } // Remove checked, disabled or indeterminate state function off(input, state, keep) { var node = input[0], parent = input.parent(), checked = state == _checked, indeterminate = state == _indeterminate, disabled = state == _disabled, callback = indeterminate ? _determinate : checked ? _unchecked : 'enabled', regular = option(input, callback + capitalize(node[_type])), specific = option(input, state + capitalize(node[_type])); // Prevent unnecessary actions if (node[state] !== false) { // Toggle state if (indeterminate || !keep || keep == 'force') { node[state] = false; } // Trigger callbacks callbacks(input, checked, callback, keep); } // Add proper cursor if (!node[_disabled] && !!option(input, _cursor, true)) { parent.find('.' + _iCheckHelper).css(_cursor, 'pointer'); } // Remove state class parent[_remove](specific || option(input, state) || ''); // Set ARIA attribute if (!!parent.attr('role') && !indeterminate) { parent.attr('aria-' + (disabled ? _disabled : _checked), 'false'); } // Add regular state class parent[_add](regular || option(input, callback) || ''); } // Remove all traces function tidy(input, callback) { if (input.data(_iCheck)) { // Remove everything except input input.parent().html(input.attr('style', input.data(_iCheck).s || '')); // Callback if (callback) { input[_callback](callback); } // Unbind events input.off('.i').unwrap(); $(_label + '[for="' + input[0].id + '"]').add(input.closest(_label)).off('.i'); } } // Get some option function option(input, state, regular) { if (input.data(_iCheck)) { return input.data(_iCheck).o[state + (regular ? '' : 'Class')]; } } // Capitalize some string function capitalize(string) { return string.charAt(0).toUpperCase() + string.slice(1); } // Executable handlers function callbacks(input, checked, callback, keep) { if (!keep) { if (checked) { input[_callback]('ifToggled'); } input[_callback]('change')[_callback]('ifChanged')[_callback]('if' + capitalize(callback)); } } })(window.jQuery || window.Zepto);
cdnjs/cdnjs
ajax/libs/iCheck/1.0.3/icheck.js
JavaScript
mit
14,225
module Voting class Domain include DataMapper::Resource property :id, Serial property :name, String property :created_at, DateTime property :updated_at, DateTime has n, :users, :class_name => "Voting::User", :child_key => [:domain_id] validates_present :name validates_is_unique :name end end
zapnap/voting
lib/voting/domain.rb
Ruby
mit
352
// Type definitions for @ag-grid-community/core v25.0.1 // Project: http://www.ag-grid.com/ // Definitions by: Niall Crosby <https://github.com/ag-grid/> import { Column } from "../entities/column"; import { CellChangedEvent, RowNode } from "../entities/rowNode"; import { CellEvent, FlashCellsEvent } from "../events"; import { Beans } from "./beans"; import { Component } from "../widgets/component"; import { ICellEditorComp } from "../interfaces/iCellEditor"; import { ICellRendererComp } from "./cellRenderers/iCellRenderer"; import { ColDef } from "../entities/colDef"; import { CellPosition } from "../entities/cellPosition"; import { RowComp } from "./row/rowComp"; import { IFrameworkOverrides } from "../interfaces/iFrameworkOverrides"; import { TooltipParentComp } from '../widgets/tooltipFeature'; import { ITooltipParams } from "./tooltipComponent"; export declare class CellComp extends Component implements TooltipParentComp { static DOM_DATA_KEY_CELL_COMP: string; private static CELL_RENDERER_TYPE_NORMAL; private static CELL_RENDERER_TYPE_PINNED; private eCellWrapper; private eCellValue; private beans; private column; private rowNode; private eParentRow; private cellPosition; private rangeCount; private hasChartRange; private usingWrapper; private wrapText; private includeSelectionComponent; private includeRowDraggingComponent; private includeDndSourceComponent; private cellFocused; private editingCell; private cellEditorInPopup; private hideEditorPopup; private createCellRendererFunc; private lastIPadMouseClickEvent; private usingCellRenderer; private cellRendererType; private cellRenderer; private cellRendererGui; private cellEditor; private selectionHandle; private autoHeightCell; private firstRightPinned; private lastLeftPinned; private rowComp; private rangeSelectionEnabled; private value; private valueFormatted; private colsSpanning; private rowSpan; private suppressRefreshCell; private tooltipFeatureEnabled; private tooltip; private scope; private readonly printLayout; private cellEditorVersion; private cellRendererVersion; constructor(scope: any, beans: Beans, column: Column, rowNode: RowNode, rowComp: RowComp, autoHeightCell: boolean, printLayout: boolean); getCreateTemplate(): string; private getStylesForRowSpanning; afterAttached(): void; private createTooltipFeatureIfNeeded; onColumnHover(): void; onCellChanged(event: CellChangedEvent): void; private getCellLeft; private getCellWidth; onFlashCells(event: FlashCellsEvent): void; private setupColSpan; getColSpanningList(): Column[]; private onDisplayColumnsChanged; private refreshAriaIndex; private getInitialCssClasses; getInitialValueToRender(): string; getRenderedRow(): RowComp; isSuppressNavigable(): boolean; getCellRenderer(): ICellRendererComp | null; getCellEditor(): ICellEditorComp | null; onNewColumnsLoaded(): void; private postProcessWrapText; refreshCell(params?: { suppressFlash?: boolean; newData?: boolean; forceRefresh?: boolean; }): void; flashCell(delays?: { flashDelay: number; fadeDelay: number; }): void; private animateCell; private replaceContentsAfterRefresh; private updateAngular1ScopeAndCompile; private angular1Compile; private postProcessStylesFromColDef; private preProcessStylesFromColDef; private processStylesFromColDef; private postProcessClassesFromColDef; private preProcessClassesFromColDef; private processClassesFromColDef; private putDataIntoCellAfterRefresh; attemptCellRendererRefresh(): boolean; private refreshToolTip; private valuesAreEqual; private getToolTip; getTooltipParams(): ITooltipParams; private getTooltipText; private processCellClassRules; private postProcessCellClassRules; private preProcessCellClassRules; setUsingWrapper(): void; private chooseCellRenderer; private createCellRendererInstance; private afterCellRendererCreated; private createCellRendererParams; private formatValue; private getValueToUse; private getValueAndFormat; private getValue; onMouseEvent(eventName: string, mouseEvent: MouseEvent): void; dispatchCellContextMenuEvent(event: Event): void; createEvent(domEvent: Event | null, eventType: string): CellEvent; private onMouseOut; private onMouseOver; private onCellDoubleClicked; startRowOrCellEdit(keyPress?: number | null, charPress?: string): void; isCellEditable(): boolean; startEditingIfEnabled(keyPress?: number | null, charPress?: string | null, cellStartedEdit?: boolean): void; private createCellEditor; private afterCellEditorCreated; private addInCellEditor; private addPopupCellEditor; private onPopupEditorClosed; private setInlineEditingClass; private createCellEditorParams; private stopEditingAndFocus; private parseValue; focusCell(forceBrowserFocus?: boolean): void; setFocusInOnEditor(): void; isEditing(): boolean; onKeyDown(event: KeyboardEvent): void; setFocusOutOnEditor(): void; private onNavigationKeyPressed; private onShiftRangeSelect; private onTabKeyDown; private onBackspaceOrDeleteKeyPressed; private onEnterKeyDown; private navigateAfterEdit; private onF2KeyDown; private onEscapeKeyDown; onKeyPress(event: KeyboardEvent): void; private onSpaceKeyPressed; private onMouseDown; private isRightClickInExistingRange; private containsWidget; private isDoubleClickOnIPad; private onCellClicked; private createGridCellVo; getCellPosition(): CellPosition; getParentRow(): HTMLElement; setParentRow(eParentRow: HTMLElement): void; getColumn(): Column; getComponentHolder(): ColDef; detach(): void; destroy(): void; onLeftChanged(): void; private modifyLeftForPrintLayout; onWidthChanged(): void; private getRangeBorders; private getInitialRangeClasses; onRowIndexChanged(): void; onRangeSelectionChanged(): void; private getHasChartRange; private shouldHaveSelectionHandle; private addSelectionHandle; updateRangeBordersIfRangeCount(): void; private refreshHandle; private updateRangeBorders; onFirstRightPinnedChanged(): void; onLastLeftPinnedChanged(): void; private populateTemplate; protected getFrameworkOverrides(): IFrameworkOverrides; private addRowDragging; private addDndSource; private addSelectionCheckbox; private addDomData; private isSingleCell; onCellFocused(event?: any): void; stopRowOrCellEdit(cancel?: boolean): void; stopEditing(cancel?: boolean): void; private clearCellElement; }
ceolter/angular-grid
community-modules/core/dist/es6/rendering/cellComp.d.ts
TypeScript
mit
6,950
using System; using Csla; namespace Invoices.DataAccess.Sql { public partial class ProductTypeCachedNVLDal { } }
CslaGenFork/CslaGenFork
trunk/CoverageTest/Invoices-CS-DAL-DR/Invoices.DataAccess.Sql/ProductTypeCachedNVLDal.cs
C#
mit
135
const Route = require('../../structures/Route'); class usersGET extends Route { constructor() { super('/admin/users', 'get', { adminOnly: true }); } async run(req, res, db) { try { const users = await db.table('users') .select('id', 'username', 'enabled', 'isAdmin', 'createdAt'); return res.json({ message: 'Successfully retrieved users', users }); } catch (error) { return super.error(res, error); } } } module.exports = usersGET;
WeebDev/lolisafe
src/api/routes/admin/usersGET.js
JavaScript
mit
473
import { Autowired, Bean, BeanStub, XmlElement } from '@ag-grid-community/core'; import coreFactory from './files/ooxml/core'; import contentTypesFactory from './files/ooxml/contentTypes'; import officeThemeFactory from './files/ooxml/themes/office'; import sharedStringsFactory from './files/ooxml/sharedStrings'; import stylesheetFactory, { registerStyles } from './files/ooxml/styles/stylesheet'; import workbookFactory from './files/ooxml/workbook'; import worksheetFactory from './files/ooxml/worksheet'; import relationshipsFactory from './files/ooxml/relationships'; import { ExcelStyle, ExcelWorksheet } from '@ag-grid-community/core'; import { XmlFactory } from "@ag-grid-community/csv-export"; /** * See https://www.ecma-international.org/news/TC45_current_work/OpenXML%20White%20Paper.pdf */ @Bean('excelXlsxFactory') export class ExcelXlsxFactory extends BeanStub { @Autowired('xmlFactory') private xmlFactory: XmlFactory; private sharedStrings: string[] = []; private sheetNames: string[]; public createSharedStrings(): string { return this.createXmlPart(sharedStringsFactory.getTemplate(this.sharedStrings)); } private createXmlPart(body: XmlElement): string { const header = this.xmlFactory.createHeader({ encoding: 'UTF-8', standalone: 'yes' }); const xmlBody = this.xmlFactory.createXml(body); return `${header}${xmlBody}`; } public createExcel(styles: ExcelStyle[], worksheets: ExcelWorksheet[], sharedStrings: string[] = []): string { this.sharedStrings = sharedStrings; this.sheetNames = worksheets.map(worksheet => worksheet.name); registerStyles(styles); return this.createWorksheet(worksheets); } public createCore(): string { return this.createXmlPart(coreFactory.getTemplate()); } public createContentTypes(): string { return this.createXmlPart(contentTypesFactory.getTemplate()); } public createRels(): string { const rs = relationshipsFactory.getTemplate([{ Id: 'rId1', Type: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument', Target: 'xl/workbook.xml' }, { Id: 'rId2', Type: 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties', Target: 'docProps/core.xml' }]); return this.createXmlPart(rs); } public createStylesheet(): string { return this.createXmlPart(stylesheetFactory.getTemplate()); } public createTheme(): string { return this.createXmlPart(officeThemeFactory.getTemplate()); } public createWorkbook(): string { return this.createXmlPart(workbookFactory.getTemplate(this.sheetNames)); } public createWorkbookRels(): string { const rs = relationshipsFactory.getTemplate([{ Id: 'rId1', Type: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet', Target: 'worksheets/sheet1.xml' }, { Id: 'rId2', Type: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme', Target: 'theme/theme1.xml' }, { Id: 'rId3', Type: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles', Target: 'styles.xml' }, { Id: 'rId4', Type: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings', Target: 'sharedStrings.xml' }]); return this.createXmlPart(rs); } public createWorksheet(worksheets: ExcelWorksheet[]): string { return this.createXmlPart(worksheetFactory.getTemplate(worksheets[0])); } }
ceolter/angular-grid
enterprise-modules/excel-export/src/excelExport/excelXlsxFactory.ts
TypeScript
mit
3,835
function DetailCellRenderer() {} DetailCellRenderer.prototype.init = function(params) { this.eGui = document.createElement('div'); this.eGui.innerHTML = '<h1 style="padding: 20px;">My Custom Detail</h1>'; }; DetailCellRenderer.prototype.getGui = function() { return this.eGui; };
ceolter/angular-grid
grid-packages/ag-grid-docs/documentation/src/pages/master-detail-custom-detail/examples/simple-custom-detail/detailCellRenderer_vanilla.js
JavaScript
mit
294
/* * * * (c) 2009-2017 Highsoft, Black Label * * License: www.highcharts.com/license * * */ 'use strict'; import H from '../parts/Globals.js'; import U from '../parts/Utilities.js'; var defined = U.defined, destroyObjectProperties = U.destroyObjectProperties, erase = U.erase, extend = U.extend, pick = U.pick, splat = U.splat, wrap = U.wrap; import '../parts/Chart.js'; import controllableMixin from './controllable/controllableMixin.js'; import ControllableRect from './controllable/ControllableRect.js'; import ControllableCircle from './controllable/ControllableCircle.js'; import ControllablePath from './controllable/ControllablePath.js'; import ControllableImage from './controllable/ControllableImage.js'; import ControllableLabel from './controllable/ControllableLabel.js'; import eventEmitterMixin from './eventEmitterMixin.js'; import MockPoint from './MockPoint.js'; import ControlPoint from './ControlPoint.js'; var merge = H.merge, addEvent = H.addEvent, fireEvent = H.fireEvent, find = H.find, reduce = H.reduce, chartProto = H.Chart.prototype; /* ********************************************************************* * * ANNOTATION * ******************************************************************** */ /** * @typedef { * Annotation.ControllableCircle| * Annotation.ControllableImage| * Annotation.ControllablePath| * Annotation.ControllableRect * } * Annotation.Shape */ /** * @typedef {Annotation.ControllableLabel} Annotation.Label */ /** * An annotation class which serves as a container for items like labels or * shapes. Created items are positioned on the chart either by linking them to * existing points or created mock points * * @class * @name Highcharts.Annotation * * @param {Highcharts.Chart} chart a chart instance * @param {Highcharts.AnnotationsOptions} userOptions the options object */ var Annotation = H.Annotation = function (chart, userOptions) { var labelsAndShapes; /** * The chart that the annotation belongs to. * * @type {Highcharts.Chart} */ this.chart = chart; /** * The array of points which defines the annotation. * * @type {Array<Highcharts.Point>} */ this.points = []; /** * The array of control points. * * @type {Array<Annotation.ControlPoint>} */ this.controlPoints = []; this.coll = 'annotations'; /** * The array of labels which belong to the annotation. * * @type {Array<Annotation.Label>} */ this.labels = []; /** * The array of shapes which belong to the annotation. * * @type {Array<Annotation.Shape>} */ this.shapes = []; /** * The options for the annotations. * * @type {Highcharts.AnnotationsOptions} */ this.options = merge(this.defaultOptions, userOptions); /** * The user options for the annotations. * * @type {Highcharts.AnnotationsOptions} */ this.userOptions = userOptions; // Handle labels and shapes - those are arrays // Merging does not work with arrays (stores reference) labelsAndShapes = this.getLabelsAndShapesOptions( this.options, userOptions ); this.options.labels = labelsAndShapes.labels; this.options.shapes = labelsAndShapes.shapes; /** * The callback that reports to the overlapping-labels module which * labels it should account for. * * @name labelCollector * @memberOf Annotation# * @type {Function} */ /** * The group svg element. * * @name group * @memberOf Annotation# * @type {Highcharts.SVGElement} */ /** * The group svg element of the annotation's shapes. * * @name shapesGroup * @memberOf Annotation# * @type {Highcharts.SVGElement} */ /** * The group svg element of the annotation's labels. * * @name labelsGroup * @memberOf Annotation# * @type {Highcharts.SVGElement} */ this.init(chart, this.options); }; merge( true, Annotation.prototype, controllableMixin, eventEmitterMixin, /** @lends Annotation# */ { /** * List of events for `annotation.options.events` that should not be * added to `annotation.graphic` but to the `annotation`. * * @type {Array<string>} */ nonDOMEvents: ['add', 'afterUpdate', 'drag', 'remove'], /** * A basic type of an annotation. It allows to add custom labels * or shapes. The items can be tied to points, axis coordinates * or chart pixel coordinates. * * @sample highcharts/annotations/basic/ * Basic annotations * @sample highcharts/demo/annotations/ * Advanced annotations * @sample highcharts/css/annotations * Styled mode * @sample highcharts/annotations-advanced/controllable * Controllable items * @sample {highstock} stock/annotations/fibonacci-retracements * Custom annotation, Fibonacci retracement * * @type {Array<*>} * @since 6.0.0 * @requires modules/annotations * @optionparent annotations */ defaultOptions: { /** * Sets an ID for an annotation. Can be user later when removing an * annotation in [Chart#removeAnnotation(id)]( * /class-reference/Highcharts.Chart#removeAnnotation) method. * * @type {string|number} * @apioption annotations.id */ /** * Whether the annotation is visible. * * @sample highcharts/annotations/visible/ * Set annotation visibility */ visible: true, /** * Allow an annotation to be draggable by a user. Possible * values are `"x"`, `"xy"`, `"y"` and `""` (disabled). * * @sample highcharts/annotations/draggable/ * Annotations draggable: 'xy' * * @type {string} * @validvalue ["x", "xy", "y", ""] */ draggable: 'xy', /** * Options for annotation's labels. Each label inherits options * from the labelOptions object. An option from the labelOptions * can be overwritten by config for a specific label. * * @requires modules/annotations */ labelOptions: { /** * The alignment of the annotation's label. If right, * the right side of the label should be touching the point. * * @sample highcharts/annotations/label-position/ * Set labels position * * @type {Highcharts.AlignValue} */ align: 'center', /** * Whether to allow the annotation's labels to overlap. * To make the labels less sensitive for overlapping, * the can be set to 0. * * @sample highcharts/annotations/tooltip-like/ * Hide overlapping labels */ allowOverlap: false, /** * The background color or gradient for the annotation's label. * * @sample highcharts/annotations/label-presentation/ * Set labels graphic options * * @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject} */ backgroundColor: 'rgba(0, 0, 0, 0.75)', /** * The border color for the annotation's label. * * @sample highcharts/annotations/label-presentation/ * Set labels graphic options * * @type {Highcharts.ColorString} */ borderColor: 'black', /** * The border radius in pixels for the annotaiton's label. * * @sample highcharts/annotations/label-presentation/ * Set labels graphic options */ borderRadius: 3, /** * The border width in pixels for the annotation's label * * @sample highcharts/annotations/label-presentation/ * Set labels graphic options */ borderWidth: 1, /** * A class name for styling by CSS. * * @sample highcharts/css/annotations * Styled mode annotations * * @since 6.0.5 */ className: '', /** * Whether to hide the annotation's label * that is outside the plot area. * * @sample highcharts/annotations/label-crop-overflow/ * Crop or justify labels */ crop: false, /** * The label's pixel distance from the point. * * @sample highcharts/annotations/label-position/ * Set labels position * * @type {number} * @apioption annotations.labelOptions.distance */ /** * A * [format](https://www.highcharts.com/docs/chart-concepts/labels-and-string-formatting) * string for the data label. * * @see [plotOptions.series.dataLabels.format](plotOptions.series.dataLabels.format.html) * * @sample highcharts/annotations/label-text/ * Set labels text * * @type {string} * @apioption annotations.labelOptions.format */ /** * Alias for the format option. * * @see [format](annotations.labelOptions.format.html) * * @sample highcharts/annotations/label-text/ * Set labels text * * @type {string} * @apioption annotations.labelOptions.text */ /** * Callback JavaScript function to format the annotation's * label. Note that if a `format` or `text` are defined, the * format or text take precedence and the formatter is ignored. * `This` refers to a point object. * * @sample highcharts/annotations/label-text/ * Set labels text * * @type {Highcharts.FormatterCallbackFunction<Highcharts.Point>} * @default function () { return defined(this.y) ? this.y : 'Annotation label'; } */ formatter: function () { return defined(this.y) ? this.y : 'Annotation label'; }, /** * How to handle the annotation's label that flow outside the * plot area. The justify option aligns the label inside the * plot area. * * @sample highcharts/annotations/label-crop-overflow/ * Crop or justify labels * * @validvalue ["allow", "justify"] */ overflow: 'justify', /** * When either the borderWidth or the backgroundColor is set, * this is the padding within the box. * * @sample highcharts/annotations/label-presentation/ * Set labels graphic options */ padding: 5, /** * The shadow of the box. The shadow can be an object * configuration containing `color`, `offsetX`, `offsetY`, * `opacity` and `width`. * * @sample highcharts/annotations/label-presentation/ * Set labels graphic options * * @type {boolean|Highcharts.ShadowOptionsObject} */ shadow: false, /** * The name of a symbol to use for the border around the label. * Symbols are predefined functions on the Renderer object. * * @sample highcharts/annotations/shapes/ * Available shapes for labels */ shape: 'callout', /** * Styles for the annotation's label. * * @see [plotOptions.series.dataLabels.style](plotOptions.series.dataLabels.style.html) * * @sample highcharts/annotations/label-presentation/ * Set labels graphic options * * @type {Highcharts.CSSObject} */ style: { /** @ignore */ fontSize: '11px', /** @ignore */ fontWeight: 'normal', /** @ignore */ color: 'contrast' }, /** * Whether to [use HTML](https://www.highcharts.com/docs/chart-concepts/labels-and-string-formatting#html) * to render the annotation's label. */ useHTML: false, /** * The vertical alignment of the annotation's label. * * @sample highcharts/annotations/label-position/ * Set labels position * * @type {Highcharts.VerticalAlignValue} */ verticalAlign: 'bottom', /** * The x position offset of the label relative to the point. * Note that if a `distance` is defined, the distance takes * precedence over `x` and `y` options. * * @sample highcharts/annotations/label-position/ * Set labels position */ x: 0, /** * The y position offset of the label relative to the point. * Note that if a `distance` is defined, the distance takes * precedence over `x` and `y` options. * * @sample highcharts/annotations/label-position/ * Set labels position */ y: -16 }, /** * An array of labels for the annotation. For options that apply to * multiple labels, they can be added to the * [labelOptions](annotations.labelOptions.html). * * @type {Array<*>} * @extends annotations.labelOptions * @apioption annotations.labels */ /** * This option defines the point to which the label will be * connected. It can be either the point which exists in the * series - it is referenced by the point's id - or a new point with * defined x, y properties and optionally axes. * * @sample highcharts/annotations/mock-point/ * Attach annotation to a mock point * * @type {string|Highcharts.MockPointOptionsObject} * @requires modules/annotations * @apioption annotations.labels.point */ /** * The x position of the point. Units can be either in axis * or chart pixel coordinates. * * @type {number} * @apioption annotations.labels.point.x */ /** * The y position of the point. Units can be either in axis * or chart pixel coordinates. * * @type {number} * @apioption annotations.labels.point.y */ /** * This number defines which xAxis the point is connected to. It * refers to either the axis id or the index of the axis in the * xAxis array. If the option is not configured or the axis is not * found the point's x coordinate refers to the chart pixels. * * @type {number|string} * @apioption annotations.labels.point.xAxis */ /** * This number defines which yAxis the point is connected to. It * refers to either the axis id or the index of the axis in the * yAxis array. If the option is not configured or the axis is not * found the point's y coordinate refers to the chart pixels. * * @type {number|string} * @apioption annotations.labels.point.yAxis */ /** * An array of shapes for the annotation. For options that apply to * multiple shapes, then can be added to the * [shapeOptions](annotations.shapeOptions.html). * * @type {Array<*>} * @extends annotations.shapeOptions * @apioption annotations.shapes */ /** * This option defines the point to which the shape will be * connected. It can be either the point which exists in the * series - it is referenced by the point's id - or a new point with * defined x, y properties and optionally axes. * * @type {string|Highcharts.MockPointOptionsObject} * @extends annotations.labels.point * @apioption annotations.shapes.point */ /** * An array of points for the shape. This option is available for * shapes which can use multiple points such as path. A point can be * either a point object or a point's id. * * @see [annotations.shapes.point](annotations.shapes.point.html) * * @type {Array<string|Highcharts.MockPointOptionsObject>} * @extends annotations.labels.point * @apioption annotations.shapes.points */ /** * Id of the marker which will be drawn at the final vertex of the * path. Custom markers can be defined in defs property. * * @see [defs.markers](defs.markers.html) * * @sample highcharts/annotations/custom-markers/ * Define a custom marker for annotations * * @type {string} * @apioption annotations.shapes.markerEnd */ /** * Id of the marker which will be drawn at the first vertex of the * path. Custom markers can be defined in defs property. * * @see [defs.markers](defs.markers.html) * * @sample {highcharts} highcharts/annotations/custom-markers/ * Define a custom marker for annotations * * @type {string} * @apioption annotations.shapes.markerStart */ /** * Options for annotation's shapes. Each shape inherits options from * the shapeOptions object. An option from the shapeOptions can be * overwritten by config for a specific shape. * * @requires modules/annotations */ shapeOptions: { /** * The width of the shape. * * @sample highcharts/annotations/shape/ * Basic shape annotation * * @type {number} * @apioption annotations.shapeOptions.width **/ /** * The height of the shape. * * @sample highcharts/annotations/shape/ * Basic shape annotation * * @type {number} * @apioption annotations.shapeOptions.height */ /** * The type of the shape, e.g. circle or rectangle. * * @sample highcharts/annotations/shape/ * Basic shape annotation * * @type {string} * @default 'rect' * @apioption annotations.shapeOptions.type */ /** * The color of the shape's stroke. * * @sample highcharts/annotations/shape/ * Basic shape annotation * * @type {Highcharts.ColorString} */ stroke: 'rgba(0, 0, 0, 0.75)', /** * The pixel stroke width of the shape. * * @sample highcharts/annotations/shape/ * Basic shape annotation */ strokeWidth: 1, /** * The color of the shape's fill. * * @sample highcharts/annotations/shape/ * Basic shape annotation * * @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject} */ fill: 'rgba(0, 0, 0, 0.75)', /** * The radius of the shape. * * @sample highcharts/annotations/shape/ * Basic shape annotation */ r: 0, /** * Defines additional snapping area around an annotation * making this annotation to focus. Defined in pixels. */ snap: 2 }, /** * Options for annotation's control points. Each control point * inherits options from controlPointOptions object. * Options from the controlPointOptions can be overwritten * by options in a specific control point. * * @type {Annotation.ControlPoint.Options} * @requires modules/annotations * @apioption annotations.controlPointOptions */ controlPointOptions: { /** * @function {Annotation.ControlPoint.Positioner} * @apioption annotations.controlPointOptions.positioner */ symbol: 'circle', width: 10, height: 10, style: { stroke: 'black', 'stroke-width': 2, fill: 'white' }, visible: false, events: {} }, /** * Event callback when annotation is added to the chart. * * @type {Highcharts.EventCallbackFunction<Highcharts.Annotation>} * @since 7.1.0 * @apioption annotations.events.add */ /** * Event callback when annotation is updated (e.g. drag and * droppped or resized by control points). * * @type {Highcharts.EventCallbackFunction<Highcharts.Annotation>} * @since 7.1.0 * @apioption annotations.events.afterUpdate */ /** * Event callback when annotation is removed from the chart. * * @type {Highcharts.EventCallbackFunction<Highcharts.Annotation>} * @since 7.1.0 * @apioption annotations.events.remove */ /** * Events available in annotations. * * @requires modules/annotations */ events: {}, /** * The Z index of the annotation. */ zIndex: 6 }, /** * Initialize the annotation. * * @param {Highcharts.Chart} * The chart * @param {Highcharts.AnnotationsOptions} * The user options for the annotation */ init: function () { this.linkPoints(); this.addControlPoints(); this.addShapes(); this.addLabels(); this.addClipPaths(); this.setLabelCollector(); }, getLabelsAndShapesOptions: function (baseOptions, newOptions) { var mergedOptions = {}; ['labels', 'shapes'].forEach(function (name) { if (baseOptions[name]) { mergedOptions[name] = splat(newOptions[name]).map( function (basicOptions, i) { return merge(baseOptions[name][i], basicOptions); } ); } }); return mergedOptions; }, addShapes: function () { (this.options.shapes || []).forEach(function (shapeOptions, i) { var shape = this.initShape(shapeOptions, i); merge(true, this.options.shapes[i], shape.options); }, this); }, addLabels: function () { (this.options.labels || []).forEach(function (labelsOptions, i) { var labels = this.initLabel(labelsOptions, i); merge(true, this.options.labels[i], labels.options); }, this); }, addClipPaths: function () { this.setClipAxes(); if (this.clipXAxis && this.clipYAxis) { this.clipRect = this.chart.renderer.clipRect( this.getClipBox() ); } }, setClipAxes: function () { var xAxes = this.chart.xAxis, yAxes = this.chart.yAxis, linkedAxes = reduce( (this.options.labels || []) .concat(this.options.shapes || []), function (axes, labelOrShape) { return [ xAxes[ labelOrShape && labelOrShape.point && labelOrShape.point.xAxis ] || axes[0], yAxes[ labelOrShape && labelOrShape.point && labelOrShape.point.yAxis ] || axes[1] ]; }, [] ); this.clipXAxis = linkedAxes[0]; this.clipYAxis = linkedAxes[1]; }, getClipBox: function () { return { x: this.clipXAxis.left, y: this.clipYAxis.top, width: this.clipXAxis.width, height: this.clipYAxis.height }; }, setLabelCollector: function () { var annotation = this; annotation.labelCollector = function () { return annotation.labels.reduce( function (labels, label) { if (!label.options.allowOverlap) { labels.push(label.graphic); } return labels; }, [] ); }; annotation.chart.labelCollectors.push( annotation.labelCollector ); }, /** * Set an annotation options. * * @param {Highcharts.AnnotationsOptions} - user options for an annotation */ setOptions: function (userOptions) { this.options = merge(this.defaultOptions, userOptions); }, redraw: function (animation) { this.linkPoints(); if (!this.graphic) { this.render(); } if (this.clipRect) { this.clipRect.animate(this.getClipBox()); } this.redrawItems(this.shapes, animation); this.redrawItems(this.labels, animation); controllableMixin.redraw.call(this, animation); }, /** * @param {Array<(Annotation.Label|Annotation.Shape)>} items * @param {boolean} [animation] */ redrawItems: function (items, animation) { var i = items.length; // needs a backward loop // labels/shapes array might be modified // due to destruction of the item while (i--) { this.redrawItem(items[i], animation); } }, render: function () { var renderer = this.chart.renderer; this.graphic = renderer .g('annotation') .attr({ zIndex: this.options.zIndex, visibility: this.options.visible ? 'visible' : 'hidden' }) .add(); this.shapesGroup = renderer .g('annotation-shapes') .add(this.graphic) .clip(this.chart.plotBoxClip); this.labelsGroup = renderer .g('annotation-labels') .attr({ // hideOverlappingLabels requires translation translateX: 0, translateY: 0 }) .add(this.graphic); if (this.clipRect) { this.graphic.clip(this.clipRect); } this.addEvents(); controllableMixin.render.call(this); }, /** * Set the annotation's visibility. * * @param {Boolean} [visible] - Whether to show or hide an annotation. * If the param is omitted, the annotation's visibility is toggled. */ setVisibility: function (visibility) { var options = this.options, visible = pick(visibility, !options.visible); this.graphic.attr( 'visibility', visible ? 'visible' : 'hidden' ); if (!visible) { this.setControlPointsVisibility(false); } options.visible = visible; }, setControlPointsVisibility: function (visible) { var setItemControlPointsVisibility = function (item) { item.setControlPointsVisibility(visible); }; controllableMixin.setControlPointsVisibility.call( this, visible ); this.shapes.forEach(setItemControlPointsVisibility); this.labels.forEach(setItemControlPointsVisibility); }, /** * Destroy the annotation. This function does not touch the chart * that the annotation belongs to (all annotations are kept in * the chart.annotations array) - it is recommended to use * {@link Highcharts.Chart#removeAnnotation} instead. */ destroy: function () { var chart = this.chart, destroyItem = function (item) { item.destroy(); }; this.labels.forEach(destroyItem); this.shapes.forEach(destroyItem); this.clipXAxis = null; this.clipYAxis = null; erase(chart.labelCollectors, this.labelCollector); eventEmitterMixin.destroy.call(this); controllableMixin.destroy.call(this); destroyObjectProperties(this, chart); }, /** * See {@link Highcharts.Chart#removeAnnotation}. */ remove: function () { // Let chart.update() remove annoations on demand return this.chart.removeAnnotation(this); }, update: function (userOptions) { var chart = this.chart, labelsAndShapes = this.getLabelsAndShapesOptions( this.userOptions, userOptions ), userOptionsIndex = chart.annotations.indexOf(this), options = H.merge(true, this.userOptions, userOptions); options.labels = labelsAndShapes.labels; options.shapes = labelsAndShapes.shapes; this.destroy(); this.constructor(chart, options); // Update options in chart options, used in exporting (#9767): chart.options.annotations[userOptionsIndex] = options; this.isUpdating = true; this.redraw(); this.isUpdating = false; fireEvent(this, 'afterUpdate'); }, /* ************************************************************* * ITEM SECTION * Contains methods for handling a single item in an annotation **************************************************************** */ /** * Initialisation of a single shape * * @param {Object} shapeOptions - a confg object for a single shape */ initShape: function (shapeOptions, index) { var options = merge( this.options.shapeOptions, { controlPointOptions: this.options.controlPointOptions }, shapeOptions ), shape = new Annotation.shapesMap[options.type]( this, options, index ); shape.itemType = 'shape'; this.shapes.push(shape); return shape; }, /** * Initialisation of a single label * * @param {Object} labelOptions **/ initLabel: function (labelOptions, index) { var options = merge( this.options.labelOptions, { controlPointOptions: this.options.controlPointOptions }, labelOptions ), label = new ControllableLabel( this, options, index ); label.itemType = 'label'; this.labels.push(label); return label; }, /** * Redraw a single item. * * @param {Annotation.Label|Annotation.Shape} item * @param {boolean} [animation] */ redrawItem: function (item, animation) { item.linkPoints(); if (!item.shouldBeDrawn()) { this.destroyItem(item); } else { if (!item.graphic) { this.renderItem(item); } item.redraw( pick(animation, true) && item.graphic.placed ); if (item.points.length) { this.adjustVisibility(item); } } }, /** * Hide or show annotaiton attached to points. * * @param {Annotation.Label|Annotation.Shape} item */ adjustVisibility: function (item) { // #9481 var hasVisiblePoints = false, label = item.graphic; item.points.forEach(function (point) { if ( point.series.visible !== false && point.visible !== false ) { hasVisiblePoints = true; } }); if (!hasVisiblePoints) { label.hide(); } else if (label.visibility === 'hidden') { label.show(); } }, /** * Destroy a single item. * * @param {Annotation.Label|Annotation.Shape} item */ destroyItem: function (item) { // erase from shapes or labels array erase(this[item.itemType + 's'], item); item.destroy(); }, /** * @private */ renderItem: function (item) { item.render( item.itemType === 'label' ? this.labelsGroup : this.shapesGroup ); } } ); /** * An object uses for mapping between a shape type and a constructor. * To add a new shape type extend this object with type name as a key * and a constructor as its value. */ Annotation.shapesMap = { 'rect': ControllableRect, 'circle': ControllableCircle, 'path': ControllablePath, 'image': ControllableImage }; Annotation.types = {}; Annotation.MockPoint = MockPoint; Annotation.ControlPoint = ControlPoint; H.extendAnnotation = function ( Constructor, BaseConstructor, prototype, defaultOptions ) { BaseConstructor = BaseConstructor || Annotation; merge( true, Constructor.prototype, BaseConstructor.prototype, prototype ); Constructor.prototype.defaultOptions = merge( Constructor.prototype.defaultOptions, defaultOptions || {} ); }; /* ********************************************************************* * * EXTENDING CHART PROTOTYPE * ******************************************************************** */ extend(chartProto, /** @lends Highcharts.Chart# */ { initAnnotation: function (userOptions) { var Constructor = Annotation.types[userOptions.type] || Annotation, annotation = new Constructor(this, userOptions); this.annotations.push(annotation); return annotation; }, /** * Add an annotation to the chart after render time. * * @param {Highcharts.AnnotationsOptions} options * The annotation options for the new, detailed annotation. * @param {boolean} [redraw] * * @return {Highcharts.Annotation} - The newly generated annotation. */ addAnnotation: function (userOptions, redraw) { var annotation = this.initAnnotation(userOptions); this.options.annotations.push(annotation.options); if (pick(redraw, true)) { annotation.redraw(); } return annotation; }, /** * Remove an annotation from the chart. * * @param {String|Number|Annotation} idOrAnnotation - The annotation's id or * direct annotation object. */ removeAnnotation: function (idOrAnnotation) { var annotations = this.annotations, annotation = idOrAnnotation.coll === 'annotations' ? idOrAnnotation : find( annotations, function (annotation) { return annotation.options.id === idOrAnnotation; } ); if (annotation) { fireEvent(annotation, 'remove'); erase(this.options.annotations, annotation.options); erase(annotations, annotation); annotation.destroy(); } }, drawAnnotations: function () { this.plotBoxClip.attr(this.plotBox); this.annotations.forEach(function (annotation) { annotation.redraw(); }); } }); // Let chart.update() update annotations chartProto.collectionsWithUpdate.push('annotations'); // Let chart.update() create annoations on demand chartProto.collectionsWithInit.annotations = [chartProto.addAnnotation]; chartProto.callbacks.push(function (chart) { chart.annotations = []; if (!chart.options.annotations) { chart.options.annotations = []; } chart.plotBoxClip = this.renderer.clipRect(this.plotBox); chart.controlPointsGroup = chart.renderer .g('control-points') .attr({ zIndex: 99 }) .clip(chart.plotBoxClip) .add(); chart.options.annotations.forEach(function (annotationOptions, i) { var annotation = chart.initAnnotation(annotationOptions); chart.options.annotations[i] = annotation.options; }); chart.drawAnnotations(); addEvent(chart, 'redraw', chart.drawAnnotations); addEvent(chart, 'destroy', function () { chart.plotBoxClip.destroy(); chart.controlPointsGroup.destroy(); }); }); wrap( H.Pointer.prototype, 'onContainerMouseDown', function (proceed) { if (!this.chart.hasDraggedAnnotation) { proceed.apply(this, Array.prototype.slice.call(arguments, 1)); } } );
cdnjs/cdnjs
ajax/libs/highcharts/8.0.0/es-modules/annotations/annotations.src.js
JavaScript
mit
42,338
#!/usr/bin/python3 """ Simple wrapper to get diff of two schedules It's able to show different attributes (by 'attrs' kwarg) and indicate missing phases Follows 'diff' exit codes: 0 - same 1 - different 2 - other trouble Test as "python -m schedules_tools.batches.diff" """ import argparse from datetime import datetime import json import logging from schedules_tools import jsondate, discovery from schedules_tools.converter import ScheduleConverter from schedules_tools.models import Task, Schedule import sys log = logging.getLogger(__name__) REPORT_NO_CHANGE = '' REPORT_ADDED = '_added_' REPORT_REMOVED = '_removed_' REPORT_CHANGED = '_changed_' REPORT_PREFIX_MAP = { REPORT_ADDED: '[+]', REPORT_REMOVED: '[-]', REPORT_CHANGED: '[M]', REPORT_NO_CHANGE: 3 * ' ', } NAME_SIM_THRESHOLD = 0.8 TASK_SCORE_THRESHOLD = 0.45 NAME_SIM_WEIGHT = 0.5 TASK_POS_WEIGHT = 0.5 def strings_similarity(str1, str2, winkler=True, scaling=0.1): """ Find the Jaro-Winkler distance of 2 strings. https://en.wikipedia.org/wiki/Jaro-Winkler_distance :param winkler: add winkler adjustment to the Jaro distance :param scaling: constant scaling factor for how much the score is adjusted upwards for having common prefixes. Should not exceed 0.25 """ if str1 == str2: return 1.0 def num_of_char_matches(s1, len1, s2, len2): count = 0 transpositions = 0 # number of matching chars w/ different sequence order limit = int(max(len1, len2) / 2 - 1) for i in range(len1): start = i - limit if start < 0: start = 0 end = i + limit + 1 if end > len2: end = len2 index = s2.find(s1[i], start, end) if index > -1: # found common char count += 1 if index != i: transpositions += 1 return count, transpositions len1 = len(str1) len2 = len(str2) num_of_matches, transpositions = num_of_char_matches(str1, len1, str2, len2) if num_of_matches == 0: return 0.0 m = float(num_of_matches) t = transpositions / 2.0 dj = (m / float(len1) + m / float(len2) + (m - t) / m) / 3.0 if winkler: length = 0 # length of common prefix at the start of the string (max = 4) max_length = min( len1, len2, 4 ) while length < max_length and str1[length] == str2[length]: length += 1 return dj + (length * scaling * (1.0 - dj)) return dj class ScheduleDiff(object): result = [] hierarchy_attr = 'tasks' subtree_hash_attr_name = 'subtree_hash' """ Default list of attributes used to compare 2 tasks. """ default_tasks_match_attrs = ['name', 'dStart', 'dFinish'] def __init__(self, schedule_a, schedule_b, trim_time=False, extra_compare_attributes=None): self.schedule_a = schedule_a self.schedule_b = schedule_b self.trim_time = trim_time self.attributes_to_compare = self.default_tasks_match_attrs if extra_compare_attributes: # avoid using += to not modify class-level list self.attributes_to_compare = self.attributes_to_compare + list(extra_compare_attributes) self.result = self._diff() def __str__(self): return self.result_to_str() def _get_subtree(self, item): return getattr(item, self.hierarchy_attr) def result_to_str(self, items=None, level=0): """ Textual representation of the diff. """ res = '' if items is None: items = self.result schedule = Schedule() for item in items: subtree = item['subtree'] state = item['item_state'] if state in [REPORT_CHANGED, REPORT_ADDED]: task = item['right'] elif state is REPORT_REMOVED: task = item['left'] else: task = item['both'] task_obj = Task.load_from_dict(task, schedule) res += '{} {}{}\n'.format(REPORT_PREFIX_MAP[state], level * ' ', str(task_obj)) if subtree: res += self.result_to_str(subtree, level + 2) return res def _create_report(self, item_state, left=None, right=None, both=None, subtree=[], changed_attrs=[]): """ Returns a dictionary representing a possible change. { left: Task or None, right: Task or None, both: used instead of left and right, when the task are equal, subtree: List of reports from the child Tasks, changed_attr: List of changed attributes, item_state: Type of change } """ if both: report = { 'both': both.dump_as_dict(recursive=False), 'subtree': subtree, 'changed_attrs': changed_attrs, 'item_state': item_state } else: # No need to keep the whole structure, # child tasks will be placed in report['tasks'] if left is not None: left = left.dump_as_dict(recursive=False) if right is not None: right = right.dump_as_dict(recursive=False) report = { 'left': left, 'right': right, 'subtree': subtree, 'changed_attrs': changed_attrs, 'item_state': item_state, } return report def _set_subtree_items_state(self, items, state): """ Set the given state recursively on the subtree items """ def create_report(item): kwargs = { 'subtree': self._set_subtree_items_state(self._get_subtree(item), state) } if state == REPORT_NO_CHANGE: kwargs['both'] = item elif state == REPORT_ADDED: kwargs['right'] = item elif state == REPORT_REMOVED: kwargs['left'] = item return self._create_report(state, **kwargs) return [create_report(item) for item in items] def get_changed_attrs(self, task_a, task_b): """ Compare 2 tasks Uses attributes defined in `self.attributes_to_compare` and subtree hash and returns a list of atts that don't match. """ changed_attributes = [attr for attr in self.attributes_to_compare if not self._compare_tasks_attributes(task_a, task_b, attr)] if task_a.get_subtree_hash(self.attributes_to_compare) \ != task_b.get_subtree_hash(self.attributes_to_compare): changed_attributes.append(self.subtree_hash_attr_name) return changed_attributes def _compare_tasks_attributes(self, task_a, task_b, attr_name): """ Compares tasks attributes. Trims time from datetime objects if self.trim_time is set. """ attribute_a = getattr(task_a, attr_name) attribute_b = getattr(task_b, attr_name) if self.trim_time: if isinstance(attribute_a, datetime): attribute_a = attribute_a.date() if isinstance(attribute_b, datetime): attribute_b = attribute_b.date() return attribute_a == attribute_b def find_best_match(self, t1, possible_matches, start_at_index=0): """ Finds the best match for the given task in the list of possible matches. Returns the index of the best match and a dict with a state suggestion and list of changed attrs. """ match_index = None best_match = { 'state': REPORT_REMOVED, 'changes': [], 'name_score': 0, 'score': TASK_SCORE_THRESHOLD } if start_at_index > 0: possible_matches = possible_matches[start_at_index:] for i, t2 in enumerate(possible_matches, start_at_index): res = self.eval_tasks(t1, t2, i, name_threshold=best_match['name_score']) if (res['state'] is REPORT_CHANGED and res['score'] > best_match['score']): match_index = i best_match = res if res['state'] is REPORT_NO_CHANGE: match_index = i best_match = res break return match_index, best_match def _task_position_score(self, index): return 1.0 / (2 * (index + 1)) def _task_score(self, name_score, position_score): weight_sum = NAME_SIM_WEIGHT + TASK_POS_WEIGHT name_score *= NAME_SIM_WEIGHT position_score *= TASK_POS_WEIGHT return (name_score + position_score) / weight_sum def eval_tasks(self, t1, t2, t2_index, name_threshold=NAME_SIM_THRESHOLD): name_score = 0.0 position_score = 0.0 changed_attrs = self.get_changed_attrs(t1, t2) # different names if 'name' in changed_attrs: t1_subtree = t1.get_subtree_hash(self.attributes_to_compare) t2_subtree = t2.get_subtree_hash(self.attributes_to_compare) if t1_subtree and t2_subtree: if t1_subtree == t2_subtree: state = REPORT_CHANGED position_score = 1.0 else: name_score = strings_similarity(t1.name, t2.name) if (name_score > name_threshold and len(changed_attrs) < len(self.attributes_to_compare)): state = REPORT_CHANGED position_score = self._task_position_score(t2_index) else: state = REPORT_REMOVED # no subtrees else: name_score = strings_similarity(t1.name, t2.name, winkler=False) if name_score > name_threshold: state = REPORT_CHANGED position_score = self._task_position_score(t2_index) else: state = REPORT_REMOVED # names are equal else: name_score = 1.0 if (not changed_attrs or (len(changed_attrs) == 1 and self.subtree_hash_attr_name in changed_attrs)): state = REPORT_NO_CHANGE else: state = REPORT_CHANGED position_score = 1.0 return { 'state': state, 'changes': changed_attrs, 'name_score': name_score, 'position_score': position_score, 'score': self._task_score(name_score, position_score) } def _diff(self, tasks_a=None, tasks_b=None): if tasks_a is None: tasks_a = self.schedule_a.tasks if tasks_b is None: tasks_b = self.schedule_b.tasks res = [] last_b_index = 0 # shortcut to create a report for an added task def report_task_added(index, recursive=True): task = tasks_b[index] subtree = self._get_subtree(task) if recursive: subtree = self._set_subtree_items_state(subtree, REPORT_ADDED) return self._create_report(REPORT_ADDED, right=task, subtree=subtree) for task in tasks_a: match_index, match = self.find_best_match(task, tasks_b, start_at_index=last_b_index) report = {} if match_index is None: subtree = self._set_subtree_items_state(self._get_subtree(task), REPORT_REMOVED) report = self._create_report(REPORT_REMOVED, left=task, subtree=subtree) else: # ALL elements between last_b_index and match_index => ADDED res.extend([report_task_added(k) for k in range(last_b_index, match_index)]) # exact match => NO CHANGE if not match['changes']: subtree = self._set_subtree_items_state(self._get_subtree(task), match['state']) report_kwargs = {'both': task, 'subtree': subtree} # structural change => CHANGED / NO CHANGE elif self.subtree_hash_attr_name in match['changes']: # process child tasks subtree = self._diff( self._get_subtree(task), self._get_subtree(tasks_b[match_index]) ) if len(match['changes']) > 1: report_kwargs = { 'left': task, 'right': tasks_b[match_index], 'subtree': subtree } else: report_kwargs = { 'both': task, 'subtree': subtree } # no structural changes => CHANGED else: subtree = self._set_subtree_items_state( self._get_subtree(tasks_b[match_index]), REPORT_NO_CHANGE) report_kwargs = { 'left': task, 'right': tasks_b[match_index], 'subtree': subtree } report = self._create_report(match['state'], changed_attrs=match['changes'], **report_kwargs) last_b_index = match_index + 1 res.append(report) # remaining tasks => ADDED res.extend([report_task_added(k) for k in range(last_b_index, len(tasks_b))]) return res def dump_json(self, **kwargs): def _encoder(obj): if isinstance(obj, Task): return obj.dump_as_dict() return jsondate._datetime_encoder(obj) kwargs['default'] = _encoder return json.dumps(self.result, **kwargs) def setup_logging(level): log_format = '%(name)-10s %(levelname)7s: %(message)s' sh = logging.StreamHandler(sys.stdout) sh.setLevel(level) formatter = logging.Formatter(log_format) sh.setFormatter(formatter) # setup root logger inst = logging.getLogger('') inst.setLevel(level) inst.addHandler(sh) def main(): setup_logging(logging.INFO) parser = argparse.ArgumentParser( description='Tool to show differences between two schedules.') parser.add_argument('--simple-diff', help='Simple comparison between two schedules.', action='store_true', default=False) parser.add_argument( '--handlers-path', help='Add python-dot-notation path to discover handlers (needs to ' 'be python module), can be called several times ' '(conflicting names will be overriden - the last ' 'implementation will be used)', action='append', default=[]) parser.add_argument('--whole-days', help='Compare just date part of timestamp (will ' 'ignore differences in time)', action='store_true', default=False) parser.add_argument('left') parser.add_argument('right') args = parser.parse_args() for path in args.handlers_path: discovery.search_paths.append(path) left = ScheduleConverter() left.import_schedule(args.left) right = ScheduleConverter() right.import_schedule(args.right) if args.simple_diff: diff_res = left.schedule.diff(right.schedule, whole_days=args.whole_days) else: diff_res = ScheduleDiff(left.schedule, right.schedule) if diff_res: print(diff_res) sys.exit(1) if __name__ == '__main__': main()
RedHat-Eng-PGM/schedules-tools
schedules_tools/diff.py
Python
mit
16,312
this.primereact = this.primereact || {}; this.primereact.multiselect = (function (exports, React, core, inputtext, virtualscroller, PrimeReact) { 'use strict'; function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } var React__default = /*#__PURE__*/_interopDefaultLegacy(React); var PrimeReact__default = /*#__PURE__*/_interopDefaultLegacy(PrimeReact); function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _arrayLikeToArray$1(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray$1(arr); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _unsupportedIterableToArray$1(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$1(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$1(o, minLen); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray$1(arr) || _nonIterableSpread(); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function ownKeys$2(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread$2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$2(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$2(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createSuper$4(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$4(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$4() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var Checkbox = /*#__PURE__*/function (_Component) { _inherits(Checkbox, _Component); var _super = _createSuper$4(Checkbox); function Checkbox(props) { var _this; _classCallCheck(this, Checkbox); _this = _super.call(this, props); _this.state = { focused: false }; _this.onClick = _this.onClick.bind(_assertThisInitialized(_this)); _this.onFocus = _this.onFocus.bind(_assertThisInitialized(_this)); _this.onBlur = _this.onBlur.bind(_assertThisInitialized(_this)); _this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this)); _this.inputRef = /*#__PURE__*/React.createRef(_this.props.inputRef); return _this; } _createClass(Checkbox, [{ key: "onClick", value: function onClick(e) { if (!this.props.disabled && !this.props.readOnly && this.props.onChange) { this.props.onChange({ originalEvent: e, value: this.props.value, checked: !this.props.checked, stopPropagation: function stopPropagation() {}, preventDefault: function preventDefault() {}, target: { type: 'checkbox', name: this.props.name, id: this.props.id, value: this.props.value, checked: !this.props.checked } }); this.inputRef.current.checked = !this.props.checked; this.inputRef.current.focus(); e.preventDefault(); } } }, { key: "updateInputRef", value: function updateInputRef() { var ref = this.props.inputRef; if (ref) { if (typeof ref === 'function') { ref(this.inputRef.current); } else { ref.current = this.inputRef.current; } } } }, { key: "componentDidMount", value: function componentDidMount() { this.updateInputRef(); if (this.props.tooltip) { this.renderTooltip(); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { if (this.tooltip) { this.tooltip.destroy(); this.tooltip = null; } } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { this.inputRef.current.checked = this.props.checked; if (prevProps.tooltip !== this.props.tooltip || prevProps.tooltipOptions !== this.props.tooltipOptions) { if (this.tooltip) this.tooltip.update(_objectSpread$2({ content: this.props.tooltip }, this.props.tooltipOptions || {}));else this.renderTooltip(); } } }, { key: "onFocus", value: function onFocus() { this.setState({ focused: true }); } }, { key: "onBlur", value: function onBlur() { this.setState({ focused: false }); } }, { key: "onKeyDown", value: function onKeyDown(event) { if (event.key === 'Enter') { this.onClick(event); event.preventDefault(); } } }, { key: "renderTooltip", value: function renderTooltip() { this.tooltip = core.tip({ target: this.element, content: this.props.tooltip, options: this.props.tooltipOptions }); } }, { key: "render", value: function render() { var _this2 = this; var containerClass = core.classNames('p-checkbox p-component', { 'p-checkbox-checked': this.props.checked, 'p-checkbox-disabled': this.props.disabled, 'p-checkbox-focused': this.state.focused }, this.props.className); var boxClass = core.classNames('p-checkbox-box', { 'p-highlight': this.props.checked, 'p-disabled': this.props.disabled, 'p-focus': this.state.focused }); var iconClass = core.classNames('p-checkbox-icon p-c', _defineProperty({}, this.props.icon, this.props.checked)); return /*#__PURE__*/React__default['default'].createElement("div", { ref: function ref(el) { return _this2.element = el; }, id: this.props.id, className: containerClass, style: this.props.style, onClick: this.onClick, onContextMenu: this.props.onContextMenu, onMouseDown: this.props.onMouseDown }, /*#__PURE__*/React__default['default'].createElement("div", { className: "p-hidden-accessible" }, /*#__PURE__*/React__default['default'].createElement("input", { ref: this.inputRef, type: "checkbox", "aria-labelledby": this.props.ariaLabelledBy, id: this.props.inputId, name: this.props.name, tabIndex: this.props.tabIndex, defaultChecked: this.props.checked, onKeyDown: this.onKeyDown, onFocus: this.onFocus, onBlur: this.onBlur, disabled: this.props.disabled, readOnly: this.props.readOnly, required: this.props.required })), /*#__PURE__*/React__default['default'].createElement("div", { className: boxClass, ref: function ref(el) { return _this2.box = el; }, role: "checkbox", "aria-checked": this.props.checked }, /*#__PURE__*/React__default['default'].createElement("span", { className: iconClass }))); } }]); return Checkbox; }(React.Component); _defineProperty(Checkbox, "defaultProps", { id: null, inputRef: null, inputId: null, value: null, name: null, checked: false, style: null, className: null, disabled: false, required: false, readOnly: false, tabIndex: null, icon: 'pi pi-check', tooltip: null, tooltipOptions: null, ariaLabelledBy: null, onChange: null, onMouseDown: null, onContextMenu: null }); function _createSuper$3(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$3(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$3() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var MultiSelectHeader = /*#__PURE__*/function (_Component) { _inherits(MultiSelectHeader, _Component); var _super = _createSuper$3(MultiSelectHeader); function MultiSelectHeader(props) { var _this; _classCallCheck(this, MultiSelectHeader); _this = _super.call(this, props); _this.onFilter = _this.onFilter.bind(_assertThisInitialized(_this)); _this.onSelectAll = _this.onSelectAll.bind(_assertThisInitialized(_this)); return _this; } _createClass(MultiSelectHeader, [{ key: "onFilter", value: function onFilter(event) { if (this.props.onFilter) { this.props.onFilter({ originalEvent: event, query: event.target.value }); } } }, { key: "onSelectAll", value: function onSelectAll(event) { if (this.props.onSelectAll) { this.props.onSelectAll({ originalEvent: event, checked: this.props.selectAll }); } } }, { key: "renderFilterElement", value: function renderFilterElement() { if (this.props.filter) { return /*#__PURE__*/React__default['default'].createElement("div", { className: "p-multiselect-filter-container" }, /*#__PURE__*/React__default['default'].createElement(inputtext.InputText, { type: "text", role: "textbox", value: this.props.filterValue, onChange: this.onFilter, className: "p-multiselect-filter", placeholder: this.props.filterPlaceholder }), /*#__PURE__*/React__default['default'].createElement("span", { className: "p-multiselect-filter-icon pi pi-search" })); } return null; } }, { key: "render", value: function render() { var filterElement = this.renderFilterElement(); var checkboxElement = this.props.showSelectAll && /*#__PURE__*/React__default['default'].createElement(Checkbox, { checked: this.props.selectAll, onChange: this.onSelectAll, role: "checkbox", "aria-checked": this.props.selectAll }); var closeElement = /*#__PURE__*/React__default['default'].createElement("button", { type: "button", className: "p-multiselect-close p-link", onClick: this.props.onClose }, /*#__PURE__*/React__default['default'].createElement("span", { className: "p-multiselect-close-icon pi pi-times" }), /*#__PURE__*/React__default['default'].createElement(core.Ripple, null)); var element = /*#__PURE__*/React__default['default'].createElement("div", { className: "p-multiselect-header" }, checkboxElement, filterElement, closeElement); if (this.props.template) { var defaultOptions = { className: 'p-multiselect-header', checkboxElement: checkboxElement, checked: this.props.selectAll, onChange: this.onSelectAll, filterElement: filterElement, closeElement: closeElement, closeElementClassName: 'p-multiselect-close p-link', closeIconClassName: 'p-multiselect-close-icon pi pi-times', onCloseClick: this.props.onClose, element: element, props: this.props }; return core.ObjectUtils.getJSXElement(this.props.template, defaultOptions); } return element; } }]); return MultiSelectHeader; }(React.Component); function _createSuper$2(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$2(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$2() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var MultiSelectItem = /*#__PURE__*/function (_Component) { _inherits(MultiSelectItem, _Component); var _super = _createSuper$2(MultiSelectItem); function MultiSelectItem(props) { var _this; _classCallCheck(this, MultiSelectItem); _this = _super.call(this, props); _this.onClick = _this.onClick.bind(_assertThisInitialized(_this)); _this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this)); return _this; } _createClass(MultiSelectItem, [{ key: "onClick", value: function onClick(event) { if (this.props.onClick) { this.props.onClick({ originalEvent: event, option: this.props.option }); } event.preventDefault(); } }, { key: "onKeyDown", value: function onKeyDown(event) { if (this.props.onKeyDown) { this.props.onKeyDown({ originalEvent: event, option: this.props.option }); } } }, { key: "render", value: function render() { var className = core.classNames('p-multiselect-item', { 'p-highlight': this.props.selected, 'p-disabled': this.props.disabled }, this.props.option.className); var checkboxClassName = core.classNames('p-checkbox-box', { 'p-highlight': this.props.selected }); var checkboxIcon = core.classNames('p-checkbox-icon p-c', { 'pi pi-check': this.props.selected }); var content = this.props.template ? core.ObjectUtils.getJSXElement(this.props.template, this.props.option) : this.props.label; var tabIndex = this.props.disabled ? null : this.props.tabIndex || 0; return /*#__PURE__*/React__default['default'].createElement("li", { className: className, onClick: this.onClick, tabIndex: tabIndex, onKeyDown: this.onKeyDown, role: "option", "aria-selected": this.props.selected }, /*#__PURE__*/React__default['default'].createElement("div", { className: "p-checkbox p-component" }, /*#__PURE__*/React__default['default'].createElement("div", { className: checkboxClassName }, /*#__PURE__*/React__default['default'].createElement("span", { className: checkboxIcon }))), /*#__PURE__*/React__default['default'].createElement("span", null, content), /*#__PURE__*/React__default['default'].createElement(core.Ripple, null)); } }]); return MultiSelectItem; }(React.Component); _defineProperty(MultiSelectItem, "defaultProps", { option: null, label: null, selected: false, disabled: false, tabIndex: null, template: null, onClick: null, onKeyDown: null }); function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var MultiSelectPanelComponent = /*#__PURE__*/function (_Component) { _inherits(MultiSelectPanelComponent, _Component); var _super = _createSuper$1(MultiSelectPanelComponent); function MultiSelectPanelComponent(props) { var _this; _classCallCheck(this, MultiSelectPanelComponent); _this = _super.call(this, props); _this.onEnter = _this.onEnter.bind(_assertThisInitialized(_this)); _this.onFilterInputChange = _this.onFilterInputChange.bind(_assertThisInitialized(_this)); return _this; } _createClass(MultiSelectPanelComponent, [{ key: "onEnter", value: function onEnter() { var _this2 = this; this.props.onEnter(function () { if (_this2.virtualScrollerRef) { var selectedIndex = _this2.props.getSelectedOptionIndex(); if (selectedIndex !== -1) { _this2.virtualScrollerRef.scrollToIndex(selectedIndex); } } }); } }, { key: "onFilterInputChange", value: function onFilterInputChange(event) { if (this.virtualScrollerRef) { this.virtualScrollerRef.scrollToIndex(0); } this.props.onFilterInputChange && this.props.onFilterInputChange(event); } }, { key: "isEmptyFilter", value: function isEmptyFilter() { return !(this.props.visibleOptions && this.props.visibleOptions.length) && this.props.hasFilter(); } }, { key: "renderHeader", value: function renderHeader() { return /*#__PURE__*/React__default['default'].createElement(MultiSelectHeader, { filter: this.props.filter, filterValue: this.props.filterValue, onFilter: this.onFilterInputChange, filterPlaceholder: this.props.filterPlaceholder, onClose: this.props.onCloseClick, showSelectAll: this.props.showSelectAll, selectAll: this.props.isAllSelected(), onSelectAll: this.props.onSelectAll, template: this.props.panelHeaderTemplate }); } }, { key: "renderFooter", value: function renderFooter() { if (this.props.panelFooterTemplate) { var content = core.ObjectUtils.getJSXElement(this.props.panelFooterTemplate, this.props, this.props.onOverlayHide); return /*#__PURE__*/React__default['default'].createElement("div", { className: "p-multiselect-footer" }, content); } return null; } }, { key: "renderGroupChildren", value: function renderGroupChildren(optionGroup) { var _this3 = this; var groupChildren = this.props.getOptionGroupChildren(optionGroup); return groupChildren.map(function (option, j) { var optionLabel = _this3.props.getOptionLabel(option); var optionKey = j + '_' + _this3.props.getOptionRenderKey(option); var disabled = _this3.props.isOptionDisabled(option); var tabIndex = disabled ? null : _this3.props.tabIndex || 0; return /*#__PURE__*/React__default['default'].createElement(MultiSelectItem, { key: optionKey, label: optionLabel, option: option, template: _this3.props.itemTemplate, selected: _this3.props.isSelected(option), onClick: _this3.props.onOptionSelect, onKeyDown: _this3.props.onOptionKeyDown, tabIndex: tabIndex, disabled: disabled }); }); } }, { key: "renderEmptyFilter", value: function renderEmptyFilter() { var emptyFilterMessage = core.ObjectUtils.getJSXElement(this.props.emptyFilterMessage, this.props); return /*#__PURE__*/React__default['default'].createElement("li", { className: "p-multiselect-empty-message" }, emptyFilterMessage); } }, { key: "renderItem", value: function renderItem(option, index) { if (this.props.optionGroupLabel) { var groupContent = this.props.optionGroupTemplate ? core.ObjectUtils.getJSXElement(this.props.optionGroupTemplate, option, index) : this.props.getOptionGroupLabel(option); var groupChildrenContent = this.renderGroupChildren(option); var key = index + '_' + this.props.getOptionGroupRenderKey(option); return /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, { key: key }, /*#__PURE__*/React__default['default'].createElement("li", { className: "p-multiselect-item-group" }, groupContent), groupChildrenContent); } else { var optionLabel = this.props.getOptionLabel(option); var optionKey = index + '_' + this.props.getOptionRenderKey(option); var disabled = this.props.isOptionDisabled(option); var tabIndex = disabled ? null : this.props.tabIndex || 0; return /*#__PURE__*/React__default['default'].createElement(MultiSelectItem, { key: optionKey, label: optionLabel, option: option, template: this.props.itemTemplate, selected: this.props.isSelected(option), onClick: this.props.onOptionSelect, onKeyDown: this.props.onOptionKeyDown, tabIndex: tabIndex, disabled: disabled }); } } }, { key: "renderItems", value: function renderItems() { var _this4 = this; if (this.props.visibleOptions && this.props.visibleOptions.length) { return this.props.visibleOptions.map(function (option, index) { return _this4.renderItem(option, index); }); } else if (this.props.hasFilter()) { return this.renderEmptyFilter(); } return null; } }, { key: "renderContent", value: function renderContent() { var _this5 = this; if (this.props.virtualScrollerOptions) { var virtualScrollerProps = _objectSpread$1(_objectSpread$1({}, this.props.virtualScrollerOptions), { style: _objectSpread$1(_objectSpread$1({}, this.props.virtualScrollerOptions.style), { height: this.props.scrollHeight }), className: core.classNames('p-multiselect-items-wrapper', this.props.virtualScrollerOptions.className), items: this.props.visibleOptions, onLazyLoad: function onLazyLoad(event) { return _this5.props.virtualScrollerOptions.onLazyLoad(_objectSpread$1(_objectSpread$1({}, event), { filter: _this5.props.filterValue })); }, itemTemplate: function itemTemplate(item, options) { return item && _this5.renderItem(item, options.index); }, contentTemplate: function contentTemplate(options) { var className = core.classNames('p-multiselect-items p-component', options.className); var content = _this5.isEmptyFilter() ? _this5.renderEmptyFilter() : options.children; return /*#__PURE__*/React__default['default'].createElement("ul", { ref: options.ref, className: className, role: "listbox", "aria-multiselectable": true }, content); } }); return /*#__PURE__*/React__default['default'].createElement(virtualscroller.VirtualScroller, _extends({ ref: function ref(el) { return _this5.virtualScrollerRef = el; } }, virtualScrollerProps)); } else { var items = this.renderItems(); return /*#__PURE__*/React__default['default'].createElement("div", { className: "p-multiselect-items-wrapper", style: { maxHeight: this.props.scrollHeight } }, /*#__PURE__*/React__default['default'].createElement("ul", { className: "p-multiselect-items p-component", role: "listbox", "aria-multiselectable": true }, items)); } } }, { key: "renderElement", value: function renderElement() { var panelClassName = core.classNames('p-multiselect-panel p-component', { 'p-multiselect-limited': !this.props.allowOptionSelect() }, this.props.panelClassName); var header = this.renderHeader(); var content = this.renderContent(); var footer = this.renderFooter(); return /*#__PURE__*/React__default['default'].createElement(core.CSSTransition, { nodeRef: this.props.forwardRef, classNames: "p-connected-overlay", in: this.props.in, timeout: { enter: 120, exit: 100 }, options: this.props.transitionOptions, unmountOnExit: true, onEnter: this.onEnter, onEntered: this.props.onEntered, onExit: this.props.onExit, onExited: this.props.onExited }, /*#__PURE__*/React__default['default'].createElement("div", { ref: this.props.forwardRef, className: panelClassName, style: this.props.panelStyle, onClick: this.props.onClick }, header, content, footer)); } }, { key: "render", value: function render() { var element = this.renderElement(); return /*#__PURE__*/React__default['default'].createElement(core.Portal, { element: element, appendTo: this.props.appendTo }); } }]); return MultiSelectPanelComponent; }(React.Component); var MultiSelectPanel = /*#__PURE__*/React__default['default'].forwardRef(function (props, ref) { return /*#__PURE__*/React__default['default'].createElement(MultiSelectPanelComponent, _extends({ forwardRef: ref }, props)); }); function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var MultiSelect = /*#__PURE__*/function (_Component) { _inherits(MultiSelect, _Component); var _super = _createSuper(MultiSelect); function MultiSelect(props) { var _this; _classCallCheck(this, MultiSelect); _this = _super.call(this, props); _this.state = { filter: '', focused: false, overlayVisible: false }; _this.onClick = _this.onClick.bind(_assertThisInitialized(_this)); _this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this)); _this.onOptionSelect = _this.onOptionSelect.bind(_assertThisInitialized(_this)); _this.onOptionKeyDown = _this.onOptionKeyDown.bind(_assertThisInitialized(_this)); _this.onFocus = _this.onFocus.bind(_assertThisInitialized(_this)); _this.onBlur = _this.onBlur.bind(_assertThisInitialized(_this)); _this.onFilterInputChange = _this.onFilterInputChange.bind(_assertThisInitialized(_this)); _this.onCloseClick = _this.onCloseClick.bind(_assertThisInitialized(_this)); _this.onSelectAll = _this.onSelectAll.bind(_assertThisInitialized(_this)); _this.onOverlayEnter = _this.onOverlayEnter.bind(_assertThisInitialized(_this)); _this.onOverlayEntered = _this.onOverlayEntered.bind(_assertThisInitialized(_this)); _this.onOverlayExit = _this.onOverlayExit.bind(_assertThisInitialized(_this)); _this.onOverlayExited = _this.onOverlayExited.bind(_assertThisInitialized(_this)); _this.onPanelClick = _this.onPanelClick.bind(_assertThisInitialized(_this)); _this.getOptionLabel = _this.getOptionLabel.bind(_assertThisInitialized(_this)); _this.getOptionRenderKey = _this.getOptionRenderKey.bind(_assertThisInitialized(_this)); _this.isOptionDisabled = _this.isOptionDisabled.bind(_assertThisInitialized(_this)); _this.getOptionGroupChildren = _this.getOptionGroupChildren.bind(_assertThisInitialized(_this)); _this.getOptionGroupLabel = _this.getOptionGroupLabel.bind(_assertThisInitialized(_this)); _this.getOptionGroupRenderKey = _this.getOptionGroupRenderKey.bind(_assertThisInitialized(_this)); _this.allowOptionSelect = _this.allowOptionSelect.bind(_assertThisInitialized(_this)); _this.isSelected = _this.isSelected.bind(_assertThisInitialized(_this)); _this.isAllSelected = _this.isAllSelected.bind(_assertThisInitialized(_this)); _this.hasFilter = _this.hasFilter.bind(_assertThisInitialized(_this)); _this.getSelectedOptionIndex = _this.getSelectedOptionIndex.bind(_assertThisInitialized(_this)); _this.hide = _this.hide.bind(_assertThisInitialized(_this)); _this.onOptionKeyDown = _this.onOptionKeyDown.bind(_assertThisInitialized(_this)); _this.overlayRef = /*#__PURE__*/React.createRef(); _this.inputRef = /*#__PURE__*/React.createRef(_this.props.inputRef); return _this; } _createClass(MultiSelect, [{ key: "onPanelClick", value: function onPanelClick(event) { core.OverlayService.emit('overlay-click', { originalEvent: event, target: this.container }); } }, { key: "allowOptionSelect", value: function allowOptionSelect() { return !this.props.selectionLimit || !this.props.value || this.props.value && this.props.value.length < this.props.selectionLimit; } }, { key: "onOptionSelect", value: function onOptionSelect(event) { var _this2 = this; var originalEvent = event.originalEvent, option = event.option; if (this.props.disabled || this.isOptionDisabled(option)) { return; } var optionValue = this.getOptionValue(option); var isOptionValueUsed = this.isOptionValueUsed(option); var selected = this.isSelected(option); var allowOptionSelect = this.allowOptionSelect(); if (selected) this.updateModel(originalEvent, this.props.value.filter(function (val) { return !core.ObjectUtils.equals(isOptionValueUsed ? val : _this2.getOptionValue(val), optionValue, _this2.equalityKey()); }));else if (allowOptionSelect) this.updateModel(originalEvent, [].concat(_toConsumableArray(this.props.value || []), [optionValue])); } }, { key: "onOptionKeyDown", value: function onOptionKeyDown(event) { var originalEvent = event.originalEvent; var listItem = originalEvent.currentTarget; switch (originalEvent.which) { //down case 40: var nextItem = this.findNextItem(listItem); if (nextItem) { nextItem.focus(); } originalEvent.preventDefault(); break; //up case 38: var prevItem = this.findPrevItem(listItem); if (prevItem) { prevItem.focus(); } originalEvent.preventDefault(); break; //enter and space case 13: case 32: this.onOptionSelect(event); originalEvent.preventDefault(); break; //escape case 27: this.hide(); this.inputRef.current.focus(); break; } } }, { key: "findNextItem", value: function findNextItem(item) { var nextItem = item.nextElementSibling; if (nextItem) return core.DomHandler.hasClass(nextItem, 'p-disabled') || core.DomHandler.hasClass(nextItem, 'p-multiselect-item-group') ? this.findNextItem(nextItem) : nextItem;else return null; } }, { key: "findPrevItem", value: function findPrevItem(item) { var prevItem = item.previousElementSibling; if (prevItem) return core.DomHandler.hasClass(prevItem, 'p-disabled') || core.DomHandler.hasClass(prevItem, 'p-multiselect-item-group') ? this.findPrevItem(prevItem) : prevItem;else return null; } }, { key: "onClick", value: function onClick(event) { if (!this.props.disabled && !this.isPanelClicked(event) && !core.DomHandler.hasClass(event.target, 'p-multiselect-token-icon') && !this.isClearClicked(event)) { if (this.state.overlayVisible) { this.hide(); } else { this.show(); } this.inputRef.current.focus(); } } }, { key: "onKeyDown", value: function onKeyDown(event) { switch (event.which) { //down case 40: if (!this.state.overlayVisible && event.altKey) { this.show(); event.preventDefault(); } break; //space case 32: if (this.state.overlayVisible) this.hide();else this.show(); event.preventDefault(); break; //escape case 27: this.hide(); break; //tab case 9: if (this.state.overlayVisible) { var firstFocusableElement = core.DomHandler.getFirstFocusableElement(this.overlayRef.current); if (firstFocusableElement) { firstFocusableElement.focus(); event.preventDefault(); } } break; } } }, { key: "onSelectAll", value: function onSelectAll(event) { var _this3 = this; if (this.props.onSelectAll) { this.props.onSelectAll(event); } else { var value = null; var visibleOptions = this.getVisibleOptions(); if (event.checked) { value = []; if (visibleOptions) { var selectedOptions = visibleOptions.filter(function (option) { return _this3.isOptionDisabled(option) && _this3.isSelected(option); }); value = selectedOptions.map(function (option) { return _this3.getOptionValue(option); }); } } else if (visibleOptions) { visibleOptions = visibleOptions.filter(function (option) { return !_this3.isOptionDisabled(option); }); if (this.props.optionGroupLabel) { value = []; visibleOptions.forEach(function (optionGroup) { return value = [].concat(_toConsumableArray(value), _toConsumableArray(_this3.getOptionGroupChildren(optionGroup).filter(function (option) { return !_this3.isOptionDisabled(option); }).map(function (option) { return _this3.getOptionValue(option); }))); }); } else { value = visibleOptions.map(function (option) { return _this3.getOptionValue(option); }); } value = _toConsumableArray(new Set([].concat(_toConsumableArray(value), _toConsumableArray(this.props.value || [])))); } this.updateModel(event.originalEvent, value); } } }, { key: "updateModel", value: function updateModel(event, value) { if (this.props.onChange) { this.props.onChange({ originalEvent: event, value: value, stopPropagation: function stopPropagation() {}, preventDefault: function preventDefault() {}, target: { name: this.props.name, id: this.props.id, value: value } }); } } }, { key: "onFilterInputChange", value: function onFilterInputChange(event) { var _this4 = this; var filter = event.query; this.setState({ filter: filter }, function () { if (_this4.props.onFilter) { _this4.props.onFilter({ originalEvent: event, filter: filter }); } }); } }, { key: "resetFilter", value: function resetFilter() { var _this5 = this; var filter = ''; this.setState({ filter: filter }, function () { _this5.props.onFilter && _this5.props.onFilter({ filter: filter }); }); } }, { key: "show", value: function show() { this.setState({ overlayVisible: true }); } }, { key: "hide", value: function hide() { this.setState({ overlayVisible: false }); } }, { key: "onOverlayEnter", value: function onOverlayEnter(callback) { core.ZIndexUtils.set('overlay', this.overlayRef.current); this.alignOverlay(); this.scrollInView(); callback && callback(); } }, { key: "onOverlayEntered", value: function onOverlayEntered(callback) { this.bindDocumentClickListener(); this.bindScrollListener(); this.bindResizeListener(); callback && callback(); this.props.onShow && this.props.onShow(); } }, { key: "onOverlayExit", value: function onOverlayExit() { this.unbindDocumentClickListener(); this.unbindScrollListener(); this.unbindResizeListener(); } }, { key: "onOverlayExited", value: function onOverlayExited() { if (this.props.filter && this.props.resetFilterOnHide) { this.resetFilter(); } core.ZIndexUtils.clear(this.overlayRef.current); this.props.onHide && this.props.onHide(); } }, { key: "alignOverlay", value: function alignOverlay() { core.DomHandler.alignOverlay(this.overlayRef.current, this.label.parentElement, this.props.appendTo || PrimeReact__default['default'].appendTo); } }, { key: "scrollInView", value: function scrollInView() { var highlightItem = core.DomHandler.findSingle(this.overlayRef.current, 'li.p-highlight'); if (highlightItem) { highlightItem.scrollIntoView({ block: 'nearest', inline: 'start' }); } } }, { key: "onCloseClick", value: function onCloseClick(event) { this.hide(); this.inputRef.current.focus(); event.preventDefault(); event.stopPropagation(); } }, { key: "getSelectedOptionIndex", value: function getSelectedOptionIndex() { if (this.props.value != null && this.props.options) { if (this.props.optionGroupLabel) { for (var i = 0; i < this.props.options.length; i++) { var selectedOptionIndex = this.findOptionIndexInList(this.props.value, this.getOptionGroupChildren(this.props.options[i])); if (selectedOptionIndex !== -1) { return { group: i, option: selectedOptionIndex }; } } } else { return this.findOptionIndexInList(this.props.value, this.props.options); } } return -1; } }, { key: "findOptionIndexInList", value: function findOptionIndexInList(value, list) { var _this6 = this; var key = this.equalityKey(); return list.findIndex(function (item) { return value.some(function (val) { return core.ObjectUtils.equals(val, _this6.getOptionValue(item), key); }); }); } }, { key: "isSelected", value: function isSelected(option) { var _this7 = this; var selected = false; if (this.props.value) { var optionValue = this.getOptionValue(option); var isOptionValueUsed = this.isOptionValueUsed(option); var key = this.equalityKey(); selected = this.props.value.some(function (val) { return core.ObjectUtils.equals(isOptionValueUsed ? val : _this7.getOptionValue(val), optionValue, key); }); } return selected; } }, { key: "getLabelByValue", value: function getLabelByValue(val) { var option; if (this.props.options) { if (this.props.optionGroupLabel) { var _iterator = _createForOfIteratorHelper(this.props.options), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var optionGroup = _step.value; option = this.findOptionByValue(val, this.getOptionGroupChildren(optionGroup)); if (option) { break; } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } } else { option = this.findOptionByValue(val, this.props.options); } } return option ? this.getOptionLabel(option) : null; } }, { key: "findOptionByValue", value: function findOptionByValue(val, list) { var key = this.equalityKey(); var _iterator2 = _createForOfIteratorHelper(list), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var option = _step2.value; var optionValue = this.getOptionValue(option); if (core.ObjectUtils.equals(optionValue, val, key)) { return option; } } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } return null; } }, { key: "onFocus", value: function onFocus(event) { var _this8 = this; event.persist(); this.setState({ focused: true }, function () { if (_this8.props.onFocus) { _this8.props.onFocus(event); } }); } }, { key: "onBlur", value: function onBlur(event) { var _this9 = this; event.persist(); this.setState({ focused: false }, function () { if (_this9.props.onBlur) { _this9.props.onBlur(event); } }); } }, { key: "bindDocumentClickListener", value: function bindDocumentClickListener() { var _this10 = this; if (!this.documentClickListener) { this.documentClickListener = function (event) { if (_this10.state.overlayVisible && _this10.isOutsideClicked(event)) { _this10.hide(); } }; document.addEventListener('click', this.documentClickListener); } } }, { key: "bindScrollListener", value: function bindScrollListener() { var _this11 = this; if (!this.scrollHandler) { this.scrollHandler = new core.ConnectedOverlayScrollHandler(this.container, function () { if (_this11.state.overlayVisible) { _this11.hide(); } }); } this.scrollHandler.bindScrollListener(); } }, { key: "unbindScrollListener", value: function unbindScrollListener() { if (this.scrollHandler) { this.scrollHandler.unbindScrollListener(); } } }, { key: "bindResizeListener", value: function bindResizeListener() { var _this12 = this; if (!this.resizeListener) { this.resizeListener = function () { if (_this12.state.overlayVisible && !core.DomHandler.isAndroid()) { _this12.hide(); } }; window.addEventListener('resize', this.resizeListener); } } }, { key: "unbindResizeListener", value: function unbindResizeListener() { if (this.resizeListener) { window.removeEventListener('resize', this.resizeListener); this.resizeListener = null; } } }, { key: "isOutsideClicked", value: function isOutsideClicked(event) { return this.container && !(this.container.isSameNode(event.target) || this.isClearClicked(event) || this.container.contains(event.target) || this.isPanelClicked(event)); } }, { key: "isClearClicked", value: function isClearClicked(event) { return core.DomHandler.hasClass(event.target, 'p-multiselect-clear-icon'); } }, { key: "isPanelClicked", value: function isPanelClicked(event) { return this.overlayRef && this.overlayRef.current && this.overlayRef.current.contains(event.target); } }, { key: "unbindDocumentClickListener", value: function unbindDocumentClickListener() { if (this.documentClickListener) { document.removeEventListener('click', this.documentClickListener); this.documentClickListener = null; } } }, { key: "updateInputRef", value: function updateInputRef() { var ref = this.props.inputRef; if (ref) { if (typeof ref === 'function') { ref(this.inputRef.current); } else { ref.current = this.inputRef.current; } } } }, { key: "componentDidMount", value: function componentDidMount() { this.updateInputRef(); if (this.props.tooltip) { this.renderTooltip(); } } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { if (prevProps.tooltip !== this.props.tooltip || prevProps.tooltipOptions !== this.props.tooltipOptions) { if (this.tooltip) this.tooltip.update(_objectSpread({ content: this.props.tooltip }, this.props.tooltipOptions || {}));else this.renderTooltip(); } if (this.state.overlayVisible && this.hasFilter()) { this.alignOverlay(); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.unbindDocumentClickListener(); this.unbindResizeListener(); if (this.scrollHandler) { this.scrollHandler.destroy(); this.scrollHandler = null; } if (this.tooltip) { this.tooltip.destroy(); this.tooltip = null; } core.ZIndexUtils.clear(this.overlayRef.current); } }, { key: "hasFilter", value: function hasFilter() { return this.state.filter && this.state.filter.trim().length > 0; } }, { key: "isAllSelected", value: function isAllSelected() { var _this13 = this; if (this.props.onSelectAll) { return this.props.selectAll; } else { var visibleOptions = this.getVisibleOptions(); if (visibleOptions.length === 0) { return false; } visibleOptions = visibleOptions.filter(function (option) { return !_this13.isOptionDisabled(option); }); if (this.props.optionGroupLabel) { var _iterator3 = _createForOfIteratorHelper(visibleOptions), _step3; try { for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { var optionGroup = _step3.value; var visibleOptionsGroupChildren = this.getOptionGroupChildren(optionGroup).filter(function (option) { return !_this13.isOptionDisabled(option); }); var _iterator4 = _createForOfIteratorHelper(visibleOptionsGroupChildren), _step4; try { for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { var option = _step4.value; if (!this.isSelected(option)) { return false; } } } catch (err) { _iterator4.e(err); } finally { _iterator4.f(); } } } catch (err) { _iterator3.e(err); } finally { _iterator3.f(); } } else { var _iterator5 = _createForOfIteratorHelper(visibleOptions), _step5; try { for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) { var _option = _step5.value; if (!this.isSelected(_option)) { return false; } } } catch (err) { _iterator5.e(err); } finally { _iterator5.f(); } } } return true; } }, { key: "getOptionLabel", value: function getOptionLabel(option) { return this.props.optionLabel ? core.ObjectUtils.resolveFieldData(option, this.props.optionLabel) : option && option['label'] !== undefined ? option['label'] : option; } }, { key: "getOptionValue", value: function getOptionValue(option) { if (this.props.optionValue) { var data = core.ObjectUtils.resolveFieldData(option, this.props.optionValue); return data !== null ? data : option; } return option && option['value'] !== undefined ? option['value'] : option; } }, { key: "getOptionRenderKey", value: function getOptionRenderKey(option) { return this.props.dataKey ? core.ObjectUtils.resolveFieldData(option, this.props.dataKey) : this.getOptionLabel(option); } }, { key: "getOptionGroupRenderKey", value: function getOptionGroupRenderKey(optionGroup) { return core.ObjectUtils.resolveFieldData(optionGroup, this.props.optionGroupLabel); } }, { key: "getOptionGroupLabel", value: function getOptionGroupLabel(optionGroup) { return core.ObjectUtils.resolveFieldData(optionGroup, this.props.optionGroupLabel); } }, { key: "getOptionGroupChildren", value: function getOptionGroupChildren(optionGroup) { return core.ObjectUtils.resolveFieldData(optionGroup, this.props.optionGroupChildren); } }, { key: "isOptionDisabled", value: function isOptionDisabled(option) { if (this.props.optionDisabled) { return core.ObjectUtils.isFunction(this.props.optionDisabled) ? this.props.optionDisabled(option) : core.ObjectUtils.resolveFieldData(option, this.props.optionDisabled); } return option && option['disabled'] !== undefined ? option['disabled'] : false; } }, { key: "isOptionValueUsed", value: function isOptionValueUsed(option) { return this.props.optionValue || option && option['value'] !== undefined; } }, { key: "getVisibleOptions", value: function getVisibleOptions() { if (this.hasFilter()) { var filterValue = this.state.filter.trim().toLocaleLowerCase(this.props.filterLocale); var searchFields = this.props.filterBy ? this.props.filterBy.split(',') : [this.props.optionLabel || 'label']; if (this.props.optionGroupLabel) { var filteredGroups = []; var _iterator6 = _createForOfIteratorHelper(this.props.options), _step6; try { for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) { var optgroup = _step6.value; var filteredSubOptions = core.FilterUtils.filter(this.getOptionGroupChildren(optgroup), searchFields, filterValue, this.props.filterMatchMode, this.props.filterLocale); if (filteredSubOptions && filteredSubOptions.length) { filteredGroups.push(_objectSpread(_objectSpread({}, optgroup), { items: filteredSubOptions })); } } } catch (err) { _iterator6.e(err); } finally { _iterator6.f(); } return filteredGroups; } else { return core.FilterUtils.filter(this.props.options, searchFields, filterValue, this.props.filterMatchMode, this.props.filterLocale); } } else { return this.props.options; } } }, { key: "isEmpty", value: function isEmpty() { return !this.props.value || this.props.value.length === 0; } }, { key: "equalityKey", value: function equalityKey() { return this.props.optionValue ? null : this.props.dataKey; } }, { key: "checkValidity", value: function checkValidity() { return this.inputRef.current.checkValidity(); } }, { key: "removeChip", value: function removeChip(event, item) { var key = this.equalityKey(); var value = this.props.value.filter(function (val) { return !core.ObjectUtils.equals(val, item, key); }); this.updateModel(event, value); } }, { key: "getSelectedItemsLabel", value: function getSelectedItemsLabel() { var pattern = /{(.*?)}/; if (pattern.test(this.props.selectedItemsLabel)) { return this.props.selectedItemsLabel.replace(this.props.selectedItemsLabel.match(pattern)[0], this.props.value.length + ''); } return this.props.selectedItemsLabel; } }, { key: "getLabel", value: function getLabel() { var label; if (!this.isEmpty() && !this.props.fixedPlaceholder) { if (this.props.value.length <= this.props.maxSelectedLabels) { label = ''; for (var i = 0; i < this.props.value.length; i++) { if (i !== 0) { label += ','; } label += this.getLabelByValue(this.props.value[i]); } return label; } else { return this.getSelectedItemsLabel(); } } return label; } }, { key: "getLabelContent", value: function getLabelContent() { var _this14 = this; if (this.props.selectedItemTemplate) { if (!this.isEmpty()) { if (this.props.value.length <= this.props.maxSelectedLabels) { return this.props.value.map(function (val, index) { var item = core.ObjectUtils.getJSXElement(_this14.props.selectedItemTemplate, val); return /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, { key: index }, item); }); } else { return this.getSelectedItemsLabel(); } } else { return core.ObjectUtils.getJSXElement(this.props.selectedItemTemplate); } } else { if (this.props.display === 'chip' && !this.isEmpty()) { return this.props.value.map(function (val) { var label = _this14.getLabelByValue(val); return /*#__PURE__*/React__default['default'].createElement("div", { className: "p-multiselect-token", key: label }, /*#__PURE__*/React__default['default'].createElement("span", { className: "p-multiselect-token-label" }, label), !_this14.props.disabled && /*#__PURE__*/React__default['default'].createElement("span", { className: "p-multiselect-token-icon pi pi-times-circle", onClick: function onClick(e) { return _this14.removeChip(e, val); } })); }); } return this.getLabel(); } } }, { key: "renderTooltip", value: function renderTooltip() { this.tooltip = core.tip({ target: this.container, content: this.props.tooltip, options: this.props.tooltipOptions }); } }, { key: "renderClearIcon", value: function renderClearIcon() { var _this15 = this; var empty = this.isEmpty(); if (!empty && this.props.showClear && !this.props.disabled) { return /*#__PURE__*/React__default['default'].createElement("i", { className: "p-multiselect-clear-icon pi pi-times", onClick: function onClick(e) { return _this15.updateModel(e, null); } }); } return null; } }, { key: "renderLabel", value: function renderLabel() { var _this16 = this; var empty = this.isEmpty(); var content = this.getLabelContent(); var labelClassName = core.classNames('p-multiselect-label', { 'p-placeholder': empty && this.props.placeholder, 'p-multiselect-label-empty': empty && !this.props.placeholder && !this.props.selectedItemTemplate, 'p-multiselect-items-label': !empty && this.props.value.length > this.props.maxSelectedLabels }); return /*#__PURE__*/React__default['default'].createElement("div", { ref: function ref(el) { return _this16.label = el; }, className: "p-multiselect-label-container" }, /*#__PURE__*/React__default['default'].createElement("div", { className: labelClassName }, content || this.props.placeholder || 'empty')); } }, { key: "render", value: function render() { var _this17 = this; var className = core.classNames('p-multiselect p-component p-inputwrapper', { 'p-multiselect-chip': this.props.display === 'chip', 'p-disabled': this.props.disabled, 'p-multiselect-clearable': this.props.showClear && !this.props.disabled, 'p-focus': this.state.focused, 'p-inputwrapper-filled': this.props.value && this.props.value.length > 0, 'p-inputwrapper-focus': this.state.focused || this.state.overlayVisible }, this.props.className); var iconClassName = core.classNames('p-multiselect-trigger-icon p-c', this.props.dropdownIcon); var visibleOptions = this.getVisibleOptions(); var label = this.renderLabel(); var clearIcon = this.renderClearIcon(); return /*#__PURE__*/React__default['default'].createElement("div", { id: this.props.id, className: className, onClick: this.onClick, ref: function ref(el) { return _this17.container = el; }, style: this.props.style }, /*#__PURE__*/React__default['default'].createElement("div", { className: "p-hidden-accessible" }, /*#__PURE__*/React__default['default'].createElement("input", { ref: this.inputRef, id: this.props.inputId, name: this.props.name, readOnly: true, type: "text", onFocus: this.onFocus, onBlur: this.onBlur, onKeyDown: this.onKeyDown, role: "listbox", "aria-haspopup": "listbox", "aria-labelledby": this.props.ariaLabelledBy, "aria-expanded": this.state.overlayVisible, disabled: this.props.disabled, tabIndex: this.props.tabIndex })), label, clearIcon, /*#__PURE__*/React__default['default'].createElement("div", { className: "p-multiselect-trigger" }, /*#__PURE__*/React__default['default'].createElement("span", { className: iconClassName })), /*#__PURE__*/React__default['default'].createElement(MultiSelectPanel, _extends({ ref: this.overlayRef, visibleOptions: visibleOptions }, this.props, { onClick: this.onPanelClick, onOverlayHide: this.hide, filterValue: this.state.filter, hasFilter: this.hasFilter, onFilterInputChange: this.onFilterInputChange, onCloseClick: this.onCloseClick, onSelectAll: this.onSelectAll, getOptionLabel: this.getOptionLabel, getOptionRenderKey: this.getOptionRenderKey, isOptionDisabled: this.isOptionDisabled, getOptionGroupChildren: this.getOptionGroupChildren, getOptionGroupLabel: this.getOptionGroupLabel, getOptionGroupRenderKey: this.getOptionGroupRenderKey, isSelected: this.isSelected, getSelectedOptionIndex: this.getSelectedOptionIndex, isAllSelected: this.isAllSelected, onOptionSelect: this.onOptionSelect, allowOptionSelect: this.allowOptionSelect, onOptionKeyDown: this.onOptionKeyDown, in: this.state.overlayVisible, onEnter: this.onOverlayEnter, onEntered: this.onOverlayEntered, onExit: this.onOverlayExit, onExited: this.onOverlayExited }))); } }]); return MultiSelect; }(React.Component); _defineProperty(MultiSelect, "defaultProps", { id: null, inputRef: null, name: null, value: null, options: null, optionLabel: null, optionValue: null, optionDisabled: null, optionGroupLabel: null, optionGroupChildren: null, optionGroupTemplate: null, display: 'comma', style: null, className: null, panelClassName: null, panelStyle: null, virtualScrollerOptions: null, scrollHeight: '200px', placeholder: null, fixedPlaceholder: false, disabled: false, showClear: false, filter: false, filterBy: null, filterMatchMode: 'contains', filterPlaceholder: null, filterLocale: undefined, emptyFilterMessage: 'No results found', resetFilterOnHide: false, tabIndex: 0, dataKey: null, inputId: null, appendTo: null, tooltip: null, tooltipOptions: null, maxSelectedLabels: 3, selectionLimit: null, selectedItemsLabel: '{0} items selected', ariaLabelledBy: null, itemTemplate: null, selectedItemTemplate: null, panelHeaderTemplate: null, panelFooterTemplate: null, transitionOptions: null, dropdownIcon: 'pi pi-chevron-down', showSelectAll: true, selectAll: false, onChange: null, onFocus: null, onBlur: null, onShow: null, onHide: null, onFilter: null, onSelectAll: null }); exports.MultiSelect = MultiSelect; Object.defineProperty(exports, '__esModule', { value: true }); return exports; }({}, React, primereact.core, primereact.inputtext, primereact.virtualscroller, primereact.api));
cdnjs/cdnjs
ajax/libs/primereact/6.5.1/multiselect/multiselect.js
JavaScript
mit
72,104
/* * * * License: www.highcharts.com/license * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ 'use strict'; import H from '../parts/Globals.js'; import U from '../parts/Utilities.js'; var isArray = U.isArray; import reduceArrayMixin from '../mixins/reduce-array.js'; import multipleLinesMixin from '../mixins/multipe-lines.js'; var merge = H.merge, SMA = H.seriesTypes.sma, getArrayExtremes = reduceArrayMixin.getArrayExtremes; /** * The Stochastic series type. * * @private * @class * @name Highcharts.seriesTypes.stochastic * * @augments Highcharts.Series */ H.seriesType('stochastic', 'sma', /** * Stochastic oscillator. This series requires the `linkedTo` option to be * set and should be loaded after the `stock/indicators/indicators.js` file. * * @sample stock/indicators/stochastic * Stochastic oscillator * * @extends plotOptions.sma * @since 6.0.0 * @product highstock * @excluding allAreas, colorAxis, joinBy, keys, navigatorOptions, * pointInterval, pointIntervalUnit, pointPlacement, * pointRange, pointStart, showInNavigator, stacking * @requires stock/indicators/indicators * @requires stock/indicators/stochastic * @optionparent plotOptions.stochastic */ { /** * @excluding index, period */ params: { /** * Periods for Stochastic oscillator: [%K, %D]. * * @type {Array<number,number>} * @default [14, 3] */ periods: [14, 3] }, marker: { enabled: false }, tooltip: { pointFormat: '<span style="color:{point.color}">\u25CF</span><b> {series.name}</b><br/>%K: {point.y}<br/>%D: {point.smoothed}<br/>' }, /** * Smoothed line options. */ smoothedLine: { /** * Styles for a smoothed line. */ styles: { /** * Pixel width of the line. */ lineWidth: 1, /** * Color of the line. If not set, it's inherited from * [plotOptions.stochastic.color * ](#plotOptions.stochastic.color). * * @type {Highcharts.ColorString} */ lineColor: undefined } }, dataGrouping: { approximation: 'averages' } }, /** * @lends Highcharts.Series# */ H.merge(multipleLinesMixin, { nameComponents: ['periods'], nameBase: 'Stochastic', pointArrayMap: ['y', 'smoothed'], parallelArrays: ['x', 'y', 'smoothed'], pointValKey: 'y', linesApiNames: ['smoothedLine'], init: function () { SMA.prototype.init.apply(this, arguments); // Set default color for lines: this.options = merge({ smoothedLine: { styles: { lineColor: this.color } } }, this.options); }, getValues: function (series, params) { var periodK = params.periods[0], periodD = params.periods[1], xVal = series.xData, yVal = series.yData, yValLen = yVal ? yVal.length : 0, // 0- date, 1-%K, 2-%D SO = [], xData = [], yData = [], slicedY, close = 3, low = 2, high = 1, CL, HL, LL, K, D = null, points, extremes, i; // Stochastic requires close value if (yValLen < periodK || !isArray(yVal[0]) || yVal[0].length !== 4) { return false; } // For a N-period, we start from N-1 point, to calculate Nth point // That is why we later need to comprehend slice() elements list // with (+1) for (i = periodK - 1; i < yValLen; i++) { slicedY = yVal.slice(i - periodK + 1, i + 1); // Calculate %K extremes = getArrayExtremes(slicedY, low, high); LL = extremes[0]; // Lowest low in %K periods CL = yVal[i][close] - LL; HL = extremes[1] - LL; K = CL / HL * 100; xData.push(xVal[i]); yData.push([K, null]); // Calculate smoothed %D, which is SMA of %K if (i >= (periodK - 1) + (periodD - 1)) { points = SMA.prototype.getValues.call(this, { xData: xData.slice(-periodD), yData: yData.slice(-periodD) }, { period: periodD }); D = points.yData[0]; } SO.push([xVal[i], K, D]); yData[yData.length - 1][1] = D; } return { values: SO, xData: xData, yData: yData }; } })); /** * A Stochastic indicator. If the [type](#series.stochastic.type) option is not * specified, it is inherited from [chart.type](#chart.type). * * @extends series,plotOptions.stochastic * @since 6.0.0 * @product highstock * @excluding allAreas, colorAxis, dataParser, dataURL, joinBy, keys, * navigatorOptions, pointInterval, pointIntervalUnit, * pointPlacement, pointRange, pointStart, showInNavigator, stacking * @requires stock/indicators/indicators * @requires stock/indicators/stochastic * @apioption series.stochastic */ ''; // to include the above in the js output
cdnjs/cdnjs
ajax/libs/highcharts/7.2.2/es-modules/indicators/stochastic.src.js
JavaScript
mit
5,303
from __future__ import print_function class Sequence(object): def __init__(self, name, seq): """ :param seq: the sequence :type seq: string """ self.name = name self.sequence = seq def __len__(self): return len(self.sequence) def to_fasta(self): id_ = self.name.replace(' ', '_') fasta = '>{}\n'.format(id_) start = 0 while start < len(self.sequence): end = start + 80 fasta += self.sequence[start: end + 1] + '\n' start = end return fasta class DNASequence(Sequence): alphabet = 'ATGC' def gc_percent(self): return float(self.sequence.count('G') + self.sequence.count('C')) / len(self.sequence) class AASequence(Sequence): _water = 18.0153 _weight_table = {'A': 89.0932, 'C': 121.1582, 'E': 147.1293, 'D': 133.1027, 'G': 75.0666, 'F': 165.1891, 'I': 131.1729, 'H': 155.1546, 'K': 146.1876, 'M': 149.2113, 'L': 131.1729, 'O': 255.3134, 'N': 132.1179, 'Q': 146.1445, 'P': 115.1305, 'S': 105.0926, 'R': 174.201, 'U': 168.0532, 'T': 119.1192, 'W': 204.2252, 'V': 117.1463, 'Y': 181.1885} def molecular_weight(self): return sum([self._weight_table[aa] for aa in self.sequence]) - (len(self.sequence) - 1) * self._water
C3BI-pasteur-fr/python-course-1
source/_static/code/inheritance_sequence.py
Python
cc0-1.0
1,463
/** * Copyright (c) 2014 openHAB UG (haftungsbeschraenkt) and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.eclipse.smarthome.core.transform.internal; /** * @author Thomas.Eichstaedt-Engelen */ public abstract class AbstractTransformationServiceTest { protected String source = "<?xml version=\"1.0\"?><xml_api_reply version=\"1\"><weather module_id=\"0\"" + " tab_id=\"0\" mobile_row=\"0\" mobile_zipped=\"1\" row=\"0\" section=\"0\" ><forecast_information>" + "<city data=\"Krefeld, North Rhine-Westphalia\"/><postal_code data=\"Krefeld Germany\"/>" + "<latitude_e6 data=\"\"/><longitude_e6 data=\"\"/><forecast_date data=\"2011-03-01\"/>" + "<current_date_time data=\"2011-03-01 15:20:00 +0000\"/><unit_system data=\"SI\"/></forecast_information>" + "<current_conditions><condition data=\"Meistens bew�lkt\"/><temp_f data=\"46\"/><temp_c data=\"8\"/>" + "<humidity data=\"Feuchtigkeit: 66 %\"/><icon data=\"/ig/images/weather/mostly_cloudy.gif\"/>" + "<wind_condition data=\"Wind: N mit 26 km/h\"/></current_conditions><forecast_conditions><day_of_week data=\"Di.\"/>" + "<low data=\"-1\"/><high data=\"6\"/><icon data=\"/ig/images/weather/sunny.gif\"/><condition data=\"Klar\"/>" + "</forecast_conditions><forecast_conditions><day_of_week data=\"Mi.\"/><low data=\"-1\"/><high data=\"8\"/>" + "<icon data=\"/ig/images/weather/sunny.gif\"/><condition data=\"Klar\"/></forecast_conditions><forecast_conditions>" + "<day_of_week data=\"Do.\"/><low data=\"-1\"/><high data=\"8\"/><icon data=\"/ig/images/weather/sunny.gif\"/>" + "<condition data=\"Klar\"/></forecast_conditions><forecast_conditions><day_of_week data=\"Fr.\"/><low data=\"0\"/>" + "<high data=\"8\"/><icon data=\"/ig/images/weather/sunny.gif\"/><condition data=\"Klar\"/></forecast_conditions>" + "</weather></xml_api_reply>"; }
innoq/smarthome
bundles/core/org.eclipse.smarthome.core.transform.test/src/test/java/org/eclipse/smarthome/core/transform/internal/AbstractTransformationServiceTest.java
Java
epl-1.0
2,058
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.1.9-03/31/2009 04:14 PM(snajper)-fcs // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2009.07.19 at 07:21:12 PM EDT // package seg.jUCMNav.importexport.z151.generated; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for Description complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="Description"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="description" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "Description", propOrder = { "description" }) public class Description { @XmlElement(required = true) protected String description; /** * Gets the value of the description property. * * @return * possible object is * {@link String } * */ public String getDescription() { return description; } /** * Sets the value of the description property. * * @param value * allowed object is * {@link String } * */ public void setDescription(String value) { this.description = value; } }
McGill-DP-Group/seg.jUCMNav
src/seg/jUCMNav/importexport/z151/generated/Description.java
Java
epl-1.0
1,823
/****************************************************************************** * * Copyright 2014 Paphus Solutions Inc. * * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html * * 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 android.app; import java.awt.Cursor; /** * Stub class. */ public class ProgressDialog extends AlertDialog { public ProgressDialog(Activity activty) { super(activty); } public void show() { this.activity.frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); } public void dismiss() { this.activity.frame.setCursor(Cursor.getDefaultCursor()); } public void setCancelable(boolean cancelable){ } }
BOTlibre/BOTlibre
swingdroid/source/android/app/ProgressDialog.java
Java
epl-1.0
1,233
/******************************************************************************* * Copyright (c) 2019 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.jaxws.test.wsr.client; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.util.Iterator; import java.util.Map; import javax.xml.namespace.QName; import javax.xml.stream.FactoryConfigurationError; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.ws.BindingProvider; import com.ibm.websphere.simplicity.RemoteFile; import componenttest.topology.impl.LibertyServer; import componenttest.topology.utils.HttpUtils; public class TestUtils { /* * This method is to work around the issue of the hard-coded address and port value which specified in the wsdl file. * A servlet could use this util to reset the EndpointAddress with the correct addr and value of a test server. * In future, if the we support vendor plan, we could specify the values there. */ public static void setEndpointAddressProperty(BindingProvider bp, String serverAddr, int serverPort) throws IOException { String endpointAddr = bp.getRequestContext().get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY).toString(); URL endpointUrl = new URL(endpointAddr); String newEndpointAddr = endpointUrl.getProtocol() + "://" + serverAddr + ":" + serverPort + endpointUrl.getPath(); bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, newEndpointAddr); } /** * Validate the XML attributes * * @param is * @param attributeParams The Map.Entry key likes "targetNamespace=http://com.ibm/jaxws/testmerge/replace/", value likes "{http://schemas.xmlsoap.org/wsdl/}definitions" * @return * @throws XMLStreamException * @throws FactoryConfigurationError */ public static Map<String, QName> validateXMLAttributes(InputStream is, Map<String, QName> attributeParams) throws XMLStreamException, FactoryConfigurationError { XMLStreamReader reader = null; try { reader = XMLInputFactory.newInstance().createXMLStreamReader(is); while (reader.hasNext()) { int event = reader.next(); if (XMLStreamConstants.START_ELEMENT == event) { Iterator<Map.Entry<String, QName>> iter = attributeParams.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, QName> entry = iter.next(); String[] keyValuePair = entry.getKey().split("="); QName elementQName = entry.getValue(); if (reader.getLocalName().equals(elementQName.getLocalPart()) && reader.getNamespaceURI().equals(elementQName.getNamespaceURI()) && compareAttribute(reader, keyValuePair[0], keyValuePair[1])) { iter.remove(); } } if (attributeParams.isEmpty()) { break; } } } } finally { if (reader != null) { reader.close(); } } return attributeParams; } private static boolean compareAttribute(XMLStreamReader reader, String attrName, String attrValue) { int count = reader.getAttributeCount(); for (int i = 0; i < count; i++) { String name = reader.getAttributeLocalName(i); String value = reader.getAttributeValue(i); if (name.equals(attrName) && value.equals(attrValue)) { return true; } } return false; } /** * Copy the file to server, rename if the targetFileName is not equal to srcFileName. * * @param server, the LibertyServer * @param srcPathFromPubishFolder, the folder path relative to publish folder * @param srcFileName, the source file name to copy * @param targetPathFromServerRoot, the target path relative to server root * @param targetFileName, the target file name * @throws Exception */ public static void publishFileToServer(LibertyServer server, String srcPathFromPubishFolder, String srcFileName, String targetPathFromServerRoot, String targetFileName) throws Exception { server.copyFileToLibertyServerRoot(targetPathFromServerRoot, srcPathFromPubishFolder + "/" + srcFileName); if (targetFileName != null && !targetFileName.isEmpty() && !targetFileName.equals(srcFileName)) { server.renameLibertyServerRootFile(targetPathFromServerRoot + "/" + srcFileName, targetPathFromServerRoot + "/" + targetFileName); } } /** * Replace the string in a server file. * * @param server, the LibertyServer * @param filePathFromServerRoot, the file path relative to server root * @param fromStr, the string that need replace in the file. * @param toStr, the string to replace the original one. * @throws Exception */ public static void replaceServerFileString(LibertyServer server, String filePathFromServerRoot, String fromStr, String toStr) throws Exception { InputStream is = null; OutputStream os = null; try { RemoteFile serverFile = server.getFileFromLibertyServerRoot(filePathFromServerRoot); is = serverFile.openForReading(); StringBuilder builder = new StringBuilder(); //read InputStreamReader isr = new InputStreamReader(is); BufferedReader bfin = new BufferedReader(isr); String rLine = ""; while ((rLine = bfin.readLine()) != null) { builder.append(rLine); } is.close(); //replace String xmiText = builder.toString(); String updatedText = xmiText.replaceAll(fromStr, toStr); //write os = serverFile.openForWriting(false); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os)); writer.write(updatedText); writer.close(); } catch (Exception e) { throw e; } finally { if (is != null) { try { is.close(); } catch (IOException e) { //ignore; } } if (os != null) { try { os.close(); } catch (IOException e) { //ignore; } } } } public static String getServletResponse(String servletUrl) throws Exception { URL url = new URL(servletUrl); HttpURLConnection con = HttpUtils.getHttpConnection(url, HttpURLConnection.HTTP_OK, 10); BufferedReader br = HttpUtils.getConnectionStream(con); String result = br.readLine(); String line; while ((line = br.readLine()) != null) { result += line; } return result; } }
OpenLiberty/open-liberty
dev/com.ibm.ws.jaxws.clientcontainer_fat/fat/src/com/ibm/ws/jaxws/test/wsr/client/TestUtils.java
Java
epl-1.0
7,976
/******************************************************************************* * Copyright (c) 2012-2016 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package org.eclipse.che.ide.ext.java.client.action; import com.google.gwtmockito.GwtMockitoTestRunner; import org.eclipse.che.api.promises.client.Operation; import org.eclipse.che.api.promises.client.Promise; import org.eclipse.che.api.promises.client.PromiseError; import org.eclipse.che.api.workspace.shared.dto.ProjectConfigDto; import org.eclipse.che.ide.api.action.ActionEvent; import org.eclipse.che.ide.api.action.Presentation; import org.eclipse.che.ide.api.app.AppContext; import org.eclipse.che.ide.api.app.CurrentProject; import org.eclipse.che.ide.api.notification.NotificationManager; import org.eclipse.che.ide.api.selection.Selection; import org.eclipse.che.ide.ext.java.client.JavaLocalizationConstant; import org.eclipse.che.ide.ext.java.client.JavaResources; import org.eclipse.che.ide.ext.java.client.project.classpath.ClasspathResolver; import org.eclipse.che.ide.ext.java.client.project.classpath.service.ClasspathServiceClient; import org.eclipse.che.ide.ext.java.client.project.node.PackageNode; import org.eclipse.che.ide.ext.java.client.project.node.SourceFolderNode; import org.eclipse.che.ide.ext.java.shared.dto.classpath.ClasspathEntryDto; import org.eclipse.che.ide.part.explorer.project.ProjectExplorerPresenter; import org.eclipse.che.ide.project.node.FolderReferenceNode; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Matchers; import org.mockito.Mock; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import static org.eclipse.che.ide.api.notification.StatusNotification.DisplayMode.EMERGE_MODE; import static org.eclipse.che.ide.api.notification.StatusNotification.Status.FAIL; import static org.mockito.Matchers.anyBoolean; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * Test for {@link MarkDirAsSourceAction} * * @author Valeriy Svydenko */ @RunWith(GwtMockitoTestRunner.class) public class MarkDirAsSourceActionTest { final private static String PROJECT_PATH = "/projects/path"; final private static String TEXT = "to be or not to be"; @Mock private JavaResources javaResources; @Mock private AppContext appContext; @Mock private ClasspathServiceClient classpathService; @Mock private ClasspathResolver classpathResolver; @Mock private NotificationManager notificationManager; @Mock private ProjectExplorerPresenter projectExplorerPresenter; @Mock private JavaLocalizationConstant locale; @Mock private CurrentProject currentProject; @Mock private ProjectConfigDto projectConfigDto; @Mock private ActionEvent actionEvent; @Mock private Presentation presentation; @Mock private Selection selection; @Mock private FolderReferenceNode folderReferenceNode; @Mock private Promise<List<ClasspathEntryDto>> classpathPromise; @Mock private PromiseError promiseError; @Captor private ArgumentCaptor<Operation<List<ClasspathEntryDto>>> classpathCapture; @Captor private ArgumentCaptor<Operation<PromiseError>> classpathErrorCapture; @InjectMocks private MarkDirAsSourceAction action; @Before public void setUp() throws Exception { when(appContext.getCurrentProject()).thenReturn(currentProject); when(currentProject.getProjectConfig()).thenReturn(projectConfigDto); when(projectConfigDto.getPath()).thenReturn(PROJECT_PATH); when(projectExplorerPresenter.getSelection()).thenReturn(selection); when(selection.getHeadElement()).thenReturn(folderReferenceNode); when(actionEvent.getPresentation()).thenReturn(presentation); FolderReferenceNode folder = mock(FolderReferenceNode.class); when(selection.getHeadElement()).thenReturn(folder); when(classpathService.getClasspath(anyString())).thenReturn(classpathPromise); when(classpathPromise.then(Matchers.<Operation<List<ClasspathEntryDto>>>anyObject())).thenReturn(classpathPromise); } @Test public void titleAndDescriptionShouldBeSet() throws Exception { verify(locale).markDirectoryAsSourceAction(); verify(locale).markDirectoryAsSourceDescription(); } @Test public void actionShouldBePerformed() throws Exception { List<ClasspathEntryDto> classpathEntries = new ArrayList<>(); Set<String> sources = new HashSet<>(); when(folderReferenceNode.getStorablePath()).thenReturn(TEXT); when(classpathResolver.getSources()).thenReturn(sources); action.actionPerformed(actionEvent); verify(classpathService.getClasspath(PROJECT_PATH)).then(classpathCapture.capture()); classpathCapture.getValue().apply(classpathEntries); verify(classpathResolver).resolveClasspathEntries(classpathEntries); verify(classpathResolver).getSources(); Assert.assertEquals(1, sources.size()); verify(classpathResolver).updateClasspath(); } @Test public void readingClasspathFailed() throws Exception { action.actionPerformed(actionEvent); when(promiseError.getMessage()).thenReturn(TEXT); verify(classpathService.getClasspath(PROJECT_PATH)).catchError(classpathErrorCapture.capture()); classpathErrorCapture.getValue().apply(promiseError); verify(notificationManager).notify("Can't get classpath", TEXT, FAIL, EMERGE_MODE); } @Test public void actionShouldBeHideIfSelectedNodeIsSource() throws Exception { SourceFolderNode sourceFolder = mock(SourceFolderNode.class); when(selection.getHeadElement()).thenReturn(sourceFolder); action.updateInPerspective(actionEvent); verify(presentation).setVisible(false); verify(presentation).setEnabled(anyBoolean()); } @Test public void actionShouldBeVisibleIfSelectedNodeIsNotSource() throws Exception { action.updateInPerspective(actionEvent); verify(presentation).setVisible(true); verify(presentation).setEnabled(anyBoolean()); } @Test public void actionShouldBeDisableIfSelectionIsMultiple() throws Exception { when(selection.isSingleSelection()).thenReturn(false); action.updateInPerspective(actionEvent); verify(presentation).setVisible(anyBoolean()); verify(presentation).setEnabled(false); } @Test public void actionShouldBeDisableIfSelectedNodeIsPackage() throws Exception { PackageNode packageNode = mock(PackageNode.class); when(selection.getHeadElement()).thenReturn(packageNode); when(selection.isSingleSelection()).thenReturn(true); action.updateInPerspective(actionEvent); verify(presentation).setVisible(anyBoolean()); verify(presentation).setEnabled(false); } @Test public void actionShouldBeDisableIfSelectedNodeIsNotFolder() throws Exception { Object someNode = mock(Object.class); when(selection.getHeadElement()).thenReturn(someNode); when(selection.isSingleSelection()).thenReturn(true); action.updateInPerspective(actionEvent); verify(presentation).setVisible(anyBoolean()); verify(presentation).setEnabled(false); } }
stour/che
plugins/plugin-java/che-plugin-java-ext-lang-client/src/test/java/org/eclipse/che/ide/ext/java/client/action/MarkDirAsSourceActionTest.java
Java
epl-1.0
8,195
/******************************************************************************* * Copyright (c) 2006, 2018 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.ejbcontainer.injection.ann.ejb; import javax.ejb.CreateException; import javax.ejb.EJBLocalHome; /** * Compatibility EJBLocalHome interface for CompCatBean. **/ public interface CatEJBLocalHome extends EJBLocalHome { /** * @return CatEJBLocal The SessionBean EJB object. * @exception javax.ejb.CreateException SessionBean EJB object was not created. */ public CatEJBLocal create() throws CreateException; }
OpenLiberty/open-liberty
dev/com.ibm.ws.ejbcontainer.injection_fat/test-applications/EJB3INJSABean.jar/src/com/ibm/ws/ejbcontainer/injection/ann/ejb/CatEJBLocalHome.java
Java
epl-1.0
995
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.zwave.internal.protocol.commandclass; import java.util.Arrays; import java.util.List; import org.openhab.binding.zwave.internal.protocol.SerialMessage; import org.openhab.binding.zwave.internal.protocol.ZWaveNode; import org.openhab.binding.zwave.internal.protocol.initialization.ZWaveNodeStageAdvancer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Used only by {@link ZWaveSecurityCommandClassWithInitialization} during device inclusion. * * During device inclusion, the security registration process between us and the node * has multiple stages in order to share our network key with the device. This class * is used to track our current state in that process and determine next steps. * * The specific commands to be exchanged are: * {@value #INIT_COMMAND_ORDER_LIST} * * @author Dave Badia * @since TODO */ class ZWaveSecureInclusionStateTracker { private static final Logger logger = LoggerFactory.getLogger(ZWaveSecureInclusionStateTracker.class); /** * During node inclusion <b>only</b>, this is the order in which commands should be sent and received. * Commands absent from this list (for example {@link #SECURITY_MESSAGE_ENCAP}) can be sent/received at any time */ private final List<Byte> INIT_COMMAND_ORDER_LIST = Arrays.asList(new Byte[]{ ZWaveSecurityCommandClass.SECURITY_SCHEME_GET, ZWaveSecurityCommandClass.SECURITY_SCHEME_REPORT, ZWaveSecurityCommandClass.SECURITY_NETWORK_KEY_SET, ZWaveSecurityCommandClass.SECURITY_NETWORK_KEY_VERIFY, ZWaveSecurityCommandClass.SECURITY_COMMANDS_SUPPORTED_GET, ZWaveSecurityCommandClass.SECURITY_COMMANDS_SUPPORTED_REPORT, }); private static final boolean HALT_ON_IMPROPER_ORDER = true; private byte currentStep = INIT_COMMAND_ORDER_LIST.get(0); /** * After we send a non-nonce security message, we can wait up to 10 seconds * for a reply. Then we must exit the inclusion process */ private static final int WAIT_TIME_MILLIS = 10000; /** * The next {@link SerialMessage} that will be given to {@link ZWaveNodeStageAdvancer} * when it calls {@link ZWaveSecurityCommandClass#initialize(boolean)} */ private SerialMessage nextRequestMessage = null; /** * Lock object that will be used for synchronization */ private final Object nextMessageLock = new Object(); private String errorState = null; private long waitForReplyTimeout = 0; private final ZWaveNode node; ZWaveSecureInclusionStateTracker(ZWaveNode node) { this.node = node; } /** * Since these operations are security sensitive we must ensure they are * executing in the proper sequence * @param newStep the state we are about to enter * @return true if the new command was in an acceptable order, false * if it was not. if false is returned, the response should <b>not</b> * be sent. */ synchronized boolean verifyAndAdvanceState(Byte newStep) { logger.debug("NODE {}: ZWaveSecurityCommandClass in verifyAndAdvanceState with newstep={}, currentstep={}", node.getNodeId(), ZWaveSecurityCommandClass.commandToString(newStep), ZWaveSecurityCommandClass.commandToString(currentStep)); if(!INIT_COMMAND_ORDER_LIST.contains(newStep)) { // Commands absent from EXPECTED_COMMAND_ORDER_LIST are always ok return true; } // Going back to the first step (zero index) is always OK // TODO: DB is it really? if(INIT_COMMAND_ORDER_LIST.indexOf(newStep) > 0) { // We have to verify where we are at int currentIndex = INIT_COMMAND_ORDER_LIST.indexOf(currentStep); int newIndex = INIT_COMMAND_ORDER_LIST.indexOf(newStep); // Accept one message back or the same message(device resending last reply) in addition to the normal one message ahead if(newIndex != currentIndex && newIndex - currentIndex > 1) { if(HALT_ON_IMPROPER_ORDER) { setErrorState(String.format("NODE %s: Commands received out of order, aborting current=%s, new=%s", node.getNodeId(), ZWaveSecurityCommandClass.commandToString(currentStep), ZWaveSecurityCommandClass.commandToString(newStep))); return false; } else { logger.warn("NODE {}: Commands received out of order (warning only, continuing) current={}, new={}", node.getNodeId(), ZWaveSecurityCommandClass.commandToString(currentStep), ZWaveSecurityCommandClass.commandToString(newStep)); // fall through below } } } currentStep = newStep; return true; } public void setErrorState(String errorState) { this.errorState = errorState; } public void resetWaitForReplyTimeout() { waitForReplyTimeout = System.currentTimeMillis() + WAIT_TIME_MILLIS; } void setNextRequest(SerialMessage message) { logger.debug("NODE {}: in InclusionStateTracker.setNextRequest() (current={}) with {}", node.getNodeId(), (nextRequestMessage != null), message); if(nextRequestMessage != null) { logger.warn("NODE {}: in InclusionStateTracker.setNextRequest() overriding old message which was never sent of {}", node.getNodeId(), message); } verifyAndAdvanceState((byte) (message.getMessagePayloadByte(3) & 0xff)); synchronized(nextMessageLock) { nextRequestMessage = message; nextMessageLock.notify(); } } /** * Gets the next message to be sent during the inclusion flow. * Each message can only get retrieved once * @return the next message or null if there was none */ SerialMessage getNextRequest() { synchronized(nextMessageLock) { logger.debug("NODE {}: in InclusionStateTracker.getNextRequest() time left for reply: {}ms, returning {}", node.getNodeId(), (System.currentTimeMillis() - waitForReplyTimeout), nextRequestMessage); if(System.currentTimeMillis() > waitForReplyTimeout) { // waited too long for a reply, secure inclusion failed setErrorState(WAIT_TIME_MILLIS+"ms passed since last request was sent, secure inclusion failed."); return null; } if(nextRequestMessage != null) { SerialMessage message = nextRequestMessage; resetWaitForReplyTimeout(); nextRequestMessage = null; return message; } return null; } } public byte getCurrentStep() { return currentStep; } public String getErrorState() { return errorState; } }
openhab/openhab
bundles/binding/org.openhab.binding.zwave/src/main/java/org/openhab/binding/zwave/internal/protocol/commandclass/ZWaveSecureInclusionStateTracker.java
Java
epl-1.0
7,375
import java.util.logging.Level; import java.util.logging.Logger; public class Main { /** * @param args */ public static void main(String[] args) { Thread t1 = new Hilo(0); t1.start(); try { t1.join(); } catch (InterruptedException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } }
davidhmhernandez/ServiciosyProcesos
Concurrencia1Act7/src/Main.java
Java
epl-1.0
384
package eu.modelwriter.specification.editor.scanner; import org.eclipse.jface.text.TextAttribute; import org.eclipse.jface.text.rules.IToken; import org.eclipse.jface.text.rules.RuleBasedScanner; import org.eclipse.jface.text.rules.Token; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.widgets.Display; import eu.modelwriter.specification.editor.RGBStorage; public class LoadScanner extends RuleBasedScanner { public LoadScanner() { final IToken loadToken = new Token(new TextAttribute(new Color(Display.getCurrent(), RGBStorage.LOAD_RGB))); setDefaultReturnToken(loadToken); } }
ModelWriter/Tarski
Source/eu.modelwriter.specification.editor/src/eu/modelwriter/specification/editor/scanner/LoadScanner.java
Java
epl-1.0
619
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.tinkerforge.internal.model.impl; import org.eclipse.emf.ecore.EClass; import org.openhab.binding.tinkerforge.internal.model.Electrode; import org.openhab.binding.tinkerforge.internal.model.ModelPackage; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Electrode</b></em>'. * * @author Theo Weiss * @since 1.5.0 * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.ElectrodeImpl#getDeviceType <em>Device * Type</em>}</li> * </ul> * * @generated */ public class ElectrodeImpl extends MultiTouchDeviceImpl implements Electrode { /** * The default value of the '{@link #getDeviceType() <em>Device Type</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getDeviceType() * @generated * @ordered */ protected static final String DEVICE_TYPE_EDEFAULT = "electrode"; /** * The cached value of the '{@link #getDeviceType() <em>Device Type</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getDeviceType() * @generated * @ordered */ protected String deviceType = DEVICE_TYPE_EDEFAULT; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ protected ElectrodeImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override protected EClass eStaticClass() { return ModelPackage.Literals.ELECTRODE; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public String getDeviceType() { return deviceType; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case ModelPackage.ELECTRODE__DEVICE_TYPE: return getDeviceType(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case ModelPackage.ELECTRODE__DEVICE_TYPE: return DEVICE_TYPE_EDEFAULT == null ? deviceType != null : !DEVICE_TYPE_EDEFAULT.equals(deviceType); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (deviceType: "); result.append(deviceType); result.append(')'); return result.toString(); } } // ElectrodeImpl
openhab/openhab
bundles/binding/org.openhab.binding.tinkerforge/src/main/java/org/openhab/binding/tinkerforge/internal/model/impl/ElectrodeImpl.java
Java
epl-1.0
3,535
/******************************************************************************* * Copyright (c) 2016 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.logstash.collector.v10; import org.osgi.framework.Version; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.ConfigurationPolicy; import com.ibm.ws.logstash.collector.LogstashRuntimeVersion; @Component(name = LogstashCollector10.COMPONENT_NAME, service = { LogstashRuntimeVersion.class }, configurationPolicy = ConfigurationPolicy.IGNORE, property = { "service.vendor=IBM" }) public class LogstashCollector10 implements LogstashRuntimeVersion { public static final String COMPONENT_NAME = "com.ibm.ws.logstash.collector.v10.LogstashCollector10"; @Override public Version getVersion() { return VERSION_1_0; } }
OpenLiberty/open-liberty
dev/com.ibm.ws.logstash.collector.1.0/src/com/ibm/ws/logstash/collector/v10/LogstashCollector10.java
Java
epl-1.0
1,247
package com.coverity.ws.v9; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for updateStreamDefects complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="updateStreamDefects"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="streamDefectIds" type="{http://ws.coverity.com/v9}streamDefectIdDataObj" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="defectStateSpec" type="{http://ws.coverity.com/v9}defectStateSpecDataObj" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "updateStreamDefects", propOrder = { "streamDefectIds", "defectStateSpec" }) public class UpdateStreamDefects { protected List<StreamDefectIdDataObj> streamDefectIds; protected DefectStateSpecDataObj defectStateSpec; /** * Gets the value of the streamDefectIds property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the streamDefectIds property. * * <p> * For example, to add a new item, do as follows: * <pre> * getStreamDefectIds().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link StreamDefectIdDataObj } * * */ public List<StreamDefectIdDataObj> getStreamDefectIds() { if (streamDefectIds == null) { streamDefectIds = new ArrayList<StreamDefectIdDataObj>(); } return this.streamDefectIds; } /** * Gets the value of the defectStateSpec property. * * @return * possible object is * {@link DefectStateSpecDataObj } * */ public DefectStateSpecDataObj getDefectStateSpec() { return defectStateSpec; } /** * Sets the value of the defectStateSpec property. * * @param value * allowed object is * {@link DefectStateSpecDataObj } * */ public void setDefectStateSpec(DefectStateSpecDataObj value) { this.defectStateSpec = value; } }
christ66/coverity-plugin
src/main/java/com/coverity/ws/v9/UpdateStreamDefects.java
Java
epl-1.0
2,691
/******************************************************************************* * Copyright (C) 2011, Jens Baumgart <jens.baumgart@sap.com> * Copyright (C) 2011, Stefan Lay <stefan.lay@sap.com> * Copyright (C) 2015, Thomas Wolf <thomas.wolf@paranor.ch> * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.eclipse.egit.ui.internal.history; import java.io.IOException; import java.util.Collection; import java.util.List; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.egit.ui.Activator; import org.eclipse.egit.ui.JobFamilies; import org.eclipse.egit.ui.internal.UIText; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revplot.PlotCommit; class FormatJob extends Job { @Override public boolean belongsTo(Object family) { if (JobFamilies.FORMAT_COMMIT_INFO.equals(family)) return true; return super.belongsTo(family); } private Object lock = new Object(); // guards formatRequest and formatResult private FormatRequest formatRequest; private FormatResult formatResult; FormatJob(FormatRequest formatRequest) { super(UIText.FormatJob_buildingCommitInfo); this.formatRequest = formatRequest; } FormatResult getFormatResult() { synchronized(lock) { return formatResult; } } @Override protected IStatus run(IProgressMonitor monitor) { if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } FormatResult commitInfo; CommitInfoBuilder builder; try { synchronized(lock) { SWTCommit commit = (SWTCommit)formatRequest.getCommit(); commit.parseBody(); builder = new CommitInfoBuilder(formatRequest.getRepository(), commit, formatRequest.isFill(), formatRequest.getAllRefs()); } commitInfo = builder.format(monitor); } catch (IOException e) { return Activator.createErrorStatus(e.getMessage(), e); } if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } synchronized(lock) { formatResult = commitInfo; } return Status.OK_STATUS; } static class FormatRequest { public Collection<Ref> getAllRefs() { return allRefs; } public void setAllRefs(Collection<Ref> allRefs) { this.allRefs = allRefs; } private Repository repository; private PlotCommit<?> commit; private boolean fill; private Collection<Ref> allRefs; FormatRequest(Repository repository, PlotCommit<?> commit, boolean fill, Collection<Ref> allRefs) { this.repository = repository; this.commit = commit; this.fill = fill; this.allRefs = allRefs; } public Repository getRepository() { return repository; } public PlotCommit<?> getCommit() { return commit; } public boolean isFill() { return fill; } } static class FormatResult{ private final String commitInfo; private final List<GitCommitReference> knownLinks; private final int headerEnd; private final int footerStart; FormatResult(String commmitInfo, List<GitCommitReference> links, int headerEnd, int footerStart) { this.commitInfo = commmitInfo; this.knownLinks = links; this.headerEnd = headerEnd; this.footerStart = footerStart; } public String getCommitInfo() { return commitInfo; } public List<GitCommitReference> getKnownLinks() { return knownLinks; } public int getHeaderEnd() { return headerEnd; } public int getFooterStart() { return footerStart; } } }
SmithAndr/egit
org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/history/FormatJob.java
Java
epl-1.0
3,809
/* * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.config.yangjmxgenerator.plugin; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.io.FileUtils; import org.apache.maven.project.MavenProject; import org.opendaylight.controller.config.spi.ModuleFactory; import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry; import org.opendaylight.controller.config.yangjmxgenerator.PackageTranslator; import org.opendaylight.controller.config.yangjmxgenerator.ServiceInterfaceEntry; import org.opendaylight.controller.config.yangjmxgenerator.TypeProviderWrapper; import org.opendaylight.yangtools.sal.binding.yang.types.TypeProviderImpl; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode; import org.opendaylight.yangtools.yang.model.api.Module; import org.opendaylight.yangtools.yang.model.api.SchemaContext; import org.opendaylight.yangtools.yang2sources.spi.BasicCodeGenerator; import org.opendaylight.yangtools.yang2sources.spi.MavenProjectAware; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class interfaces with yang-maven-plugin. Gets parsed yang modules in * {@link SchemaContext}, and parameters form the plugin configuration, and * writes service interfaces and/or modules. */ public class JMXGenerator implements BasicCodeGenerator, MavenProjectAware { private static final class NamespaceMapping { private final String namespace, packageName; public NamespaceMapping(final String namespace, final String packagename) { this.namespace = namespace; this.packageName = packagename; } } @VisibleForTesting static final String NAMESPACE_TO_PACKAGE_DIVIDER = "=="; @VisibleForTesting static final String NAMESPACE_TO_PACKAGE_PREFIX = "namespaceToPackage"; @VisibleForTesting static final String MODULE_FACTORY_FILE_BOOLEAN = "moduleFactoryFile"; private static final Logger LOG = LoggerFactory.getLogger(JMXGenerator.class); private static final Pattern NAMESPACE_MAPPING_PATTERN = Pattern.compile("(.+)" + NAMESPACE_TO_PACKAGE_DIVIDER + "(.+)"); private PackageTranslator packageTranslator; private final CodeWriter codeWriter; private Map<String, String> namespaceToPackageMapping; private File resourceBaseDir; private File projectBaseDir; private boolean generateModuleFactoryFile = true; public JMXGenerator() { this(new CodeWriter()); } public JMXGenerator(final CodeWriter codeWriter) { this.codeWriter = codeWriter; } @Override public Collection<File> generateSources(final SchemaContext context, final File outputBaseDir, final Set<Module> yangModulesInCurrentMavenModule) { Preconditions.checkArgument(context != null, "Null context received"); Preconditions.checkArgument(outputBaseDir != null, "Null outputBaseDir received"); Preconditions .checkArgument(namespaceToPackageMapping != null && !namespaceToPackageMapping.isEmpty(), "No namespace to package mapping provided in additionalConfiguration"); packageTranslator = new PackageTranslator(namespaceToPackageMapping); if (!outputBaseDir.exists()) { outputBaseDir.mkdirs(); } GeneratedFilesTracker generatedFiles = new GeneratedFilesTracker(); // create SIE structure qNamesToSIEs Map<QName, ServiceInterfaceEntry> qNamesToSIEs = new HashMap<>(); Map<IdentitySchemaNode, ServiceInterfaceEntry> knownSEITracker = new HashMap<>(); for (Module module : context.getModules()) { String packageName = packageTranslator.getPackageName(module); Map<QName, ServiceInterfaceEntry> namesToSIEntries = ServiceInterfaceEntry .create(module, packageName, knownSEITracker); for (Entry<QName, ServiceInterfaceEntry> sieEntry : namesToSIEntries .entrySet()) { // merge value into qNamesToSIEs if (qNamesToSIEs.containsKey(sieEntry.getKey()) == false) { qNamesToSIEs.put(sieEntry.getKey(), sieEntry.getValue()); } else { throw new IllegalStateException( "Cannot add two SIE with same qname " + sieEntry.getValue()); } } if (yangModulesInCurrentMavenModule.contains(module)) { // write this sie to disk for (ServiceInterfaceEntry sie : namesToSIEntries.values()) { try { generatedFiles.addFile(codeWriter.writeSie(sie, outputBaseDir)); } catch (Exception e) { throw new RuntimeException( "Error occurred during SIE source generate phase", e); } } } } File mainBaseDir = concatFolders(projectBaseDir, "src", "main", "java"); Preconditions.checkNotNull(resourceBaseDir, "resource base dir attribute was null"); StringBuilder fullyQualifiedNamesOfFactories = new StringBuilder(); // create MBEs for (Module module : yangModulesInCurrentMavenModule) { String packageName = packageTranslator.getPackageName(module); Map<String /* MB identity local name */, ModuleMXBeanEntry> namesToMBEs = ModuleMXBeanEntry .create(module, qNamesToSIEs, context, new TypeProviderWrapper(new TypeProviderImpl(context)), packageName); for (Entry<String, ModuleMXBeanEntry> mbeEntry : namesToMBEs .entrySet()) { ModuleMXBeanEntry mbe = mbeEntry.getValue(); try { List<File> files1 = codeWriter.writeMbe(mbe, outputBaseDir, mainBaseDir); generatedFiles.addFile(files1); } catch (Exception e) { throw new RuntimeException( "Error occurred during MBE source generate phase", e); } fullyQualifiedNamesOfFactories.append(mbe .getFullyQualifiedName(mbe.getStubFactoryName())); fullyQualifiedNamesOfFactories.append("\n"); } } // create ModuleFactory file if needed if (fullyQualifiedNamesOfFactories.length() > 0 && generateModuleFactoryFile) { File serviceLoaderFile = JMXGenerator.concatFolders( resourceBaseDir, "META-INF", "services", ModuleFactory.class.getName()); // if this file does not exist, create empty file serviceLoaderFile.getParentFile().mkdirs(); try { serviceLoaderFile.createNewFile(); FileUtils.write(serviceLoaderFile, fullyQualifiedNamesOfFactories.toString()); } catch (IOException e) { String message = "Cannot write to " + serviceLoaderFile; LOG.error(message); throw new RuntimeException(message, e); } } return generatedFiles.getFiles(); } @VisibleForTesting static File concatFolders(final File projectBaseDir, final String... folderNames) { StringBuilder b = new StringBuilder(); for (String folder : folderNames) { b.append(folder); b.append(File.separator); } return new File(projectBaseDir, b.toString()); } @Override public void setAdditionalConfig(final Map<String, String> additionalCfg) { LOG.debug("{}: Additional configuration received: {}", getClass().getCanonicalName(), additionalCfg); this.namespaceToPackageMapping = extractNamespaceMapping(additionalCfg); this.generateModuleFactoryFile = extractModuleFactoryBoolean(additionalCfg); } private boolean extractModuleFactoryBoolean( final Map<String, String> additionalCfg) { String bool = additionalCfg.get(MODULE_FACTORY_FILE_BOOLEAN); if (bool == null) { return true; } if ("false".equals(bool)) { return false; } return true; } private static Map<String, String> extractNamespaceMapping( final Map<String, String> additionalCfg) { Map<String, String> namespaceToPackage = Maps.newHashMap(); for (String key : additionalCfg.keySet()) { if (key.startsWith(NAMESPACE_TO_PACKAGE_PREFIX)) { String mapping = additionalCfg.get(key); NamespaceMapping mappingResolved = extractNamespaceMapping(mapping); namespaceToPackage.put(mappingResolved.namespace, mappingResolved.packageName); } } return namespaceToPackage; } private static NamespaceMapping extractNamespaceMapping(final String mapping) { Matcher matcher = NAMESPACE_MAPPING_PATTERN.matcher(mapping); Preconditions.checkArgument(matcher.matches(), "Namespace to package mapping:%s is in invalid format, requested format is: %s", mapping, NAMESPACE_MAPPING_PATTERN); return new NamespaceMapping(matcher.group(1), matcher.group(2)); } @Override public void setResourceBaseDir(final File resourceDir) { this.resourceBaseDir = resourceDir; } @Override public void setMavenProject(final MavenProject project) { this.projectBaseDir = project.getBasedir(); LOG.debug("{}: project base dir: {}", getClass().getCanonicalName(), projectBaseDir); } @VisibleForTesting static class GeneratedFilesTracker { private final Set<File> files = Sets.newHashSet(); void addFile(final File file) { if (files.contains(file)) { List<File> undeletedFiles = Lists.newArrayList(); for (File presentFile : files) { if (presentFile.delete() == false) { undeletedFiles.add(presentFile); } } if (undeletedFiles.isEmpty() == false) { LOG.error( "Illegal state occurred: Unable to delete already generated files, undeleted files: {}", undeletedFiles); } throw new IllegalStateException( "Name conflict in generated files, file" + file + " present twice"); } files.add(file); } void addFile(final Collection<File> files) { for (File file : files) { addFile(file); } } public Set<File> getFiles() { return files; } } }
my76128/controller
opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/JMXGenerator.java
Java
epl-1.0
11,935
package de.cooperateproject.modeling.textual.common.naming; import java.util.List; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EReference; import org.eclipse.uml2.uml.NamedElement; import org.eclipse.xtext.nodemodel.INode; import org.eclipse.xtext.nodemodel.util.NodeModelUtils; import de.cooperateproject.modeling.textual.common.metamodel.textualCommons.PackageImport; import de.cooperateproject.modeling.textual.common.metamodel.textualCommons.TextualCommonsPackage; import de.cooperateproject.modeling.textual.common.metamodel.textualCommons.util.TextualCommonsSwitch; public class NameSwitch extends TextualCommonsSwitch<String> { @Override public String casePackageImport(PackageImport object) { return determineNameOfReferencedNamedElement(object, TextualCommonsPackage.Literals.UML_REFERENCING_ELEMENT__REFERENCED_ELEMENT); } @Override public String caseNamedElement( de.cooperateproject.modeling.textual.common.metamodel.textualCommons.NamedElement object) { Object result = object.eGet(TextualCommonsPackage.Literals.NAMED_ELEMENT__NAME, false); if (result != null) { return (String) result; } return determineNameOfReferencedNamedElement(object, TextualCommonsPackage.Literals.UML_REFERENCING_ELEMENT__REFERENCED_ELEMENT); } private String determineNameOfReferencedNamedElement(EObject object, EReference umlReference) { List<INode> nodes = NodeModelUtils.findNodesForFeature(object, umlReference); if (!nodes.isEmpty()) { return normalizeNodeName(NodeModelUtils.getTokenText(nodes.get(0))); } Object referencedElement = object.eGet(umlReference, false); if (referencedElement instanceof NamedElement) { return ((NamedElement) referencedElement).getName(); } return null; } private static String normalizeNodeName(String nodeName) { if (nodeName != null && nodeName.matches("\\\".*\\\"")) { return nodeName.subSequence(1, nodeName.length() - 1).toString(); } return nodeName; } }
Cooperate-Project/Cooperate
bundles/de.cooperateproject.modeling.textual.common/src/de/cooperateproject/modeling/textual/common/naming/NameSwitch.java
Java
epl-1.0
2,176
/******************************************************************************* * Copyright (c) 2015 UT-Battelle, LLC. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Robert Smith *******************************************************************************/ package org.eclipse.eavp.viz.modeling.factory; import org.eclipse.eavp.viz.modeling.base.IMesh; /** * A interface for classes which serve IControllerProviders. An * IControllerFactory takes as input an IMesh and returns an IControllerProvider * which is capable of processing that IMesh. An IControllerFactory * implementation should be specific as to what kind of view and/or controller * its IControllerProviders create, as the same IMesh may be valid for use with * multiple separate implementations of IView and IController. * * @author Robert Smith * */ public interface IControllerProviderFactory { /** * Creates a controller and associated view for the given model. * * @param model * The model for which a controller will be created * @return The new controller, which contains the input model and the new * view */ public IControllerProvider createProvider(IMesh model); }
jarrah42/eavp
org.eclipse.eavp.viz.modeling/src/org/eclipse/eavp/viz/modeling/factory/IControllerProviderFactory.java
Java
epl-1.0
1,456
/******************************************************************************* * Copyright (c) 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ define(["intern!tdd","intern/chai!assert","dojo/Deferred","js/toolbox/toolbox"], function(tdd,assert,Deferred,toolbox) { var server, testBookmark, testFeatureTool; with(assert) { /** * Defines the 'toolbox' module test suite. */ tdd.suite("Toolbox Tests", function() { tdd.before(function() { testBookmark = { id: "myTool", type:"bookmark", name:"myTool", url:"ibm.com", icon:"default.png" }; testToolEntry = { id: "myFeature-1.0", type:"featureTool", }; }); tdd.beforeEach(function() { // Mock the admin center server since it is not available in a unittest server = sinon.fakeServer.create(); }); tdd.afterEach(function() { server.restore(); }); tdd.test("ToolEntry - create from ToolEntry", function() { var tool = new Toolbox.ToolEntry(testToolEntry); console.log("DEBUG", tool); assert.equal(tool.id, testToolEntry.id, "ToolEntry was not constructed with correct value for 'id'"); assert.equal(tool.type, testToolEntry.type, "ToolEntry was not constructed with correct value for 'type'"); assert.isUndefined(tool.name, "ToolEntry should not have a name"); }); tdd.test("ToolEntry - create from Bookmark", function() { var tool = new Toolbox.ToolEntry(testBookmark); console.log("DEBUG", tool); assert.equal(tool.id, testBookmark.id, "ToolEntry was not constructed with correct value for 'id'"); assert.equal(tool.type, testBookmark.type, "ToolEntry was not constructed with correct value for 'type'"); assert.isUndefined(tool.name, "ToolEntry should not have a name even though it was created from an Object that had a name"); }); tdd.test("Bookmark - create", function() { var tool = new Toolbox.Bookmark(testBookmark); assert.isUndefined(tool.id, "Tool was constructed with an 'id'"); assert.isUndefined(tool.type, "Tool was constructed with an 'type'"); assert.equal(tool.name, testBookmark.name, "Tool was not constructed with correct value for 'name'"); assert.equal(tool.url, testBookmark.url, "Tool was not constructed with correct value for 'url'"); assert.equal(tool.icon, testBookmark.icon, "Tool was not constructed with correct value for 'icon'"); }); tdd.test("Toolbox - construct", function() { var tb = new Toolbox(); assert.isTrue(tb instanceof Toolbox, "Unable to construct Toolbox"); }); tdd.test("Toolbox - get instance", function() { var tb = toolbox.getToolbox(); assert.isTrue(tb instanceof Toolbox, "Unable to get instance of Toolbox"); }); tdd.test("Toolbox - get instance is same instance", function() { var tbNew = new Toolbox(); var tbInst = toolbox.getToolbox(); assert.isFalse(tbInst === tbNew, "The 'singleton' instance of Toolbox should not match a 'new' instance of Toolbox"); assert.isTrue(tbInst === toolbox.getToolbox(), "The 'singleton' instance of Toolbox should match the previous return for the singleton"); }); tdd.test("toolbox.getToolEntries - returns Deferred", function() { assert.isTrue(toolbox.getToolbox().getToolEntries() instanceof Deferred, "Toolbox.getToolEntries should return a Deferred"); }); tdd.test("toolbox.getToolEntries - resolves with Array (no Tools)", function() { var dfd = this.async(1000); toolbox.getToolbox().getToolEntries().then(dfd.callback(function(tools) { assert.isTrue(tools instanceof Array, "Toolbox.getToolEntries should resolve with an Array"); }), function(err) { dfd.reject(err); }); server.respondWith("GET", "/ibm/api/adminCenter/v1/toolbox/toolEntries", [200, { "Content-Type": "application/json" },'{"toolEntries":[]}']); server.respond(); return dfd; }); tdd.test("toolbox.getToolEntries - resolves with Array of Tool objects", function() { var dfd = this.async(1000); toolbox.getToolbox().getToolEntries().then(dfd.callback(function(tools) { assert.isTrue(tools instanceof Array, "Toolbox.getToolEntries should resolve with an Array"); assert.equal(tools.length, 1, "Expected exactly 1 tool back from the mock response"); var tool = tools[0]; assert.equal(tool.id, testToolEntry.id, "Tool was not constructed with correct value for 'id'"); assert.equal(tool.type, testToolEntry.type, "Tool was not constructed with correct value for 'type'"); }), function(err) { dfd.reject(err); }); server.respondWith("GET", "/ibm/api/adminCenter/v1/toolbox/toolEntries", [200, { "Content-Type": "application/json" },'['+JSON.stringify(testToolEntry)+']']); server.respond(); return dfd; }); tdd.test("toolbox.getTool - returns Deferred", function() { assert.isTrue(toolbox.getToolbox().getTool('myTool') instanceof Deferred, "Toolbox.getTool should return a Deferred"); }); tdd.test("toolbox.getTool - returns a Tool", function() { var dfd = this.async(1000); toolbox.getToolbox().getTool('myTool').then(dfd.callback(function(tool) { assert.equal(tool.id, testBookmark.id, "Returned tool did not have correct value for 'id'"); assert.equal(tool.type, testBookmark.type, "Returned tool did not have correct value for 'type'"); assert.equal(tool.name, testBookmark.name, "Returned tool did not have correct value for 'name'"); assert.equal(tool.url, testBookmark.url, "Returned tool did not have correct value for 'url'"); assert.equal(tool.icon, testBookmark.icon, "Returned tool did not have correct value for 'icon'"); }), function(err) { dfd.reject(err); }); server.respondWith("GET", "/ibm/api/adminCenter/v1/toolbox/toolEntries/myTool", [200, { "Content-Type": "application/json" }, JSON.stringify(testBookmark)]); server.respond(); return dfd; }); tdd.test("Toolbox.getTool - filtered Tool", function() { var dfd = this.async(1000); toolbox.getToolbox().getTool('myTool', 'name,url').then(dfd.callback(function(tool) { assert.equal(tool.id, null, "Returned tool was filtered and should not have an 'id'"); assert.equal(tool.type, null, "Returned tool was filtered and should not have a 'type'"); assert.equal(tool.name, testBookmark.name, "Returned tool did not have correct value for 'name'"); assert.equal(tool.url, testBookmark.url, "Returned tool did not have correct value for 'url'"); assert.equal(tool.icon, null, "Returned tool was filtered and should not have an 'icon'"); }), function(err) { dfd.reject(err); }); server.respondWith("GET", "/ibm/api/adminCenter/v1/toolbox/toolEntries/myTool?fields=name,url", [200, { "Content-Type": "application/json" }, '{"name":"'+testBookmark.name+'","url":"'+testBookmark.url+'"}']); server.respond(); return dfd; }); tdd.test("Toolbox.getTool - no provided Tool ID", function() { try { toolbox.getToolbox().getTool(); assert.isTrue(false, "Toolbox.getTool should throw an error when no tool ID is provided"); } catch(err) { // Pass } }); tdd.test("Toolbox.addToolEntry - returns Deferred", function() { assert.isTrue(toolbox.getToolbox().addToolEntry(testBookmark) instanceof Deferred, "Toolbox.addToolEntry should return a Deferred"); }); tdd.test("Toolbox.addToolEntry - returns the created ToolEntry", function() { var dfd = this.async(1000); toolbox.getToolbox().addToolEntry(testBookmark).then(dfd.callback(function(tool) { assert.equal(tool.id, testBookmark.id, "Returned tool did not have correct value for 'id'"); assert.equal(tool.type, testBookmark.type, "Returned tool did not have correct value for 'type'"); assert.equal(tool.name, testBookmark.name, "Returned tool did not have correct value for 'name'"); assert.equal(tool.url, testBookmark.url, "Returned tool did not have correct value for 'url'"); assert.equal(tool.icon, testBookmark.icon, "Returned tool did not have correct value for 'icon'"); }), function(err) { dfd.reject(err); }); server.respondWith("POST", "/ibm/api/adminCenter/v1/toolbox/toolEntries", [201, { "Content-Type": "application/json" }, JSON.stringify(testBookmark)]); server.respond(); return dfd; }); tdd.test("Toolbox.addToolEntry - no provided ToolEntry props", function() { try { toolbox.getToolbox().addToolEntry(); assert.isTrue(false, "Toolbox.addToolEntry should throw an error when no tool ID is provided"); } catch(err) { // Pass } }); tdd.test("Toolbox.addBookmark - returns Deferred", function() { assert.isTrue(toolbox.getToolbox().addBookmark(testBookmark) instanceof Deferred, "Toolbox.addBookmark should return a Deferred"); }); tdd.test("Toolbox.addBookmark - returns the created Bookmark", function() { var dfd = this.async(1000); toolbox.getToolbox().addBookmark(testBookmark).then(dfd.callback(function(tool) { assert.equal(tool.id, testBookmark.id, "Returned tool did not have correct value for 'id'"); assert.equal(tool.type, testBookmark.type, "Returned tool did not have correct value for 'type'"); assert.equal(tool.name, testBookmark.name, "Returned tool did not have correct value for 'name'"); assert.equal(tool.url, testBookmark.url, "Returned tool did not have correct value for 'url'"); assert.equal(tool.icon, testBookmark.icon, "Returned tool did not have correct value for 'icon'"); }), function(err) { dfd.reject(err); }); server.respondWith("POST", "/ibm/api/adminCenter/v1/toolbox/bookmarks", [201, { "Content-Type": "application/json" }, JSON.stringify(testBookmark)]); server.respond(); return dfd; }); tdd.test("Toolbox.addBookmark - no provided Bookmark props", function() { try { toolbox.getToolbox().addBookmark(); assert.isTrue(false, "Toolbox.addBookmark should throw an error when no tool ID is provided"); } catch(err) { // Pass } }); tdd.test("Toolbox.deleteTool - returns Deferred", function() { assert.isTrue(toolbox.getToolbox().deleteTool('myTool') instanceof Deferred, "Toolbox.deleteTool should return a Deferred"); }); tdd.test("Toolbox.deleteTool - returns the deleted entry's JSON", function() { var dfd = this.async(1000); toolbox.getToolbox().deleteTool(testBookmark.id).then(dfd.callback(function(tool) { assert.equal(tool.id, testBookmark.id, "Returned tool did not have correct value for 'id'"); assert.equal(tool.type, testBookmark.type, "Returned tool did not have correct value for 'type'"); assert.equal(tool.name, testBookmark.name, "Returned tool did not have correct value for 'name'"); assert.equal(tool.url, testBookmark.url, "Returned tool did not have correct value for 'url'"); assert.equal(tool.icon, testBookmark.icon, "Returned tool did not have correct value for 'icon'"); }), function(err) { dfd.reject(err); }); server.respondWith("DELETE", "/ibm/api/adminCenter/v1/toolbox/toolEntries/myTool", [200, { "Content-Type": "application/json" }, JSON.stringify(testBookmark)]); server.respond(); return dfd; }); tdd.test("Toolbox.deleteTool - no provided Tool ID", function() { try { toolbox.getToolbox().deleteTool(); assert.isTrue(false, "Toolbox.deleteTool should throw an error when no tool ID is provided"); } catch(err) { // Pass } }); }); } });
OpenLiberty/open-liberty
dev/com.ibm.ws.ui/resources/WEB-CONTENT/unittest/toolbox/toolboxTests.js
JavaScript
epl-1.0
14,570
/******************************************************************************* * Copyright (c) 2017, 2021 Red Hat Inc and others * * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 * which is available at https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Red Hat Inc - initial API and implementation *******************************************************************************/ package org.eclipse.kapua.kura.simulator; import java.util.LinkedList; import java.util.List; import java.util.Set; import org.eclipse.kapua.kura.simulator.app.Application; import org.eclipse.kapua.kura.simulator.app.ApplicationController; import org.eclipse.kapua.kura.simulator.birth.BirthCertificateModule; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A default Kura simulator */ public class Simulator implements AutoCloseable { private static final Logger logger = LoggerFactory.getLogger(Simulator.class); protected final Transport transport; protected List<Module> modules = new LinkedList<>(); public Simulator(final GatewayConfiguration configuration, final Transport transport, final Set<Application> applications) { this.transport = transport; // set up callbacks this.transport.whenConnected(this::connected); this.transport.whenDisconnected(this::disconnected); // set up application controller final ApplicationController applicationController = new ApplicationController(transport, applications); modules.add(applicationController); // set up builder modules.add(new BirthCertificateModule(configuration, applicationController::getApplicationIds)); // finally connect this.transport.connect(); } @Override public void close() { // we don't close the transport here } protected void connected() { logger.info("Connected ... sending birth certificate ..."); for (final Module module : modules) { try { module.connected(transport); } catch (final Exception e) { logger.warn("Failed to call module: {}", module, e); } } } protected void disconnected() { for (final Module module : modules) { try { module.disconnected(transport); } catch (final Exception e) { logger.warn("Failed to call module: {}", module, e); } } } }
stzilli/kapua
simulator-kura/src/main/java/org/eclipse/kapua/kura/simulator/Simulator.java
Java
epl-1.0
2,615
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateModuleSectionTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('module_section', function (Blueprint $table) { $table->increments('id'); $table->string('name')->unique(); $table->string('description')->nullable(); $table->integer('module_id')->unsigned(); }); Schema::table('module_section', function($table) { $table->foreign('module_id') ->references('id')->on('module') ->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('module_section'); } }
ImbalanceGaming/imbalance-gaming-laravel
database/migrations/2016_03_14_011932_create_module_section_table.php
PHP
gpl-2.0
887
using System.ComponentModel; using System.ComponentModel.Design; using System.Drawing.Design; using Microsoft.VisualStudio.Shell; using NLog; using System; using System.Linq.Expressions; namespace CHeaderGenerator { public class CSourceFileOptions : DialogPage, INotifyPropertyChanged { private bool showIncludeGuard = true; private string headerComment = @"/* Header file generated by C Header Generator. Executed by {Name} on {Date}. */"; private bool includeStaticFunctions = false; private bool includeExternFunctions = false; private string logLayout = "[${longdate}] ${level}: ${logger} - ${message}"; private LogLevel logLevel = LogLevel.Info; private bool autoSaveFiles = true; public event PropertyChangedEventHandler PropertyChanged; [Description("Generate an include guard to surround the file")] [DisplayName("Show Include Guard")] [Category("General")] public bool ShowIncludeGuard { get { return this.showIncludeGuard; } set { if (this.showIncludeGuard != value) { this.showIncludeGuard = value; this.OnPropertyChanged(() => this.ShowIncludeGuard); } } } [Description("The format of the header comment to display at the beginning of the header file")] [DisplayName("Header Comment")] [Category("General")] [Editor(typeof(MultilineStringEditor), typeof(UITypeEditor))] public string HeaderComment { get { return this.headerComment; } set { if (this.headerComment != value) { this.headerComment = value; this.OnPropertyChanged(() => this.HeaderComment); } } } [Description("Include static declarations in header file")] [DisplayName("Include Static Declarations")] [Category("General")] public bool IncludeStaticFunctions { get { return this.includeStaticFunctions; } set { if (this.includeStaticFunctions != value) { this.includeStaticFunctions = value; this.OnPropertyChanged(() => this.IncludeStaticFunctions); } } } [Description("Include extern declarations in header file")] [DisplayName("Include Extern Declarations")] [Category("General")] public bool IncludeExternFunctions { get { return this.includeExternFunctions; } set { if (this.includeExternFunctions != value) { this.includeExternFunctions = value; this.OnPropertyChanged(() => this.IncludeExternFunctions); } } } [Description("Layout for log messages to the output window")] [DisplayName("Log Message Layout")] [Category("Logging")] public string LogLayout { get { return this.logLayout; } set { if (this.logLayout != value) { this.logLayout = value; this.OnPropertyChanged(() => this.LogLayout); } } } [Description("Minimum level for log messages")] [DisplayName("Log Level")] [Category("Logging")] public LogLevel LogLevel { get { return this.logLevel; } set { if (this.logLevel != value) { this.logLevel = value; this.OnPropertyChanged(() => this.LogLevel); } } } [Description("Automatically save files that have been modified when generating header files")] [DisplayName("Automatically Save Files")] [Category("General")] public bool AutoSaveFiles { get { return this.autoSaveFiles; } set { if (this.autoSaveFiles != value) { this.autoSaveFiles = value; this.OnPropertyChanged(() => this.AutoSaveFiles); } } } protected virtual void OnPropertyChanged<T>(Expression<Func<T>> propFunc) { var body = propFunc.Body as MemberExpression; if (body != null) this.OnPropertyChanged(body.Member.Name); } protected virtual void OnPropertyChanged(string propertyName) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } }
cmc13/CHeaderGenerator
CHeaderGenerator/CSourceFileOptions.cs
C#
gpl-2.0
4,992
<?php /** * 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; under version 2 * of the License (non-upgradable). * * 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 Street, Fifth Floor, Boston, MA 02110-1301, USA. * * Copyright (c) 2013 (original work) Open Assessment Technologies SA (under the project TAO-PRODUCT); * * @author Jérôme Bogaerts, <jerome@taotesting.com> * @license GPLv2 * @package */ namespace qtism\data\expressions; /** * From IMS QTI: * * null is a simple expression that returns the NULL value - the null value is * treated as if it is of any desired baseType. * * @author Jérôme Bogaerts <jerome@taotesting.com> * */ class NullValue extends Expression { public function getQtiClassName() { return 'null'; } }
dhx/tao-comp
vendor/qtism/qtism/qtism/data/expressions/NullValue.php
PHP
gpl-2.0
1,260
/* * Copyright (C) 2010-2012 Project SkyFire <http://www.projectskyfire.org/> * Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2005-2011 MaNGOS <http://getmangos.com/> * * 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, see <http://www.gnu.org/licenses/>. */ /* Script Data Start SFName: Boss epoch SFAuthor: Tartalo SF%Complete: 80 SFComment: TODO: Intro, consecutive attacks to a random target durin time wrap, adjust timers SFCategory: Script Data End */ #include "ScriptPCH.h" #include "culling_of_stratholme.h" enum Spells { SPELL_CURSE_OF_EXERTION = 52772, SPELL_TIME_WARP = 52766, //Time slows down, reducing attack, casting and movement speed by 70% for 6 sec. SPELL_TIME_STOP = 58848, //Stops time in a 50 yard sphere for 2 sec. SPELL_WOUNDING_STRIKE = 52771, //Used only on the tank H_SPELL_WOUNDING_STRIKE = 58830 }; enum Yells { SAY_INTRO = -1595000, //"Prince Arthas Menethil, on this day, a powerful darkness has taken hold of your soul. The death you are destined to visit upon others will this day be your own." SAY_AGGRO = -1595001, //"We'll see about that, young prince." SAY_TIME_WARP_1 = -1595002, //"Tick tock, tick tock..." SAY_TIME_WARP_2 = -1595003, //"Not quick enough!" SAY_TIME_WARP_3 = -1595004, //"Let's get this over with. " SAY_SLAY_1 = -1595005, //"There is no future for you." SAY_SLAY_2 = -1595006, //"This is the hour of our greatest triumph!" SAY_SLAY_3 = -1595007, //"You were destined to fail. " SAY_DEATH = -1595008 //"*gurgles*" }; class boss_epoch : public CreatureScript { public: boss_epoch() : CreatureScript("boss_epoch") { } CreatureAI* GetAI(Creature* creature) const { return new boss_epochAI (creature); } struct boss_epochAI : public ScriptedAI { boss_epochAI(Creature* creature) : ScriptedAI(creature) { instance = creature->GetInstanceScript(); } uint8 Step; uint32 StepTimer; uint32 WoundingStrikeTimer; uint32 TimeWarpTimer; uint32 TimeStopTimer; uint32 CurseOfExertionTimer; InstanceScript* instance; void Reset() { Step = 1; StepTimer = 26000; CurseOfExertionTimer = 9300; TimeWarpTimer = 25300; TimeStopTimer = 21300; WoundingStrikeTimer = 5300; if (instance) instance->SetData(DATA_EPOCH_EVENT, NOT_STARTED); } void EnterCombat(Unit* /*who*/) { DoScriptText(SAY_AGGRO, me); if (instance) instance->SetData(DATA_EPOCH_EVENT, IN_PROGRESS); } void UpdateAI(const uint32 diff) { //Return since we have no target if (!UpdateVictim()) return; if (CurseOfExertionTimer < diff) { if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true)) DoCast(target, SPELL_CURSE_OF_EXERTION); CurseOfExertionTimer = 9300; } else CurseOfExertionTimer -= diff; if (WoundingStrikeTimer < diff) { DoCastVictim(SPELL_WOUNDING_STRIKE); WoundingStrikeTimer = 5300; } else WoundingStrikeTimer -= diff; if (TimeStopTimer < diff) { DoCastAOE(SPELL_TIME_STOP); TimeStopTimer = 21300; } else TimeStopTimer -= diff; if (TimeWarpTimer < diff) { DoScriptText(RAND(SAY_TIME_WARP_1, SAY_TIME_WARP_2, SAY_TIME_WARP_3), me); DoCastAOE(SPELL_TIME_WARP); TimeWarpTimer = 25300; } else TimeWarpTimer -= diff; DoMeleeAttackIfReady(); } void JustDied(Unit* /*killer*/) { DoScriptText(SAY_DEATH, me); if (instance) instance->SetData(DATA_EPOCH_EVENT, DONE); } void KilledUnit(Unit* victim) { if (victim == me) return; DoScriptText(RAND(SAY_SLAY_1, SAY_SLAY_2, SAY_SLAY_3), me); } }; }; void AddSC_boss_epoch() { new boss_epoch(); }
SkyFireArchives/SkyFireEMU_433
src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/boss_epoch.cpp
C++
gpl-2.0
5,315
<?php namespace Google\AdsApi\AdWords\v201702\mcm; /** * This file was generated from WSDL. DO NOT EDIT. */ class CurrencyCodeErrorReason { const UNSUPPORTED_CURRENCY_CODE = 'UNSUPPORTED_CURRENCY_CODE'; }
renshuki/dfp-manager
vendor/googleads/googleads-php-lib/src/Google/AdsApi/AdWords/v201702/mcm/CurrencyCodeErrorReason.php
PHP
gpl-2.0
216
<?php include_partial('stats_header', array('form' => $form, 'title' => $title)); ?> <?php if ( $sf_user->hasCredential('stats-control') ): ?> <?php include_partial('global/chart_jqplot', array( 'id' => 'control', 'data' => url_for('statistics/controlJson?type=' . $type), 'width' => '1000', 'label' => __('Ticket controls') )) ?> <?php endif ?> </div> <?php use_javascript('/js/jqplot/plugins/jqplot.barRenderer.js') ?> <?php use_javascript('/js/jqplot/plugins/jqplot.cursor.js') ?> <?php use_javascript('/js/jqplot/plugins/jqplot.canvasAxisTickRenderer.js') ?> <?php use_javascript('/js/jqplot/plugins/jqplot.canvasTextRenderer.js') ?> <?php use_javascript('statistics-jqplot') ?> <?php use_javascript('statistics-control') ?>
Fabrice-li/e-venement
apps/statistics/modules/statistics/templates/controlSuccess.php
PHP
gpl-2.0
785
<?php namespace Drupal\jsonapi\Normalizer\Value; /** * Helps normalize config entity "fields" in compliance with the JSON API spec. * * @internal */ class ConfigFieldItemNormalizerValue extends FieldItemNormalizerValue { /** * {@inheritdoc} * * @var mixed */ protected $raw; /** * Instantiate a ConfigFieldItemNormalizerValue object. * * @param mixed $values * The normalized result. */ public function __construct($values) { $this->raw = $values; } /** * {@inheritdoc} */ public function rasterizeValue() { return $this->rasterizeValueRecursive($this->raw); } }
enslyon/ensl
modules/jsonapi/src/Normalizer/Value/ConfigFieldItemNormalizerValue.php
PHP
gpl-2.0
632
package org.telegram.messenger; import android.text.TextUtils; import android.util.LongSparseArray; import android.util.SparseBooleanArray; import org.telegram.tgnet.TLRPC; import java.util.ArrayList; public class ForwardingMessagesParams { public LongSparseArray<MessageObject.GroupedMessages> groupedMessagesMap = new LongSparseArray<>(); public ArrayList<MessageObject> messages; public ArrayList<MessageObject> previewMessages = new ArrayList<>(); public SparseBooleanArray selectedIds = new SparseBooleanArray(); public boolean hideForwardSendersName; public boolean hideCaption; public boolean hasCaption; public boolean hasSenders; public boolean isSecret; public boolean willSeeSenders; public boolean multiplyUsers; public boolean hasSpoilers; public ArrayList<TLRPC.TL_pollAnswerVoters> pollChoosenAnswers = new ArrayList<>(); public ForwardingMessagesParams(ArrayList<MessageObject> messages, long newDialogId) { this.messages = messages; hasCaption = false; hasSenders = false; isSecret = DialogObject.isEncryptedDialog(newDialogId); hasSpoilers = false; ArrayList<String> hiddenSendersName = new ArrayList<>(); for (int i = 0; i < messages.size(); i++) { MessageObject messageObject = messages.get(i); if (!TextUtils.isEmpty(messageObject.caption)) { hasCaption = true; } selectedIds.put(messageObject.getId(), true); TLRPC.Message message = new TLRPC.TL_message(); message.id = messageObject.messageOwner.id; message.grouped_id = messageObject.messageOwner.grouped_id; message.peer_id = messageObject.messageOwner.peer_id; message.from_id = messageObject.messageOwner.from_id; message.message = messageObject.messageOwner.message; message.media = messageObject.messageOwner.media; message.action = messageObject.messageOwner.action; message.edit_date = 0; if (messageObject.messageOwner.entities != null) { message.entities.addAll(messageObject.messageOwner.entities); if (!hasSpoilers) { for (TLRPC.MessageEntity e : message.entities) { if (e instanceof TLRPC.TL_messageEntitySpoiler) { hasSpoilers = true; break; } } } } message.out = true; message.unread = false; message.via_bot_id = messageObject.messageOwner.via_bot_id; message.reply_markup = messageObject.messageOwner.reply_markup; message.post = messageObject.messageOwner.post; message.legacy = messageObject.messageOwner.legacy; message.restriction_reason = messageObject.messageOwner.restriction_reason; TLRPC.MessageFwdHeader header = null; long clientUserId = UserConfig.getInstance(messageObject.currentAccount).clientUserId; if (!isSecret) { if (messageObject.messageOwner.fwd_from != null) { header = messageObject.messageOwner.fwd_from; if (!messageObject.isDice()) { hasSenders = true; } else { willSeeSenders = true; } if (header.from_id == null && !hiddenSendersName.contains(header.from_name)) { hiddenSendersName.add(header.from_name); } } else if (messageObject.messageOwner.from_id.user_id == 0 || messageObject.messageOwner.dialog_id != clientUserId || messageObject.messageOwner.from_id.user_id != clientUserId) { header = new TLRPC.TL_messageFwdHeader(); header.from_id = messageObject.messageOwner.from_id; if (!messageObject.isDice()) { hasSenders = true; } else { willSeeSenders = true; } } } if (header != null) { message.fwd_from = header; message.flags |= TLRPC.MESSAGE_FLAG_FWD; } message.dialog_id = newDialogId; MessageObject previewMessage = new MessageObject(messageObject.currentAccount, message, true, false) { @Override public boolean needDrawForwarded() { if (hideForwardSendersName) { return false; } return super.needDrawForwarded(); } }; previewMessage.preview = true; if (previewMessage.getGroupId() != 0) { MessageObject.GroupedMessages groupedMessages = groupedMessagesMap.get(previewMessage.getGroupId(), null); if (groupedMessages == null) { groupedMessages = new MessageObject.GroupedMessages(); groupedMessagesMap.put(previewMessage.getGroupId(), groupedMessages); } groupedMessages.messages.add(previewMessage); } previewMessages.add(0, previewMessage); if (messageObject.isPoll()) { TLRPC.TL_messageMediaPoll mediaPoll = (TLRPC.TL_messageMediaPoll) messageObject.messageOwner.media; PreviewMediaPoll newMediaPoll = new PreviewMediaPoll(); newMediaPoll.poll = mediaPoll.poll; newMediaPoll.provider = mediaPoll.provider; newMediaPoll.results = new TLRPC.TL_pollResults(); newMediaPoll.totalVotersCached = newMediaPoll.results.total_voters = mediaPoll.results.total_voters; previewMessage.messageOwner.media = newMediaPoll; if (messageObject.canUnvote()) { for (int a = 0, N = mediaPoll.results.results.size(); a < N; a++) { TLRPC.TL_pollAnswerVoters answer = mediaPoll.results.results.get(a); if (answer.chosen) { TLRPC.TL_pollAnswerVoters newAnswer = new TLRPC.TL_pollAnswerVoters(); newAnswer.chosen = answer.chosen; newAnswer.correct = answer.correct; newAnswer.flags = answer.flags; newAnswer.option = answer.option; newAnswer.voters = answer.voters; pollChoosenAnswers.add(newAnswer); newMediaPoll.results.results.add(newAnswer); } else { newMediaPoll.results.results.add(answer); } } } } } ArrayList<Long> uids = new ArrayList<>(); for (int a = 0; a < messages.size(); a++) { MessageObject object = messages.get(a); long uid; if (object.isFromUser()) { uid = object.messageOwner.from_id.user_id; } else { TLRPC.Chat chat = MessagesController.getInstance(object.currentAccount).getChat(object.messageOwner.peer_id.channel_id); if (ChatObject.isChannel(chat) && chat.megagroup && object.isForwardedChannelPost()) { uid = -object.messageOwner.fwd_from.from_id.channel_id; } else { uid = -object.messageOwner.peer_id.channel_id; } } if (!uids.contains(uid)) { uids.add(uid); } } if (uids.size() + hiddenSendersName.size() > 1) { multiplyUsers = true; } for (int i = 0; i < groupedMessagesMap.size(); i++) { groupedMessagesMap.valueAt(i).calculate(); } } public void getSelectedMessages(ArrayList<MessageObject> messagesToForward) { messagesToForward.clear(); for (int i = 0; i < messages.size(); i++) { MessageObject messageObject = messages.get(i); int id = messageObject.getId(); if (selectedIds.get(id, false)) { messagesToForward.add(messageObject); } } } public class PreviewMediaPoll extends TLRPC.TL_messageMediaPoll { public int totalVotersCached; } }
Telegram-FOSS-Team/Telegram-FOSS
TMessagesProj/src/main/java/org/telegram/messenger/ForwardingMessagesParams.java
Java
gpl-2.0
8,580
/************************************************************** TigrStringMap.H bmajoros@tigr.org 1/1/2003 TIGR++ : C++ class template library for bioinformatics Copyright (c) 2003, The Institute for Genomic Research (TIGR), Rockville, Maryland, U.S.A. All rights reserved. ***************************************************************/ #ifndef INCL_TigrStringMap_H #define INCL_TigrStringMap_H #include <list> #include "TigrString.H" using namespace std; /***************************************************************** Some primes to use for table sizes: tens: 13 19 23 31 41 53 61 71 83 89 hundreds: 101 199 293 401 499 601 701 797 887 thousands: 997 1097 1201 1301 1399 1499 1601 1699 1801 1901 1999 2099 2179 2297 2399 2477 2593 2699 2801 2897 3001 3089 3191 3301 3391 3499 3593 3701 3797 3889 4001 4099 4201 4297 4397 4493 4597 4691 4801 4889 4999 5101 5197 5297 5399 5501 5591 5701 5801 5897 5987 6101 6199 6301 6397 6491 6599 6701 6793 6899 7001 7079 7193 7297 7393 7499 7591 7699 7793 7901 7993 8101 8191 8297 8389 8501 8599 8699 8783 8893 9001 9091 9199 9293 9397 9497 9601 9697 9791 9901 ten-thousands: 9973 10993 11987 12983 13999 14983 15991 16993 17989 18979 19997 20983 21997 22993 23993 24989 25999 26993 27997 28979 29989 30983 31991 32999 33997 34981 35999 36997 37997 38993 39989 40993 41999 42989 43997 44987 45989 46997 47981 48991 49999 50993 51991 52999 53993 54983 55997 56999 57991 58997 59999 60961 61991 62989 63997 64997 65993 66977 67993 68993 69997 70999 71999 72997 73999 74959 75997 76991 77999 78989 79999 80989 81973 82997 83987 84991 85999 86993 87991 88997 89989 90997 91997 92993 93997 94999 95989 96997 97987 98999 hundred-thousands: 99961 199999 299993 399989 499979 599999 700001 799999 900001 millions: 999959 1999957 *****************************************************************/ /***************************************************************** */ template<class T> struct StringMapElem { int len; char *first; T second; StringMapElem(const char *,int len,const T &); StringMapElem(const char *,int len); StringMapElem(const StringMapElem<T> &); virtual ~StringMapElem(); }; /***************************************************************** */ template<class T> class StringMapIterator { public: typedef list<StringMapElem<T>*> Bucket; typedef StringMapElem<T> ElemType; StringMapIterator(int index,int tableSize,Bucket *array); inline bool operator!=(const StringMapIterator<T> &); bool operator==(const StringMapIterator<T> &); StringMapIterator<T> &operator++(int); StringMapIterator<T> &operator++(); StringMapElem<T> &operator*(); private: int index, tableSize; typename Bucket::iterator cur, end; Bucket *array; void findNonemptyBucket(); }; /***************************************************************** */ template<class T> class TigrStringMap { public: typedef StringMapElem<T> ElemType; typedef StringMapIterator<T> iterator; typedef StringMapIterator<T> const_iterator; TigrStringMap(int tableSize); TigrStringMap(const TigrStringMap<T> &); virtual ~TigrStringMap(); T &lookup(const char *,int index,int len); T &lookup(const char *,int len); bool isDefined(const char *,int index,int len); bool isDefined(const char *,int len); int size(); iterator begin(); iterator end(); iterator begin() const; iterator end() const; void clear(); void remove(const char *,int index,int len); void remove(const char *,int len); TigrStringMap<T> &operator=(const TigrStringMap &); private: typedef list<StringMapElem<T>*> Bucket; int tableSize, numElements; Bucket *array; unsigned hash(const char *,int len,int tableSize); }; /***************************************************************** */ template<class T> StringMapElem<T>::StringMapElem(const StringMapElem<T> &other) : len(other.len), second(other.second) { first=new char[len+1]; memcpy(first,other.first,len+1); } template<class T> StringMapElem<T>::StringMapElem(const char *p,int len) : len(len) { first=new char[len+1]; first[len]='\0'; strncpy(first,p,len); } template<class T> StringMapElem<T>::StringMapElem(const char *p,int len,const T &t) : second(t), len(len) { first=new char[len+1]; first[len]='\0'; strncpy(first,p,len); } template<class T> StringMapElem<T>::~StringMapElem() { delete [] first; } template<class T> StringMapElem<T> &StringMapIterator<T>::operator*() { return **cur; } template<class T> StringMapIterator<T> &StringMapIterator<T>::operator++() { if(index<tableSize) { ++cur; if(cur==end) { ++index; findNonemptyBucket(); } } return *this; } template<class T> StringMapIterator<T> &StringMapIterator<T>::operator++(int) { if(index<tableSize) { ++cur; if(cur==end) { ++index; findNonemptyBucket(); } } return *this; } template<class T> StringMapIterator<T>::StringMapIterator(int index,int tableSize,Bucket *array) : array(array), tableSize(tableSize), index(index) { findNonemptyBucket(); } template<class T> bool StringMapIterator<T>::operator!=(const StringMapIterator<T> &i) { return !(*this==i); } template<class T> bool StringMapIterator<T>::operator==(const StringMapIterator<T> &other) { if(other.index!=index) return false; if(index>=tableSize) return true; return cur==other.cur; } template<class T> void StringMapIterator<T>::findNonemptyBucket() { for(; index<tableSize ; ++index) { Bucket &bucket=array[index]; if(!bucket.empty()) { cur=bucket.begin(); end=bucket.end(); return; } } } template<class T> T &TigrStringMap<T>::lookup(const char *p,int len) { return lookup(p,0,len); } template<class T> T &TigrStringMap<T>::lookup(const char *pOrigin,int index,int len) { const char *p=pOrigin+index; unsigned hashValue=hash(p,len,tableSize); Bucket &bucket=array[hashValue]; typename Bucket::iterator end=bucket.end(); typename Bucket::iterator cur=bucket.begin(); for(; cur!=end ; ++cur) { StringMapElem<T> *elem=*cur; if(len!=elem->len) continue; if(!strncmp(p,elem->first,len)) return elem->second; } StringMapElem<T> *newElem=new StringMapElem<T>(p,len); bucket.push_back(newElem); ++numElements; return newElem->second; } template<class T> TigrStringMap<T>::TigrStringMap(const TigrStringMap<T> &other) : tableSize(other.tableSize), numElements(other.numElements), array(new Bucket[other.tableSize]) { for(int i=0 ; i<tableSize ; ++i) { Bucket &thisBucket=array[i], &thatBucket=other.array[i]; typename Bucket::iterator cur=thatBucket.begin(), end=thatBucket.end(); for(; cur!=end ; ++cur) thisBucket.push_back(new StringMapElem<T>(**cur)); } } template<class T> TigrStringMap<T> &TigrStringMap<T>::operator=(const TigrStringMap &other) { tableSize=other.tableSize; numElements=other.numElements; array=new Bucket[other.tableSize]; for(int i=0 ; i<tableSize ; ++i) { Bucket &thisBucket=array[i]; const Bucket &thatBucket=other.array[i]; typename Bucket::const_iterator cur=thatBucket.begin(), end=thatBucket.end(); for(; cur!=end ; ++cur) thisBucket.push_back(new StringMapElem<T>(**cur)); } return *this; } template<class T> TigrStringMap<T>::TigrStringMap(int tableSize) : tableSize(tableSize), numElements(0) { array=new Bucket[tableSize]; } template<class T> typename TigrStringMap<T>::iterator TigrStringMap<T>::begin() { return iterator(0,tableSize,array); } template<class T> typename TigrStringMap<T>::iterator TigrStringMap<T>::end() { return iterator(tableSize,tableSize,array); } template<class T> typename TigrStringMap<T>::iterator TigrStringMap<T>::begin() const { return iterator(0,tableSize,const_cast<Bucket*>(array)); } template<class T> typename TigrStringMap<T>::iterator TigrStringMap<T>::end() const { return iterator(tableSize,tableSize,const_cast<Bucket*>(array)); } template<class T> TigrStringMap<T>::~TigrStringMap() { //cout<<"~TigrStringMap"<<endl; for(int i=0 ; i<tableSize ; ++i) { Bucket &bucket=array[i]; typename Bucket::iterator cur=bucket.begin(), end=bucket.end(); for(; cur!=end ; ++cur) delete *cur; } delete [] array; } template<class T> bool TigrStringMap<T>::isDefined(const char *p,int len) { return isDefined(p,0,len); } template<class T> bool TigrStringMap<T>::isDefined(const char *pOrigin,int index,int len) { const char *p=pOrigin+index; unsigned hashValue=hash(p,len,tableSize); Bucket &bucket=array[hashValue]; typename Bucket::iterator cur=bucket.begin(), end=bucket.end(); for(; cur!=end ; ++cur) { StringMapElem<T> *elem=*cur; if(len!=elem->len) continue; if(!strncmp(p,elem->first,len)) return true; } return false; } template<class T> int TigrStringMap<T>::size() { return numElements; } template<class T> unsigned TigrStringMap<T>::hash(const char *s,int length,int tableSize) { int h=0; const char *p=s, *end=s+length; for(; p!=end ; ++p) { h=(h<<4)+*p; int g=h & 0xf000; if(g) h=h^(g>>8); } return labs(h) % tableSize; } template<class T> void TigrStringMap<T>::clear() { for(int i=0 ; i<tableSize ; ++i) { Bucket &bucket=array[i]; typename Bucket::iterator cur=bucket.begin(), end=bucket.end(); for(; cur!=end ; ++cur) delete *cur; bucket.clear(); } numElements=0; } template<class T> void TigrStringMap<T>::remove(const char *p,int len) { remove(p,0,len); } template<class T> void TigrStringMap<T>::remove(const char *pOrigin,int index,int len) { const char *p=pOrigin+index; unsigned hashValue=hash(p,len,tableSize); Bucket &bucket=array[hashValue]; typename Bucket::iterator cur=bucket.begin(), end=bucket.end(); for(; cur!=end ; ++cur) { StringMapElem<T> *elem=*cur; if(len!=elem->len) continue; if(!strncmp(p,elem->first,len)) { bucket.erase(cur); break; } } --numElements; } #endif
bmajoros/UnVeil
tigr++/TigrStringMap.H
C++
gpl-2.0
10,179
<?php /* * Copyright 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ class Google_Service_Safebrowsing_GoogleSecuritySafebrowsingV4FindFullHashesRequest extends Google_Collection { protected $collection_key = 'clientStates'; protected $apiClientType = 'Google_Service_Safebrowsing_GoogleSecuritySafebrowsingV4ClientInfo'; protected $apiClientDataType = ''; protected $clientType = 'Google_Service_Safebrowsing_GoogleSecuritySafebrowsingV4ClientInfo'; protected $clientDataType = ''; public $clientStates; protected $threatInfoType = 'Google_Service_Safebrowsing_GoogleSecuritySafebrowsingV4ThreatInfo'; protected $threatInfoDataType = ''; /** * @param Google_Service_Safebrowsing_GoogleSecuritySafebrowsingV4ClientInfo */ public function setApiClient(Google_Service_Safebrowsing_GoogleSecuritySafebrowsingV4ClientInfo $apiClient) { $this->apiClient = $apiClient; } /** * @return Google_Service_Safebrowsing_GoogleSecuritySafebrowsingV4ClientInfo */ public function getApiClient() { return $this->apiClient; } /** * @param Google_Service_Safebrowsing_GoogleSecuritySafebrowsingV4ClientInfo */ public function setClient(Google_Service_Safebrowsing_GoogleSecuritySafebrowsingV4ClientInfo $client) { $this->client = $client; } /** * @return Google_Service_Safebrowsing_GoogleSecuritySafebrowsingV4ClientInfo */ public function getClient() { return $this->client; } public function setClientStates($clientStates) { $this->clientStates = $clientStates; } public function getClientStates() { return $this->clientStates; } /** * @param Google_Service_Safebrowsing_GoogleSecuritySafebrowsingV4ThreatInfo */ public function setThreatInfo(Google_Service_Safebrowsing_GoogleSecuritySafebrowsingV4ThreatInfo $threatInfo) { $this->threatInfo = $threatInfo; } /** * @return Google_Service_Safebrowsing_GoogleSecuritySafebrowsingV4ThreatInfo */ public function getThreatInfo() { return $this->threatInfo; } }
palasthotel/grid-wordpress-box-social
vendor/google/apiclient-services/src/Google/Service/Safebrowsing/GoogleSecuritySafebrowsingV4FindFullHashesRequest.php
PHP
gpl-2.0
2,567
# -*- coding: utf-8 -*- # # This file is part of Zenodo. # Copyright (C) 2016 CERN. # # Zenodo 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. # # Zenodo 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 Zenodo; if not, write to the # Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307, USA. # # In applying this license, CERN does not # waive the privileges and immunities granted to it by virtue of its status # as an Intergovernmental Organization or submit itself to any jurisdiction. """Zenodo Marcxml mapping test.""" from __future__ import absolute_import, print_function from datetime import datetime from invenio_pidstore.models import PersistentIdentifier from invenio_records import Record from zenodo.modules.records.serializers import marcxml_v1 def test_full_record(app, db, full_record): """Test MARC21 serialization of full record.""" # Add embargo date and OAI-PMH set information. full_record['embargo_date'] = '0900-12-31' full_record['_oai'] = { "id": "oai:zenodo.org:1", "sets": ["user-zenodo", "user-ecfunded"] } # Create record and PID. record = Record.create(full_record) pid = PersistentIdentifier.create( pid_type='recid', pid_value='12345', object_type='rec', object_uuid=record.id, ) assert record.validate() is None expected = { u'control_number': u'12345', u'date_and_time_of_latest_transaction': ( record.model.updated.strftime("%Y%m%d%H%M%S.0")), u'resource_type': { u'subtype': u'book', u'type': u'publication' }, u'title_statement': { u'title': u'Test title' }, u'publication_distribution_imprint': [ {u'date_of_publication_distribution': u'2014-02-27'}, ], u'main_entry_personal_name': { u'affiliation': u'CERN', u'personal_name': u'Doe, John', u'authority_record_control_number_or_standard_number': [ u'(gnd)170118215', u'(orcid)0000-0002-1694-233X' ] }, u'added_entry_personal_name': [ { u'affiliation': u'CERN', u'personal_name': u'Doe, Jane', u'authority_record_control_number_or_standard_number': [ u'(orcid)0000-0002-1825-0097' ] }, { u'affiliation': u'CERN', u'personal_name': u'Smith, John', }, { u'affiliation': u'CERN', u'personal_name': u'Nowak, Jack', u'authority_record_control_number_or_standard_number': [ u'(gnd)170118215' ] }, { u'affiliation': u'CERN', u'relator_code': [u'oth'], u'personal_name': u'Smith, Other', u'authority_record_control_number_or_standard_number': [ u'(orcid)0000-0002-1825-0097' ] }, { u'personal_name': u'Hansen, Viggo', u'relator_code': [u'oth'], }, { u'affiliation': u'CERN', u'relator_code': [u'dtm'], u'personal_name': u'Kowalski, Manager' }, { u'relator_code': [u'ths'], u'personal_name': u'Smith, Professor' }, ], u'summary': { u'summary': u'Test Description' }, u'index_term_uncontrolled': [ {u'uncontrolled_term': u'kw1'}, {u'uncontrolled_term': u'kw2'}, {u'uncontrolled_term': u'kw3'}, ], u'subject_added_entry_topical_term': [ { u'topical_term_or_geographic_name_entry_element': u'cc-by', u'source_of_heading_or_term': u'opendefinition.org', u'level_of_subject': u'Primary', u'thesaurus': u'Source specified in subfield $2', }, { u'topical_term_or_geographic_name_entry_element': u'Astronomy', u'authority_record_control_number_or_standard_number': ( u'(url)http://id.loc.gov/authorities/subjects/sh85009003'), u'level_of_subject': u'Primary', }, ], u'general_note': { u'general_note': u'notes' }, u'information_relating_to_copyright_status': { u'copyright_status': u'open' }, u'terms_governing_use_and_reproduction_note': { u'uniform_resource_identifier': u'https://creativecommons.org/licenses/by/4.0/', u'terms_governing_use_and_reproduction': u'Creative Commons Attribution 4.0' }, u'communities': [ u'zenodo', ], u'funding_information_note': [ {u'grant_number': u'1234', u'text_of_note': u'Grant Title'}, {u'grant_number': u'4321', u'text_of_note': u'Title Grant'} ], u'host_item_entry': [ { u'main_entry_heading': u'10.1234/foo.bar', u'note': u'doi', u'relationship_information': u'cites', }, { 'main_entry_heading': u'1234.4325', 'note': u'arxiv', 'relationship_information': u'isIdenticalTo' }, { u'main_entry_heading': u'1234.4321', u'note': u'arxiv', u'relationship_information': u'cites', }, { 'main_entry_heading': u'1234.4328', 'note': u'arxiv', 'relationship_information': u'references' }, { 'main_entry_heading': u'10.1234/zenodo.4321', 'note': u'doi', 'relationship_information': u'isPartOf' }, { 'main_entry_heading': u'10.1234/zenodo.1234', 'note': u'doi', 'relationship_information': u'hasPart' }, { u'main_entry_heading': u'Staszkowka', u'edition': u'Jol', u'title': u'Bum', u'related_parts': u'1-2', u'international_standard_book_number': u'978-0201633610', }, ], u'other_standard_identifier': [ { u'standard_number_or_code': u'10.1234/foo.bar', u'source_of_number_or_code': u'doi', }, { u'standard_number_or_code': ( u'urn:lsid:ubio.org:namebank:11815'), u'source_of_number_or_code': u'lsid', u'qualifying_information': u'alternateidentifier', }, { u'standard_number_or_code': u'2011ApJS..192...18K', u'source_of_number_or_code': u'ads', u'qualifying_information': u'alternateidentifier', }, { u'standard_number_or_code': u'0317-8471', u'source_of_number_or_code': u'issn', u'qualifying_information': u'alternateidentifier', }, { u'standard_number_or_code': u'10.1234/alternate.doi', u'source_of_number_or_code': u'doi', u'qualifying_information': u'alternateidentifier', } ], u'references': [ { u'raw_reference': u'Doe, John et al (2012). Some title. ' 'Zenodo. 10.5281/zenodo.12' }, { u'raw_reference': u'Smith, Jane et al (2012). Some title. ' 'Zenodo. 10.5281/zenodo.34' } ], u'added_entry_meeting_name': [{ u'date_of_meeting': u'23-25 June, 2014', u'meeting_name_or_jurisdiction_name_as_entry_element': u'The 13th Biennial HITRAN Conference', u'number_of_part_section_meeting': u'VI', u'miscellaneous_information': u'HITRAN13', u'name_of_part_section_of_a_work': u'1', u'location_of_meeting': u'Harvard-Smithsonian Center for Astrophysics' }], u'conference_url': 'http://hitran.org/conferences/hitran-13-2014/', u'dissertation_note': { u'name_of_granting_institution': u'I guess important', }, u'journal': { 'issue': '2', 'pages': '20', 'volume': '20', 'title': 'Bam', 'year': '2014', }, u'embargo_date': '0900-12-31', u'language_code': { 'language_code_of_text_sound_track_or_separate_title': 'eng', }, u'_oai': { u'sets': [u'user-zenodo', u'user-ecfunded'], u'id': u'oai:zenodo.org:1' }, u'_files': [ { 'uri': 'https://zenodo.org/record/12345/files/test', 'checksum': 'md5:11111111111111111111111111111111', 'type': 'txt', 'size': 4, }, ], 'leader': { 'base_address_of_data': '00000', 'bibliographic_level': 'monograph_item', 'character_coding_scheme': 'marc-8', 'descriptive_cataloging_form': 'unknown', 'encoding_level': 'unknown', 'indicator_count': 2, 'length_of_the_implementation_defined_portion': 0, 'length_of_the_length_of_field_portion': 4, 'length_of_the_starting_character_position_portion': 5, 'multipart_resource_record_level': 'not_specified_or_not_applicable', 'record_length': '00000', 'record_status': 'new', 'subfield_code_count': 2, 'type_of_control': 'no_specified_type', 'type_of_record': 'language_material', 'undefined': 0, }, } # Dump MARC21 JSON structure and compare against expected JSON. preprocessed_record = marcxml_v1.preprocess_record(record=record, pid=pid) data = marcxml_v1.schema_class().dump(preprocessed_record).data assert expected == data # Assert that we can output MARCXML. assert marcxml_v1.serialize(record=record, pid=pid) def test_minimal_record(app, db, minimal_record): """Test minimal record.""" # Create record and pid. record = Record.create(minimal_record) record.model.updated = datetime.utcnow() pid = PersistentIdentifier.create( pid_type='recid', pid_value='123', object_type='rec', object_uuid=record.id) assert record.validate() is None expected = { u'date_and_time_of_latest_transaction': ( record.model.updated.strftime("%Y%m%d%H%M%S.0")), u'publication_distribution_imprint': [{ 'date_of_publication_distribution': record['publication_date'] }], u'control_number': '123', u'other_standard_identifier': [ { 'source_of_number_or_code': u'doi', 'standard_number_or_code': u'10.5072/zenodo.123' } ], u'information_relating_to_copyright_status': { 'copyright_status': 'open' }, u'summary': { 'summary': 'My description' }, u'main_entry_personal_name': { 'personal_name': 'Test' }, u'resource_type': { 'type': 'software' }, u'title_statement': { 'title': 'Test' }, u'leader': { 'base_address_of_data': '00000', 'bibliographic_level': 'monograph_item', 'character_coding_scheme': 'marc-8', 'descriptive_cataloging_form': 'unknown', 'encoding_level': 'unknown', 'indicator_count': 2, 'length_of_the_implementation_defined_portion': 0, 'length_of_the_length_of_field_portion': 4, 'length_of_the_starting_character_position_portion': 5, 'multipart_resource_record_level': 'not_specified_or_not_applicable', 'record_length': '00000', 'record_status': 'new', 'subfield_code_count': 2, 'type_of_control': 'no_specified_type', 'type_of_record': 'computer_file', 'undefined': 0, }, } data = marcxml_v1.schema_class().dump(marcxml_v1.preprocess_record( pid=pid, record=record)).data assert expected == data marcxml_v1.serialize(pid=pid, record=record) def assert_array(a1, a2): """Check array.""" for i in range(0, len(a1)): if isinstance(a1[i], dict): assert_dict(a1[i], a2[i]) elif isinstance(a1[i], list) or isinstance(a1[i], tuple): assert_array(a1[i], a2[i]) else: assert a1[i] in a2 assert len(a1) == len(a2) def assert_dict(a1, a2): """Check dict.""" for (k, v) in a1.items(): assert k in a2 if isinstance(v, dict): assert_dict(v, a2[k]) elif isinstance(v, list) or isinstance(v, tuple): assert_array(v, a2[k]) else: assert a2[k] == v assert len(a2) == len(a1)
slint/zenodo
tests/unit/records/test_schemas_marcxml.py
Python
gpl-2.0
13,950
<?php /** * Contact Form 7 Plugin * @since 0.1 * @version 1.0 */ if ( defined( 'myCRED_VERSION' ) ) { /** * Register Hook * @since 0.1 * @version 1.0 */ add_filter( 'mycred_setup_hooks', 'contact_form_seven_myCRED_Hook' ); function contact_form_seven_myCRED_Hook( $installed ) { $installed['contact_form7'] = array( 'title' => __( 'Contact Form 7 Form Submissions', 'mycred' ), 'description' => __( 'Awards %_plural% for successful form submissions (by logged in users).', 'mycred' ), 'callback' => array( 'myCRED_Contact_Form7' ) ); return $installed; } /** * Contact Form 7 Hook * @since 0.1 * @version 1.0 */ if ( !class_exists( 'myCRED_Contact_Form7' ) && class_exists( 'myCRED_Hook' ) ) { class myCRED_Contact_Form7 extends myCRED_Hook { /** * Construct */ function __construct( $hook_prefs ) { parent::__construct( array( 'id' => 'contact_form7', 'defaults' => '' ), $hook_prefs ); } /** * Run * @since 0.1 * @version 1.0 */ public function run() { add_action( 'wpcf7_mail_sent', array( $this, 'form_submission' ) ); } /** * Get Forms * Queries all Contact Form 7 forms. * @uses WP_Query() * @since 0.1 * @version 1.1 */ public function get_forms() { $forms = new WP_Query( array( 'post_type' => 'wpcf7_contact_form', 'post_status' => 'any', 'posts_per_page' => '-1', 'orderby' => 'ID', 'order' => 'ASC' ) ); $result = array(); if ( $forms->have_posts() ) { while ( $forms->have_posts() ) : $forms->the_post(); $result[get_the_ID()] = get_the_title(); endwhile; } wp_reset_postdata(); return $result; } /** * Successful Form Submission * @since 0.1 * @version 1.0 */ public function form_submission( $cf7_form ) { // Login is required if ( !is_user_logged_in() ) return; $form_id = $cf7_form->id; if ( isset( $this->prefs[$form_id] ) && $this->prefs[$form_id]['creds'] != 0 ) { $this->core->add_creds( 'contact_form_submission', get_current_user_id(), $this->prefs[$form_id]['creds'], $this->prefs[$form_id]['log'], $form_id, array( 'ref_type' => 'post' ) ); } } /** * Preferences for Commenting Hook * @since 0.1 * @version 1.0.1 */ public function preferences() { $prefs = $this->prefs; $forms = $this->get_forms(); // No forms found if ( empty( $forms ) ) { echo '<p>' . __( 'No forms found.', 'mycred' ) . '</p>'; return; } // Loop though prefs to make sure we always have a default settings (happens when a new form has been created) foreach ( $forms as $form_id => $form_title ) { if ( !isset( $prefs[$form_id] ) ) { $prefs[$form_id] = array( 'creds' => 1, 'log' => '' ); } } // Set pref if empty if ( empty( $prefs ) ) $this->prefs = $prefs; // Loop for settings foreach ( $forms as $form_id => $form_title ) { ?> <!-- Creds for --> <label for="<?php echo $this->field_id( array( $form_id, 'creds' ) ); ?>" class="subheader"><?php echo $form_title; ?></label> <ol> <li> <div class="h2"><input type="text" name="<?php echo $this->field_name( array( $form_id, 'creds' ) ); ?>" id="<?php echo $this->field_id( array( $form_id, 'creds' ) ); ?>" value="<?php echo $this->core->number( $prefs[$form_id]['creds'] ); ?>" size="8" /></div> </li> <li class="empty">&nbsp;</li> <li> <label for="<?php echo $this->field_id( array( $form_id, 'log' ) ); ?>"><?php _e( 'Log template', 'mycred' ); ?></label> <div class="h2"><input type="text" name="<?php echo $this->field_name( array( $form_id, 'log' ) ); ?>" id="<?php echo $this->field_id( array( $form_id, 'log' ) ); ?>" value="<?php echo $prefs[$form_id]['log']; ?>" class="long" /></div> <span class="description"><?php _e( 'Available template tags: General, Post', 'mycred' ); ?></span> </li> </ol> <?php } unset( $this ); } } } } ?>
crowdcreative/cidade.vc
wp-content/plugins/mycred/plugins/mycred-hook-contact-form7.php
PHP
gpl-2.0
4,148
<?php # MantisBT - a php based bugtracking system # MantisBT 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. # # MantisBT 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 MantisBT. If not, see <http://www.gnu.org/licenses/>. /** * @package CoreAPI * @subpackage ProjaxAPI * @copyright Copyright (C) 2000 - 2002 Kenzaburo Ito - kenito@300baud.org * @copyright Copyright (C) 2002 - 2013 MantisBT Team - mantisbt-dev@lists.sourceforge.net * @link http://www.mantisbt.org */ /** * requires projax.php */ require_once( 'projax' . DIRECTORY_SEPARATOR . 'projax.php' ); # enables the projax library for this page. $g_enable_projax = true; $g_projax = new Projax(); # Outputs an auto-complete field to the HTML form. The supported attribute keys in the attributes array are: # class, size, maxlength, value, and tabindex. function projax_autocomplete( $p_entrypoint, $p_field_name, $p_attributes_array = null ) { global $g_projax; static $s_projax_style_done = false; if ( ON == config_get( 'use_javascript' ) ) { echo $g_projax->text_field_with_auto_complete( $p_field_name, $p_attributes_array, $s_projax_style_done ? array( 'url' => 'xmlhttprequest.php?entrypoint=' . $p_entrypoint, 'skip_style' => '1' ) : array( 'url' => 'xmlhttprequest.php?entrypoint=' . $p_entrypoint ) ); $s_projax_style_done = true; } else { $t_tabindex = isset( $p_attributes_array['tabindex'] ) ? ( ' tabindex="' . $p_attributes_array['tabindex'] . '"' ) : ''; $t_maxlength = isset( $p_attributes_array['maxlength'] ) ?( ' maxlength="' . $p_attributes_array['maxlength'] . '"' ) : ''; echo '<input id="'.$p_field_name.'" name="'.$p_field_name.'"'. $t_tabindex . $t_maxlength . ' size="'.(isset($p_attributes_array['size'])?$p_attributes_array['size']:30).'" type="text" value="'.(isset($p_attributes_array['value'])?$p_attributes_array['value']:'').'" '.(isset($p_attributes_array['class'])?'class = "'.$p_attributes_array['class'].'" ':'').'/>'; } } # Filters the provided array of strings and only returns the ones that start with $p_prefix. # The comparison is not case sensitive. # Returns the array of the filtered strings, or an empty array. If the input array has non-unique # entries, then the output one may contain duplicates. function projax_array_filter_by_prefix( $p_array, $p_prefix ) { $t_matches = array(); foreach( $p_array as $t_entry ) { if( utf8_strtolower( utf8_substr( $t_entry, 0, utf8_strlen( $p_prefix ) ) ) == utf8_strtolower( $p_prefix ) ) { $t_matches[] = $t_entry; } } return $t_matches; } # Serializes the provided array of strings into the format expected by the auto-complete library. function projax_array_serialize_for_autocomplete( $p_array ) { $t_matches = '<ul>'; foreach( $p_array as $t_entry ) { $t_matches .= "<li>$t_entry</li>"; } $t_matches .= '</ul>'; return $t_matches; }
dauclem/Online-Bug-Tracker
private/bt/mantisbt/mantisbt-1.2.15/core/projax_api.php
PHP
gpl-2.0
3,293
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { environment } from '../../environments/environment'; import { AuthService } from '../../services/auth.service'; import { AuthInfo } from '../../types/api-output'; /** * Base skeleton for student pages. */ @Component({ selector: 'tm-student-page', templateUrl: './student-page.component.html', }) export class StudentPageComponent implements OnInit { user: string = ''; institute?: string = ''; isInstructor: boolean = false; isStudent: boolean = false; isAdmin: boolean = false; isMaintainer: boolean = false; navItems: any[] = [ { url: '/web/student', display: 'Home', }, { url: '/web/student/profile', display: 'Profile', }, { url: '/web/student/help', display: 'Help', }, ]; isFetchingAuthDetails: boolean = false; private backendUrl: string = environment.backendUrl; constructor(private route: ActivatedRoute, private authService: AuthService) {} ngOnInit(): void { this.isFetchingAuthDetails = true; this.route.queryParams.subscribe((queryParams: any) => { this.authService.getAuthUser(queryParams.user).subscribe((res: AuthInfo) => { if (res.user) { this.user = res.user.id; if (res.masquerade) { this.user += ' (M)'; } this.institute = res.institute; this.isInstructor = res.user.isInstructor; this.isStudent = res.user.isStudent; this.isAdmin = res.user.isAdmin; this.isMaintainer = res.user.isMaintainer; } else { window.location.href = `${this.backendUrl}${res.studentLoginUrl}`; } this.isFetchingAuthDetails = false; }, () => { this.isInstructor = false; this.isStudent = false; this.isAdmin = false; this.isMaintainer = false; this.isFetchingAuthDetails = false; }); }); } }
TEAMMATES/teammates
src/web/app/pages-student/student-page.component.ts
TypeScript
gpl-2.0
1,999
/* ScummVM - Graphic Adventure Engine * * ScummVM is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * 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 Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "asylum/system/speech.h" #include "asylum/resources/actor.h" #include "asylum/resources/worldstats.h" #include "asylum/system/text.h" #include "asylum/views/scene.h" #include "asylum/asylum.h" #include "asylum/staticres.h" namespace Asylum { Speech::Speech(AsylumEngine *engine): _vm(engine), _textData(0), _textDataPos(0) { _tick = _vm->getTick(); _soundResourceId = kResourceNone; _textResourceId = kResourceNone; } Speech::~Speech() { // Text resource data is disposed as part of the resource manager _textData = 0; _textDataPos = 0; // Zero-out passed pointers _vm = NULL; } ResourceId Speech::play(ResourceId soundResourceId, ResourceId textResourceId) { if (soundResourceId) if (getSound()->isPlaying(soundResourceId)) getSound()->stopAll(soundResourceId); _soundResourceId = soundResourceId; _textResourceId = textResourceId; prepareSpeech(); return soundResourceId; } ResourceId Speech::playIndexed(int32 index) { int processedIndex; if (getWorld()->actorType || index != -1) { processedIndex = (int)speechIndex[index + 5 * getWorld()->actorType] + (int)rnd(speechIndexRandom[index + 5 * getWorld()->actorType]); } else { switch(_vm->getRandom(3)) { default: case 0: processedIndex = 23; break; case 1: processedIndex = 400; break; case 2: processedIndex = 401; break; case 3: processedIndex = index; break; } if (processedIndex >= 259) processedIndex -=9; } switch (getWorld()->actorType) { default: break; case kActorMax: return play(MAKE_RESOURCE(kResourcePackSpeech, processedIndex), MAKE_RESOURCE(kResourcePackText, processedIndex + 83)); case kActorSarah: return play(MAKE_RESOURCE(kResourcePackSharedSound, processedIndex + 1927), MAKE_RESOURCE(kResourcePackText, processedIndex + 586)); case kActorCyclops: return play(MAKE_RESOURCE(kResourcePackSharedSound, processedIndex + 2084), MAKE_RESOURCE(kResourcePackText, processedIndex + 743)); case kActorAztec: return play(MAKE_RESOURCE(kResourcePackSharedSound, processedIndex + 2234), MAKE_RESOURCE(kResourcePackText, processedIndex + 893)); } return kResourceNone; } ResourceId Speech::playScene(int32 type, int32 index) { switch (type) { default: play(kResourceNone, kResourceNone); break; case 0: return play(MAKE_RESOURCE(kResourcePackSharedSound, index + 2363), MAKE_RESOURCE(kResourcePackText, index + 1022)); case 1: return play(MAKE_RESOURCE(kResourcePackSharedSound, index + 2366), MAKE_RESOURCE(kResourcePackText, index + 1025)); case 2: return play(MAKE_RESOURCE(kResourcePackSharedSound, index + 2371), MAKE_RESOURCE(kResourcePackText, index + 1030)); case 3: return play(MAKE_RESOURCE(kResourcePackSharedSound, index + 2398), MAKE_RESOURCE(kResourcePackText, index + 1057)); case 4: return play(MAKE_RESOURCE(kResourcePackSpeech, index + 503), MAKE_RESOURCE(kResourcePackText, index + 1060)); case 5: return play(MAKE_RESOURCE(kResourcePackSharedSound, index + 2401), MAKE_RESOURCE(kResourcePackText, index + 1068)); case 6: return play(MAKE_RESOURCE(kResourcePackSharedSound, index + 2409), MAKE_RESOURCE(kResourcePackText, index + 1076)); case 7: return play(MAKE_RESOURCE(kResourcePackSharedSound, index + 2415), MAKE_RESOURCE(kResourcePackText, index + 1082)); case 8: return play(MAKE_RESOURCE(kResourcePackSpeech, index + 511), MAKE_RESOURCE(kResourcePackText, index + 1084)); case 9: return play(MAKE_RESOURCE(kResourcePackSharedSound, index + 2417), MAKE_RESOURCE(kResourcePackText, index + 1088)); case 10: return play(MAKE_RESOURCE(kResourcePackSharedSound, index + 2417), MAKE_RESOURCE(kResourcePackText, index + 1093)); case 11: return play(MAKE_RESOURCE(kResourcePackSharedSound, index + 2424), MAKE_RESOURCE(kResourcePackText, index + 1100)); case 12: return play(MAKE_RESOURCE(kResourcePackSharedSound, index + 2424), MAKE_RESOURCE(kResourcePackText, index + 1102)); case 13: return play(MAKE_RESOURCE(kResourcePackSharedSound, index + 2430), MAKE_RESOURCE(kResourcePackText, index + 1108)); case 14: return play(MAKE_RESOURCE(kResourcePackSharedSound, index + 2432), MAKE_RESOURCE(kResourcePackText, index + 1110)); case 15: return play(MAKE_RESOURCE(kResourcePackSharedSound, index + 2434), MAKE_RESOURCE(kResourcePackText, index + 1112)); case 16: return play(MAKE_RESOURCE(kResourcePackSharedSound, index + 2435), MAKE_RESOURCE(kResourcePackText, index + 1113)); case 17: return play(MAKE_RESOURCE(kResourcePackSharedSound, index + 2436), MAKE_RESOURCE(kResourcePackText, index + 1114)); case 18: return play(MAKE_RESOURCE(kResourcePackSharedSound, index + 2438), MAKE_RESOURCE(kResourcePackText, index + 1116)); case 19: return play(MAKE_RESOURCE(kResourcePackSharedSound, index + 2439), MAKE_RESOURCE(kResourcePackText, index + 1117)); } return kResourceNone; } ResourceId Speech::playPlayer(int32 index) { switch (getWorld()->actorType) { default: break; case kActorMax: { int32 soundResourceIndex = index; int32 textResourceIndex = index; if (index >= 259) { soundResourceIndex -= 9; textResourceIndex -= 9; } ResourceId soundResourceId = MAKE_RESOURCE(kResourcePackSpeech, soundResourceIndex); return play(soundResourceId, MAKE_RESOURCE(kResourcePackText, textResourceIndex + 83)); } case kActorSarah: return play(MAKE_RESOURCE(kResourcePackSharedSound, index + 1927), MAKE_RESOURCE(kResourcePackText, index + 586)); case kActorCyclops: return play(MAKE_RESOURCE(kResourcePackSharedSound, index + 2084), MAKE_RESOURCE(kResourcePackText, index + 743)); case kActorAztec: return play(MAKE_RESOURCE(kResourcePackSharedSound, index + 2234), MAKE_RESOURCE(kResourcePackText, index + 893)); } return kResourceNone; } void Speech::resetResourceIds() { _soundResourceId = kResourceNone; _textResourceId = kResourceNone; } void Speech::resetTextData() { _textData = NULL; _textDataPos = NULL; } ////////////////////////////////////////////////////////////////////////// // Private methods ////////////////////////////////////////////////////////////////////////// void Speech::prepareSpeech() { int32 startTick = _vm->getTick(); if (_soundResourceId) { if (!getSound()->isPlaying(_soundResourceId) || (_tick && startTick >= _tick)) process(); if (Config.showEncounterSubtitles) { Common::Point point; Actor *actor = getScene()->getActor(); actor->adjustCoordinates(&point); int16 posY = (point.y >= 240) ? 40 : 320; getText()->draw(_textDataPos, getWorld()->font3, posY); getText()->draw(_textData, getWorld()->font1, posY); } } } void Speech::process() { _tick = 0; char *txt = getText()->get(_textResourceId); if (*(txt + strlen((const char *)txt) - 2) == 1) { _textResourceId = kResourceNone; _textData = 0; _textDataPos = 0; } else if (*txt == '{') { _textData = txt + 3; _textDataPos = 0; getText()->loadFont(getWorld()->font1); getSound()->playSound(_soundResourceId, false, Config.voiceVolume, 0); } else { _textData = 0; _textDataPos = txt; if (*txt == '/') { _textDataPos = txt + 2; } getText()->loadFont(getWorld()->font3); getSound()->playSound(_soundResourceId, false, Config.voiceVolume, 0); } } } // end of namespace Asylum
alexbevi/scummvm
engines/asylum/system/speech.cpp
C++
gpl-2.0
8,226
// Copyright 2016 Dolphin Emulator Project // Licensed under GPLv2+ // Refer to the license.txt file included. #include "Core/IOS/USB/Bluetooth/BTBase.h" #include <memory> #include <string> #include <vector> #include "Common/CommonPaths.h" #include "Common/CommonTypes.h" #include "Common/File.h" #include "Common/FileUtil.h" #include "Common/Logging/Log.h" #include "Common/SysConf.h" namespace IOS { namespace HLE { void BackUpBTInfoSection(const SysConf* sysconf) { const std::string filename = File::GetUserPath(D_CONFIG_IDX) + DIR_SEP WII_BTDINF_BACKUP; if (File::Exists(filename)) return; File::IOFile backup(filename, "wb"); const SysConf::Entry* btdinf = sysconf->GetEntry("BT.DINF"); if (!btdinf) return; const std::vector<u8>& section = btdinf->bytes; if (!backup.WriteBytes(section.data(), section.size())) ERROR_LOG(IOS_WIIMOTE, "Failed to back up BT.DINF section"); } void RestoreBTInfoSection(SysConf* sysconf) { const std::string filename = File::GetUserPath(D_CONFIG_IDX) + DIR_SEP WII_BTDINF_BACKUP; File::IOFile backup(filename, "rb"); if (!backup) return; auto& section = sysconf->GetOrAddEntry("BT.DINF", SysConf::Entry::Type::BigArray)->bytes; if (!backup.ReadBytes(section.data(), section.size())) { ERROR_LOG(IOS_WIIMOTE, "Failed to read backed up BT.DINF section"); return; } File::Delete(filename); } } // namespace HLE } // namespace IOS
linkmauve/dolphin
Source/Core/Core/IOS/USB/Bluetooth/BTBase.cpp
C++
gpl-2.0
1,428
class AddMoreColumnsToUsers < ActiveRecord::Migration def change add_column :users, :username, :string add_column :users, :image, :string end end
kirkokada/hackathon
db/migrate/20150524135324_add_more_columns_to_users.rb
Ruby
gpl-2.0
158
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Generated Thu Dec 1 09:58:36 2011 by generateDS.py version 2.7a. # import sys import getopt import re as re_ etree_ = None Verbose_import_ = False (XMLParser_import_none, XMLParser_import_lxml, XMLParser_import_elementtree ) = range(3) XMLParser_import_library = None try: # lxml from lxml import etree as etree_ XMLParser_import_library = XMLParser_import_lxml if Verbose_import_: print("running with lxml.etree") except ImportError: try: # cElementTree from Python 2.5+ # pylint: disable=E0602, E0611 import xml.etree.cElementTree as etree_ XMLParser_import_library = XMLParser_import_elementtree if Verbose_import_: print("running with cElementTree on Python 2.5+") except ImportError: try: # ElementTree from Python 2.5+ # pylint: disable=E0602,E0611 import xml.etree.ElementTree as etree_ XMLParser_import_library = XMLParser_import_elementtree if Verbose_import_: print("running with ElementTree on Python 2.5+") except ImportError: try: # normal cElementTree install import cElementTree as etree_ XMLParser_import_library = XMLParser_import_elementtree if Verbose_import_: print("running with cElementTree") except ImportError: try: # normal ElementTree install import elementtree.ElementTree as etree_ XMLParser_import_library = XMLParser_import_elementtree if Verbose_import_: print("running with ElementTree") except ImportError: raise ImportError("Failed to import ElementTree from any known place") def parsexml_(*args, **kwargs): if (XMLParser_import_library == XMLParser_import_lxml and 'parser' not in kwargs): # Use the lxml ElementTree compatible parser so that, e.g., # we ignore comments. kwargs['parser'] = etree_.ETCompatXMLParser() doc = etree_.parse(*args, **kwargs) return doc # # User methods # # Calls to the methods in these classes are generated by generateDS.py. # You can replace these methods by re-implementing the following class # in a module named generatedssuper.py. try: from generatedssuper import GeneratedsSuper except ImportError, exp: class GeneratedsSuper(object): def gds_format_string(self, input_data, input_name=''): return input_data def gds_validate_string(self, input_data, node, input_name=''): return input_data def gds_format_integer(self, input_data, input_name=''): return '%d' % input_data def gds_validate_integer(self, input_data, node, input_name=''): return input_data def gds_format_integer_list(self, input_data, input_name=''): return '%s' % input_data def gds_validate_integer_list(self, input_data, node, input_name=''): values = input_data.split() for value in values: try: fvalue = float(value) except (TypeError, ValueError), exp: raise_parse_error(node, 'Requires sequence of integers') return input_data def gds_format_float(self, input_data, input_name=''): return '%f' % input_data def gds_validate_float(self, input_data, node, input_name=''): return input_data def gds_format_float_list(self, input_data, input_name=''): return '%s' % input_data def gds_validate_float_list(self, input_data, node, input_name=''): values = input_data.split() for value in values: try: fvalue = float(value) except (TypeError, ValueError), exp: raise_parse_error(node, 'Requires sequence of floats') return input_data def gds_format_double(self, input_data, input_name=''): return '%e' % input_data def gds_validate_double(self, input_data, node, input_name=''): return input_data def gds_format_double_list(self, input_data, input_name=''): return '%s' % input_data def gds_validate_double_list(self, input_data, node, input_name=''): values = input_data.split() for value in values: try: fvalue = float(value) except (TypeError, ValueError), exp: raise_parse_error(node, 'Requires sequence of doubles') return input_data def gds_format_boolean(self, input_data, input_name=''): return '%s' % input_data def gds_validate_boolean(self, input_data, node, input_name=''): return input_data def gds_format_boolean_list(self, input_data, input_name=''): return '%s' % input_data def gds_validate_boolean_list(self, input_data, node, input_name=''): values = input_data.split() for value in values: if value not in ('true', '1', 'false', '0', ): raise_parse_error(node, 'Requires sequence of booleans ("true", "1", "false", "0")') return input_data def gds_str_lower(self, instring): return instring.lower() def get_path_(self, node): path_list = [] self.get_path_list_(node, path_list) path_list.reverse() path = '/'.join(path_list) return path Tag_strip_pattern_ = re_.compile(r'\{.*\}') def get_path_list_(self, node, path_list): if node is None: return tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) if tag: path_list.append(tag) self.get_path_list_(node.getparent(), path_list) def get_class_obj_(self, node, default_class=None): class_obj1 = default_class if 'xsi' in node.nsmap: classname = node.get('{%s}type' % node.nsmap['xsi']) if classname is not None: names = classname.split(':') if len(names) == 2: classname = names[1] class_obj2 = globals().get(classname) if class_obj2 is not None: class_obj1 = class_obj2 return class_obj1 def gds_build_any(self, node, type_name=None): return None # # If you have installed IPython you can uncomment and use the following. # IPython is available from http://ipython.scipy.org/. # ## from IPython.Shell import IPShellEmbed ## args = '' # ipshell = IPShellEmbed(args, ## banner = 'Dropping into IPython', # exit_msg = 'Leaving Interpreter, back to program.') # Then use the following line where and when you want to drop into the # IPython shell: # ipshell('<some message> -- Entering ipshell.\nHit Ctrl-D to exit') # # Globals # ExternalEncoding = 'ascii' Tag_pattern_ = re_.compile(r'({.*})?(.*)') String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') # # Support/utility functions. # def showIndent(outfile, level): for idx in range(level): outfile.write(' ') def quote_xml(inStr): if not inStr: return '' s1 = (isinstance(inStr, basestring) and inStr or '%s' % inStr) s1 = s1.replace('&', '&amp;') s1 = s1.replace('<', '&lt;') s1 = s1.replace('>', '&gt;') return s1 def quote_attrib(inStr): s1 = (isinstance(inStr, basestring) and inStr or '%s' % inStr) s1 = s1.replace('&', '&amp;') s1 = s1.replace('<', '&lt;') s1 = s1.replace('>', '&gt;') if '"' in s1: if "'" in s1: s1 = '"%s"' % s1.replace('"', "&quot;") else: s1 = "'%s'" % s1 else: s1 = '"%s"' % s1 return s1 def quote_python(inStr): s1 = inStr if s1.find("'") == -1: if s1.find('\n') == -1: return "'%s'" % s1 else: return "'''%s'''" % s1 else: if s1.find('"') != -1: s1 = s1.replace('"', '\\"') if s1.find('\n') == -1: return '"%s"' % s1 else: return '"""%s"""' % s1 def get_all_text_(node): if node.text is not None: text = node.text else: text = '' for child in node: if child.tail is not None: text += child.tail return text def find_attr_value_(attr_name, node): attrs = node.attrib attr_parts = attr_name.split(':') value = None if len(attr_parts) == 1: value = attrs.get(attr_name) elif len(attr_parts) == 2: prefix, name = attr_parts namespace = node.nsmap.get(prefix) if namespace is not None: value = attrs.get('{%s}%s' % (namespace, name, )) return value class GDSParseError(Exception): pass def raise_parse_error(node, msg): if XMLParser_import_library == XMLParser_import_lxml: msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) else: msg = '%s (element %s)' % (msg, node.tag, ) raise GDSParseError(msg) class MixedContainer: # Constants for category: CategoryNone = 0 CategoryText = 1 CategorySimple = 2 CategoryComplex = 3 # Constants for content_type: TypeNone = 0 TypeText = 1 TypeString = 2 TypeInteger = 3 TypeFloat = 4 TypeDecimal = 5 TypeDouble = 6 TypeBoolean = 7 def __init__(self, category, content_type, name, value): self.category = category self.content_type = content_type self.name = name self.value = value def getCategory(self): return self.category def getContenttype(self, content_type): return self.content_type def getValue(self): return self.value def getName(self): return self.name def export(self, outfile, level, name, namespace): if self.category == MixedContainer.CategoryText: # Prevent exporting empty content as empty lines. if self.value.strip(): outfile.write(self.value) elif self.category == MixedContainer.CategorySimple: self.exportSimple(outfile, level, name) else: # category == MixedContainer.CategoryComplex self.value.export(outfile, level, namespace, name) def exportSimple(self, outfile, level, name): if self.content_type == MixedContainer.TypeString: outfile.write('<%s>%s</%s>' % (self.name, self.value, self.name)) elif self.content_type == MixedContainer.TypeInteger or \ self.content_type == MixedContainer.TypeBoolean: outfile.write('<%s>%d</%s>' % (self.name, self.value, self.name)) elif self.content_type == MixedContainer.TypeFloat or \ self.content_type == MixedContainer.TypeDecimal: outfile.write('<%s>%f</%s>' % (self.name, self.value, self.name)) elif self.content_type == MixedContainer.TypeDouble: outfile.write('<%s>%g</%s>' % (self.name, self.value, self.name)) def exportLiteral(self, outfile, level, name): if self.category == MixedContainer.CategoryText: showIndent(outfile, level) outfile.write('model_.MixedContainer(%d, %d, "%s", "%s"),\n' % (self.category, self.content_type, self.name, self.value)) elif self.category == MixedContainer.CategorySimple: showIndent(outfile, level) outfile.write('model_.MixedContainer(%d, %d, "%s", "%s"),\n' % (self.category, self.content_type, self.name, self.value)) else: # category == MixedContainer.CategoryComplex showIndent(outfile, level) outfile.write('model_.MixedContainer(%d, %d, "%s",\n' % (self.category, self.content_type, self.name,)) self.value.exportLiteral(outfile, level + 1) showIndent(outfile, level) outfile.write(')\n') class MemberSpec_(object): def __init__(self, name='', data_type='', container=0): self.name = name self.data_type = data_type self.container = container def set_name(self, name): self.name = name def get_name(self): return self.name def set_data_type(self, data_type): self.data_type = data_type def get_data_type_chain(self): return self.data_type def get_data_type(self): if isinstance(self.data_type, list): if len(self.data_type) > 0: return self.data_type[-1] else: return 'xs:string' else: return self.data_type def set_container(self, container): self.container = container def get_container(self): return self.container def _cast(typ, value): if typ is None or value is None: return value return typ(value) # # Data representation classes. # class testsuites(GeneratedsSuper): """Contains an aggregation of testsuite results""" subclass = None superclass = None def __init__(self, testsuite=None): if testsuite is None: self.testsuite = [] else: self.testsuite = testsuite def factory(*args_, **kwargs_): if testsuites.subclass: # pylint: disable=E1102 return testsuites.subclass(*args_, **kwargs_) else: return testsuites(*args_, **kwargs_) factory = staticmethod(factory) def get_testsuite(self): return self.testsuite def set_testsuite(self, testsuite): self.testsuite = testsuite def add_testsuite(self, value): self.testsuite.append(value) def insert_testsuite(self, index, value): self.testsuite[index] = value def export(self, outfile, level, namespace_='', name_='testsuites', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) already_processed = [] self.exportAttributes(outfile, level, already_processed, namespace_, name_='testsuites') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write('/>\n') def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='testsuites'): pass def exportChildren(self, outfile, level, namespace_='', name_='testsuites', fromsubclass_=False): for testsuite_ in self.testsuite: testsuite_.export(outfile, level, namespace_, name_='testsuite') def hasContent_(self): if ( self.testsuite ): return True else: return False def exportLiteral(self, outfile, level, name_='testsuites'): level += 1 self.exportLiteralAttributes(outfile, level, [], name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, already_processed, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('testsuite=[\n') level += 1 for testsuite_ in self.testsuite: showIndent(outfile, level) outfile.write('model_.testsuiteType(\n') testsuite_.exportLiteral(outfile, level, name_='testsuiteType') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node): self.buildAttributes(node, node.attrib, []) for child in node: nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] self.buildChildren(child, node, nodeName_) def buildAttributes(self, node, attrs, already_processed): pass def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): if nodeName_ == 'testsuite': obj_ = testsuiteType.factory() obj_.build(child_) self.testsuite.append(obj_) # end class testsuites class testsuite(GeneratedsSuper): """Contains the results of exexuting a testsuiteFull class name of the test for non-aggregated testsuite documents. Class name without the package for aggregated testsuites documentswhen the test was executed. Timezone may not be specified.Host on which the tests were executed. 'localhost' should be used if the hostname cannot be determined.The total number of tests in the suiteThe total number of tests in the suite that failed. A failure is a test which the code has explicitly failed by using the mechanisms for that purpose. e.g., via an assertEqualsThe total number of tests in the suite that errorrd. An errored test is one that had an unanticipated problem. e.g., an unchecked throwable; or a problem with the implementation of the test.Time taken (in seconds) to execute the tests in the suite""" subclass = None superclass = None def __init__(self, tests=None, errors=None, name=None, timestamp=None, hostname=None, time=None, failures=None, properties=None, testcase=None, system_out=None, system_err=None, extensiontype_=None): self.tests = _cast(int, tests) self.errors = _cast(int, errors) self.name = _cast(None, name) self.timestamp = _cast(None, timestamp) self.hostname = _cast(None, hostname) self.time = _cast(float, time) self.failures = _cast(int, failures) self.properties = properties if testcase is None: self.testcase = [] else: self.testcase = testcase self.system_out = system_out self.system_err = system_err self.extensiontype_ = extensiontype_ def factory(*args_, **kwargs_): if testsuite.subclass: # pylint: disable=E1102 return testsuite.subclass(*args_, **kwargs_) else: return testsuite(*args_, **kwargs_) factory = staticmethod(factory) def get_properties(self): return self.properties def set_properties(self, properties): self.properties = properties def get_testcase(self): return self.testcase def set_testcase(self, testcase): self.testcase = testcase def add_testcase(self, value): self.testcase.append(value) def insert_testcase(self, index, value): self.testcase[index] = value def get_system_out(self): return self.system_out def set_system_out(self, system_out): self.system_out = system_out def get_system_err(self): return self.system_err def set_system_err(self, system_err): self.system_err = system_err def get_tests(self): return self.tests def set_tests(self, tests): self.tests = tests def get_errors(self): return self.errors def set_errors(self, errors): self.errors = errors def get_name(self): return self.name def set_name(self, name): self.name = name def get_timestamp(self): return self.timestamp def set_timestamp(self, timestamp): self.timestamp = timestamp def validate_ISO8601_DATETIME_PATTERN(self, value): # Validate type ISO8601_DATETIME_PATTERN, a restriction on xs:dateTime. pass def get_hostname(self): return self.hostname def set_hostname(self, hostname): self.hostname = hostname def get_time(self): return self.time def set_time(self, time): self.time = time def get_failures(self): return self.failures def set_failures(self, failures): self.failures = failures def get_extensiontype_(self): return self.extensiontype_ def set_extensiontype_(self, extensiontype_): self.extensiontype_ = extensiontype_ def export(self, outfile, level, namespace_='', name_='testsuite', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) already_processed = [] self.exportAttributes(outfile, level, already_processed, namespace_, name_='testsuite') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write('/>\n') def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='testsuite'): if self.tests is not None and 'tests' not in already_processed: already_processed.append('tests') outfile.write(' tests="%s"' % self.gds_format_integer(self.tests, input_name='tests')) if self.errors is not None and 'errors' not in already_processed: already_processed.append('errors') outfile.write(' errors="%s"' % self.gds_format_integer(self.errors, input_name='errors')) if self.name is not None and 'name' not in already_processed: already_processed.append('name') outfile.write(' name=%s' % (self.gds_format_string(quote_attrib(self.name).encode(ExternalEncoding), input_name='name'), )) if self.timestamp is not None and 'timestamp' not in already_processed: already_processed.append('timestamp') outfile.write(' timestamp=%s' % (quote_attrib(self.timestamp), )) if self.hostname is not None and 'hostname' not in already_processed: already_processed.append('hostname') outfile.write(' hostname=%s' % (self.gds_format_string(quote_attrib(self.hostname).encode(ExternalEncoding), input_name='hostname'), )) if self.time is not None and 'time' not in already_processed: already_processed.append('time') outfile.write(' time="%s"' % self.gds_format_float(self.time, input_name='time')) if self.failures is not None and 'failures' not in already_processed: already_processed.append('failures') outfile.write(' failures="%s"' % self.gds_format_integer(self.failures, input_name='failures')) if self.extensiontype_ is not None and 'xsi:type' not in already_processed: already_processed.append('xsi:type') outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"') outfile.write(' xsi:type="%s"' % self.extensiontype_) def exportChildren(self, outfile, level, namespace_='', name_='testsuite', fromsubclass_=False): if self.properties is not None: self.properties.export(outfile, level, namespace_, name_='properties', ) for testcase_ in self.testcase: testcase_.export(outfile, level, namespace_, name_='testcase') if self.system_out is not None: showIndent(outfile, level) outfile.write('<%ssystem-out>%s</%ssystem-out>\n' % (namespace_, self.gds_format_string(quote_xml(self.system_out).encode(ExternalEncoding), input_name='system-out'), namespace_)) if self.system_err is not None: showIndent(outfile, level) outfile.write('<%ssystem-err>%s</%ssystem-err>\n' % (namespace_, self.gds_format_string(quote_xml(self.system_err).encode(ExternalEncoding), input_name='system-err'), namespace_)) def hasContent_(self): if ( self.properties is not None or self.testcase or self.system_out is not None or self.system_err is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='testsuite'): level += 1 self.exportLiteralAttributes(outfile, level, [], name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, already_processed, name_): if self.tests is not None and 'tests' not in already_processed: already_processed.append('tests') showIndent(outfile, level) outfile.write('tests = %d,\n' % (self.tests,)) if self.errors is not None and 'errors' not in already_processed: already_processed.append('errors') showIndent(outfile, level) outfile.write('errors = %d,\n' % (self.errors,)) if self.name is not None and 'name' not in already_processed: already_processed.append('name') showIndent(outfile, level) outfile.write('name = "%s",\n' % (self.name,)) if self.timestamp is not None and 'timestamp' not in already_processed: already_processed.append('timestamp') showIndent(outfile, level) outfile.write('timestamp = "%s",\n' % (self.timestamp,)) if self.hostname is not None and 'hostname' not in already_processed: already_processed.append('hostname') showIndent(outfile, level) outfile.write('hostname = "%s",\n' % (self.hostname,)) if self.time is not None and 'time' not in already_processed: already_processed.append('time') showIndent(outfile, level) outfile.write('time = %f,\n' % (self.time,)) if self.failures is not None and 'failures' not in already_processed: already_processed.append('failures') showIndent(outfile, level) outfile.write('failures = %d,\n' % (self.failures,)) def exportLiteralChildren(self, outfile, level, name_): if self.properties is not None: showIndent(outfile, level) outfile.write('properties=model_.propertiesType(\n') self.properties.exportLiteral(outfile, level, name_='properties') showIndent(outfile, level) outfile.write('),\n') showIndent(outfile, level) outfile.write('testcase=[\n') level += 1 for testcase_ in self.testcase: showIndent(outfile, level) outfile.write('model_.testcaseType(\n') testcase_.exportLiteral(outfile, level, name_='testcaseType') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') if self.system_out is not None: showIndent(outfile, level) outfile.write('system_out=%s,\n' % quote_python(self.system_out).encode(ExternalEncoding)) if self.system_err is not None: showIndent(outfile, level) outfile.write('system_err=%s,\n' % quote_python(self.system_err).encode(ExternalEncoding)) def build(self, node): self.buildAttributes(node, node.attrib, []) for child in node: nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] self.buildChildren(child, node, nodeName_) def buildAttributes(self, node, attrs, already_processed): value = find_attr_value_('tests', node) if value is not None and 'tests' not in already_processed: already_processed.append('tests') try: self.tests = int(value) except ValueError, exp: raise_parse_error(node, 'Bad integer attribute: %s' % exp) value = find_attr_value_('errors', node) if value is not None and 'errors' not in already_processed: already_processed.append('errors') try: self.errors = int(value) except ValueError, exp: raise_parse_error(node, 'Bad integer attribute: %s' % exp) value = find_attr_value_('name', node) if value is not None and 'name' not in already_processed: already_processed.append('name') self.name = value self.name = ' '.join(self.name.split()) value = find_attr_value_('timestamp', node) if value is not None and 'timestamp' not in already_processed: already_processed.append('timestamp') self.timestamp = value self.validate_ISO8601_DATETIME_PATTERN(self.timestamp) # validate type ISO8601_DATETIME_PATTERN value = find_attr_value_('hostname', node) if value is not None and 'hostname' not in already_processed: already_processed.append('hostname') self.hostname = value self.hostname = ' '.join(self.hostname.split()) value = find_attr_value_('time', node) if value is not None and 'time' not in already_processed: already_processed.append('time') try: self.time = float(value) except ValueError, exp: raise ValueError('Bad float/double attribute (time): %s' % exp) value = find_attr_value_('failures', node) if value is not None and 'failures' not in already_processed: already_processed.append('failures') try: self.failures = int(value) except ValueError, exp: raise_parse_error(node, 'Bad integer attribute: %s' % exp) value = find_attr_value_('xsi:type', node) if value is not None and 'xsi:type' not in already_processed: already_processed.append('xsi:type') self.extensiontype_ = value def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): if nodeName_ == 'properties': obj_ = propertiesType.factory() obj_.build(child_) self.set_properties(obj_) elif nodeName_ == 'testcase': obj_ = testcaseType.factory() obj_.build(child_) self.testcase.append(obj_) elif nodeName_ == 'system-out': system_out_ = child_.text system_out_ = self.gds_validate_string(system_out_, node, 'system_out') self.system_out = system_out_ elif nodeName_ == 'system-err': system_err_ = child_.text system_err_ = self.gds_validate_string(system_err_, node, 'system_err') self.system_err = system_err_ # end class testsuite class system_out(GeneratedsSuper): """Data that was written to standard out while the test was executed""" subclass = None superclass = None def __init__(self): pass def factory(*args_, **kwargs_): if system_out.subclass: # pylint: disable=E1102 return system_out.subclass(*args_, **kwargs_) else: return system_out(*args_, **kwargs_) factory = staticmethod(factory) def export(self, outfile, level, namespace_='', name_='system-out', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) already_processed = [] self.exportAttributes(outfile, level, already_processed, namespace_, name_='system-out') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write('/>\n') def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='system-out'): pass def exportChildren(self, outfile, level, namespace_='', name_='system-out', fromsubclass_=False): pass def hasContent_(self): if ( ): return True else: return False def exportLiteral(self, outfile, level, name_='system-out'): level += 1 self.exportLiteralAttributes(outfile, level, [], name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, already_processed, name_): pass def exportLiteralChildren(self, outfile, level, name_): pass def build(self, node): self.buildAttributes(node, node.attrib, []) for child in node: nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] self.buildChildren(child, node, nodeName_) def buildAttributes(self, node, attrs, already_processed): pass def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): pass # end class system_out class system_err(GeneratedsSuper): """Data that was written to standard error while the test was executed""" subclass = None superclass = None def __init__(self): pass def factory(*args_, **kwargs_): if system_err.subclass: # pylint: disable=E1102 return system_err.subclass(*args_, **kwargs_) else: return system_err(*args_, **kwargs_) factory = staticmethod(factory) def export(self, outfile, level, namespace_='', name_='system-err', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) already_processed = [] self.exportAttributes(outfile, level, already_processed, namespace_, name_='system-err') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write('/>\n') def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='system-err'): pass def exportChildren(self, outfile, level, namespace_='', name_='system-err', fromsubclass_=False): pass def hasContent_(self): if ( ): return True else: return False def exportLiteral(self, outfile, level, name_='system-err'): level += 1 self.exportLiteralAttributes(outfile, level, [], name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, already_processed, name_): pass def exportLiteralChildren(self, outfile, level, name_): pass def build(self, node): self.buildAttributes(node, node.attrib, []) for child in node: nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] self.buildChildren(child, node, nodeName_) def buildAttributes(self, node, attrs, already_processed): pass def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): pass # end class system_err class testsuiteType(testsuite): """Derived from testsuite/@name in the non-aggregated documentsStarts at '0' for the first testsuite and is incremented by 1 for each following testsuite""" subclass = None superclass = testsuite def __init__(self, tests=None, errors=None, name=None, timestamp=None, hostname=None, time=None, failures=None, properties=None, testcase=None, system_out=None, system_err=None, id=None, package=None): super(testsuiteType, self).__init__(tests, errors, name, timestamp, hostname, time, failures, properties, testcase, system_out, system_err, ) self.id = _cast(int, id) self.package = _cast(None, package) pass def factory(*args_, **kwargs_): if testsuiteType.subclass: return testsuiteType.subclass(*args_, **kwargs_) else: return testsuiteType(*args_, **kwargs_) factory = staticmethod(factory) def get_id(self): return self.id def set_id(self, id): self.id = id def get_package(self): return self.package def set_package(self, package): self.package = package def export(self, outfile, level, namespace_='', name_='testsuiteType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) already_processed = [] self.exportAttributes(outfile, level, already_processed, namespace_, name_='testsuiteType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write('/>\n') def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='testsuiteType'): super(testsuiteType, self).exportAttributes(outfile, level, already_processed, namespace_, name_='testsuiteType') if self.id is not None and 'id' not in already_processed: already_processed.append('id') outfile.write(' id="%s"' % self.gds_format_integer(self.id, input_name='id')) if self.package is not None and 'package' not in already_processed: already_processed.append('package') outfile.write(' package=%s' % (self.gds_format_string(quote_attrib(self.package).encode(ExternalEncoding), input_name='package'), )) def exportChildren(self, outfile, level, namespace_='', name_='testsuiteType', fromsubclass_=False): super(testsuiteType, self).exportChildren(outfile, level, namespace_, name_, True) def hasContent_(self): if ( super(testsuiteType, self).hasContent_() ): return True else: return False def exportLiteral(self, outfile, level, name_='testsuiteType'): level += 1 self.exportLiteralAttributes(outfile, level, [], name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, already_processed, name_): if self.id is not None and 'id' not in already_processed: already_processed.append('id') showIndent(outfile, level) outfile.write('id = %d,\n' % (self.id,)) if self.package is not None and 'package' not in already_processed: already_processed.append('package') showIndent(outfile, level) outfile.write('package = "%s",\n' % (self.package,)) super(testsuiteType, self).exportLiteralAttributes(outfile, level, already_processed, name_) def exportLiteralChildren(self, outfile, level, name_): super(testsuiteType, self).exportLiteralChildren(outfile, level, name_) def build(self, node): self.buildAttributes(node, node.attrib, []) for child in node: nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] self.buildChildren(child, node, nodeName_) def buildAttributes(self, node, attrs, already_processed): value = find_attr_value_('id', node) if value is not None and 'id' not in already_processed: already_processed.append('id') try: self.id = int(value) except ValueError, exp: raise_parse_error(node, 'Bad integer attribute: %s' % exp) value = find_attr_value_('package', node) if value is not None and 'package' not in already_processed: already_processed.append('package') self.package = value self.package = ' '.join(self.package.split()) super(testsuiteType, self).buildAttributes(node, attrs, already_processed) def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): super(testsuiteType, self).buildChildren(child_, node, nodeName_, True) pass # end class testsuiteType class propertiesType(GeneratedsSuper): subclass = None superclass = None def __init__(self, property=None): if property is None: self.property = [] else: self.property = property def factory(*args_, **kwargs_): if propertiesType.subclass: # pylint: disable=E1102 return propertiesType.subclass(*args_, **kwargs_) else: return propertiesType(*args_, **kwargs_) factory = staticmethod(factory) def get_property(self): return self.property def set_property(self, property): self.property = property def add_property(self, value): self.property.append(value) def insert_property(self, index, value): self.property[index] = value def export(self, outfile, level, namespace_='', name_='propertiesType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) already_processed = [] self.exportAttributes(outfile, level, already_processed, namespace_, name_='propertiesType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write('/>\n') def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='propertiesType'): pass def exportChildren(self, outfile, level, namespace_='', name_='propertiesType', fromsubclass_=False): for property_ in self.property: property_.export(outfile, level, namespace_, name_='property') def hasContent_(self): if ( self.property ): return True else: return False def exportLiteral(self, outfile, level, name_='propertiesType'): level += 1 self.exportLiteralAttributes(outfile, level, [], name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, already_processed, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('property=[\n') level += 1 for property_ in self.property: showIndent(outfile, level) outfile.write('model_.propertyType(\n') property_.exportLiteral(outfile, level, name_='propertyType') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node): self.buildAttributes(node, node.attrib, []) for child in node: nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] self.buildChildren(child, node, nodeName_) def buildAttributes(self, node, attrs, already_processed): pass def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): if nodeName_ == 'property': obj_ = propertyType.factory() obj_.build(child_) self.property.append(obj_) # end class propertiesType class propertyType(GeneratedsSuper): subclass = None superclass = None def __init__(self, name=None, value=None): self.name = _cast(None, name) self.value = _cast(None, value) pass def factory(*args_, **kwargs_): if propertyType.subclass: # pylint: disable=E1102 return propertyType.subclass(*args_, **kwargs_) else: return propertyType(*args_, **kwargs_) factory = staticmethod(factory) def get_name(self): return self.name def set_name(self, name): self.name = name def get_value(self): return self.value def set_value(self, value): self.value = value def export(self, outfile, level, namespace_='', name_='propertyType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) already_processed = [] self.exportAttributes(outfile, level, already_processed, namespace_, name_='propertyType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write('/>\n') def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='propertyType'): if self.name is not None and 'name' not in already_processed: already_processed.append('name') outfile.write(' name=%s' % (self.gds_format_string(quote_attrib(self.name).encode(ExternalEncoding), input_name='name'), )) if self.value is not None and 'value' not in already_processed: already_processed.append('value') outfile.write(' value=%s' % (self.gds_format_string(quote_attrib(self.value).encode(ExternalEncoding), input_name='value'), )) def exportChildren(self, outfile, level, namespace_='', name_='propertyType', fromsubclass_=False): pass def hasContent_(self): if ( ): return True else: return False def exportLiteral(self, outfile, level, name_='propertyType'): level += 1 self.exportLiteralAttributes(outfile, level, [], name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, already_processed, name_): if self.name is not None and 'name' not in already_processed: already_processed.append('name') showIndent(outfile, level) outfile.write('name = "%s",\n' % (self.name,)) if self.value is not None and 'value' not in already_processed: already_processed.append('value') showIndent(outfile, level) outfile.write('value = "%s",\n' % (self.value,)) def exportLiteralChildren(self, outfile, level, name_): pass def build(self, node): self.buildAttributes(node, node.attrib, []) for child in node: nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] self.buildChildren(child, node, nodeName_) def buildAttributes(self, node, attrs, already_processed): value = find_attr_value_('name', node) if value is not None and 'name' not in already_processed: already_processed.append('name') self.name = value self.name = ' '.join(self.name.split()) value = find_attr_value_('value', node) if value is not None and 'value' not in already_processed: already_processed.append('value') self.value = value def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): pass # end class propertyType class testcaseType(GeneratedsSuper): """Name of the test methodFull class name for the class the test method is in.Time taken (in seconds) to execute the test""" subclass = None superclass = None def __init__(self, classname=None, name=None, time=None, error=None, failure=None): self.classname = _cast(None, classname) self.name = _cast(None, name) self.time = _cast(float, time) self.error = error self.failure = failure def factory(*args_, **kwargs_): if testcaseType.subclass: # pylint: disable=E1102 return testcaseType.subclass(*args_, **kwargs_) else: return testcaseType(*args_, **kwargs_) factory = staticmethod(factory) def get_error(self): return self.error def set_error(self, error): self.error = error def get_failure(self): return self.failure def set_failure(self, failure): self.failure = failure def get_classname(self): return self.classname def set_classname(self, classname): self.classname = classname def get_name(self): return self.name def set_name(self, name): self.name = name def get_time(self): return self.time def set_time(self, time): self.time = time def export(self, outfile, level, namespace_='', name_='testcaseType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) already_processed = [] self.exportAttributes(outfile, level, already_processed, namespace_, name_='testcaseType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write('/>\n') def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='testcaseType'): if self.classname is not None and 'classname' not in already_processed: already_processed.append('classname') outfile.write(' classname=%s' % (self.gds_format_string(quote_attrib(self.classname).encode(ExternalEncoding), input_name='classname'), )) if self.name is not None and 'name' not in already_processed: already_processed.append('name') outfile.write(' name=%s' % (self.gds_format_string(quote_attrib(self.name).encode(ExternalEncoding), input_name='name'), )) if self.time is not None and 'time' not in already_processed: already_processed.append('time') outfile.write(' time="%s"' % self.gds_format_float(self.time, input_name='time')) def exportChildren(self, outfile, level, namespace_='', name_='testcaseType', fromsubclass_=False): if self.error is not None: self.error.export(outfile, level, namespace_, name_='error') if self.failure is not None: self.failure.export(outfile, level, namespace_, name_='failure') def hasContent_(self): if ( self.error is not None or self.failure is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='testcaseType'): level += 1 self.exportLiteralAttributes(outfile, level, [], name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, already_processed, name_): if self.classname is not None and 'classname' not in already_processed: already_processed.append('classname') showIndent(outfile, level) outfile.write('classname = "%s",\n' % (self.classname,)) if self.name is not None and 'name' not in already_processed: already_processed.append('name') showIndent(outfile, level) outfile.write('name = "%s",\n' % (self.name,)) if self.time is not None and 'time' not in already_processed: already_processed.append('time') showIndent(outfile, level) outfile.write('time = %f,\n' % (self.time,)) def exportLiteralChildren(self, outfile, level, name_): if self.error is not None: showIndent(outfile, level) outfile.write('error=model_.errorType(\n') self.error.exportLiteral(outfile, level, name_='error') showIndent(outfile, level) outfile.write('),\n') if self.failure is not None: showIndent(outfile, level) outfile.write('failure=model_.failureType(\n') self.failure.exportLiteral(outfile, level, name_='failure') showIndent(outfile, level) outfile.write('),\n') def build(self, node): self.buildAttributes(node, node.attrib, []) for child in node: nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] self.buildChildren(child, node, nodeName_) def buildAttributes(self, node, attrs, already_processed): value = find_attr_value_('classname', node) if value is not None and 'classname' not in already_processed: already_processed.append('classname') self.classname = value self.classname = ' '.join(self.classname.split()) value = find_attr_value_('name', node) if value is not None and 'name' not in already_processed: already_processed.append('name') self.name = value self.name = ' '.join(self.name.split()) value = find_attr_value_('time', node) if value is not None and 'time' not in already_processed: already_processed.append('time') try: self.time = float(value) except ValueError, exp: raise ValueError('Bad float/double attribute (time): %s' % exp) def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): if nodeName_ == 'error': obj_ = errorType.factory() obj_.build(child_) self.set_error(obj_) elif nodeName_ == 'failure': obj_ = failureType.factory() obj_.build(child_) self.set_failure(obj_) # end class testcaseType class errorType(GeneratedsSuper): """The error message. e.g., if a java exception is thrown, the return value of getMessage()The type of error that occurred. e.g., if a java execption is thrown the full class name of the exception.""" subclass = None superclass = None def __init__(self, message=None, type_=None, valueOf_=None): self.message = _cast(None, message) self.type_ = _cast(None, type_) self.valueOf_ = valueOf_ def factory(*args_, **kwargs_): if errorType.subclass: # pylint: disable=E1102 return errorType.subclass(*args_, **kwargs_) else: return errorType(*args_, **kwargs_) factory = staticmethod(factory) def get_message(self): return self.message def set_message(self, message): self.message = message def get_type(self): return self.type_ def set_type(self, type_): self.type_ = type_ def get_valueOf_(self): return self.valueOf_ def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='errorType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) already_processed = [] self.exportAttributes(outfile, level, already_processed, namespace_, name_='errorType') if self.hasContent_(): outfile.write('>') outfile.write(str(self.valueOf_).encode(ExternalEncoding)) self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write('/>\n') def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='errorType'): if self.message is not None and 'message' not in already_processed: already_processed.append('message') outfile.write(' message=%s' % (self.gds_format_string(quote_attrib(self.message).encode(ExternalEncoding), input_name='message'), )) if self.type_ is not None and 'type_' not in already_processed: already_processed.append('type_') outfile.write(' type=%s' % (self.gds_format_string(quote_attrib(self.type_).encode(ExternalEncoding), input_name='type'), )) def exportChildren(self, outfile, level, namespace_='', name_='errorType', fromsubclass_=False): pass def hasContent_(self): if ( self.valueOf_ ): return True else: return False def exportLiteral(self, outfile, level, name_='errorType'): level += 1 self.exportLiteralAttributes(outfile, level, [], name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) showIndent(outfile, level) outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,)) def exportLiteralAttributes(self, outfile, level, already_processed, name_): if self.message is not None and 'message' not in already_processed: already_processed.append('message') showIndent(outfile, level) outfile.write('message = "%s",\n' % (self.message,)) if self.type_ is not None and 'type_' not in already_processed: already_processed.append('type_') showIndent(outfile, level) outfile.write('type_ = "%s",\n' % (self.type_,)) def exportLiteralChildren(self, outfile, level, name_): pass def build(self, node): self.buildAttributes(node, node.attrib, []) self.valueOf_ = get_all_text_(node) for child in node: nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] self.buildChildren(child, node, nodeName_) def buildAttributes(self, node, attrs, already_processed): value = find_attr_value_('message', node) if value is not None and 'message' not in already_processed: already_processed.append('message') self.message = value value = find_attr_value_('type', node) if value is not None and 'type' not in already_processed: already_processed.append('type') self.type_ = value def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): pass # end class errorType class failureType(GeneratedsSuper): """The message specified in the assertThe type of the assert.""" subclass = None superclass = None def __init__(self, message=None, type_=None, valueOf_=None): self.message = _cast(None, message) self.type_ = _cast(None, type_) self.valueOf_ = valueOf_ def factory(*args_, **kwargs_): if failureType.subclass: # pylint: disable=E1102 return failureType.subclass(*args_, **kwargs_) else: return failureType(*args_, **kwargs_) factory = staticmethod(factory) def get_message(self): return self.message def set_message(self, message): self.message = message def get_type(self): return self.type_ def set_type(self, type_): self.type_ = type_ def get_valueOf_(self): return self.valueOf_ def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='failureType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) already_processed = [] self.exportAttributes(outfile, level, already_processed, namespace_, name_='failureType') if self.hasContent_(): outfile.write('>') outfile.write(str(self.valueOf_).encode(ExternalEncoding)) self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write('/>\n') def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='failureType'): if self.message is not None and 'message' not in already_processed: already_processed.append('message') outfile.write(' message=%s' % (self.gds_format_string(quote_attrib(self.message).encode(ExternalEncoding), input_name='message'), )) if self.type_ is not None and 'type_' not in already_processed: already_processed.append('type_') outfile.write(' type=%s' % (self.gds_format_string(quote_attrib(self.type_).encode(ExternalEncoding), input_name='type'), )) def exportChildren(self, outfile, level, namespace_='', name_='failureType', fromsubclass_=False): pass def hasContent_(self): if ( self.valueOf_ ): return True else: return False def exportLiteral(self, outfile, level, name_='failureType'): level += 1 self.exportLiteralAttributes(outfile, level, [], name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) showIndent(outfile, level) outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,)) def exportLiteralAttributes(self, outfile, level, already_processed, name_): if self.message is not None and 'message' not in already_processed: already_processed.append('message') showIndent(outfile, level) outfile.write('message = "%s",\n' % (self.message,)) if self.type_ is not None and 'type_' not in already_processed: already_processed.append('type_') showIndent(outfile, level) outfile.write('type_ = "%s",\n' % (self.type_,)) def exportLiteralChildren(self, outfile, level, name_): pass def build(self, node): self.buildAttributes(node, node.attrib, []) self.valueOf_ = get_all_text_(node) for child in node: nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] self.buildChildren(child, node, nodeName_) def buildAttributes(self, node, attrs, already_processed): value = find_attr_value_('message', node) if value is not None and 'message' not in already_processed: already_processed.append('message') self.message = value value = find_attr_value_('type', node) if value is not None and 'type' not in already_processed: already_processed.append('type') self.type_ = value def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): pass # end class failureType USAGE_TEXT = """ Usage: python <Parser>.py [ -s ] <in_xml_file> """ def usage(): print USAGE_TEXT sys.exit(1) def get_root_tag(node): tag = Tag_pattern_.match(node.tag).groups()[-1] rootClass = globals().get(tag) return tag, rootClass def parse(inFileName): doc = parsexml_(inFileName) rootNode = doc.getroot() rootTag, rootClass = get_root_tag(rootNode) if rootClass is None: rootTag = 'testsuite' rootClass = testsuite rootObj = rootClass.factory() rootObj.build(rootNode) # Enable Python to collect the space used by the DOM. doc = None sys.stdout.write('<?xml version="1.0" ?>\n') rootObj.export(sys.stdout, 0, name_=rootTag, namespacedef_='') return rootObj def parseString(inString): from StringIO import StringIO doc = parsexml_(StringIO(inString)) rootNode = doc.getroot() rootTag, rootClass = get_root_tag(rootNode) if rootClass is None: rootTag = 'testsuite' rootClass = testsuite rootObj = rootClass.factory() rootObj.build(rootNode) # Enable Python to collect the space used by the DOM. doc = None sys.stdout.write('<?xml version="1.0" ?>\n') rootObj.export(sys.stdout, 0, name_="testsuite", namespacedef_='') return rootObj def parseLiteral(inFileName): doc = parsexml_(inFileName) rootNode = doc.getroot() rootTag, rootClass = get_root_tag(rootNode) if rootClass is None: rootTag = 'testsuite' rootClass = testsuite rootObj = rootClass.factory() rootObj.build(rootNode) # Enable Python to collect the space used by the DOM. doc = None sys.stdout.write('#from JUnit_api import *\n\n') sys.stdout.write('import JUnit_api as model_\n\n') sys.stdout.write('rootObj = model_.rootTag(\n') rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) sys.stdout.write(')\n') return rootObj def main(): args = sys.argv[1:] if len(args) == 1: parse(args[0]) else: usage() if __name__ == '__main__': #import pdb; pdb.set_trace() main() __all__ = [ "errorType", "failureType", "propertiesType", "propertyType", "system_err", "system_out", "testcaseType", "testsuite", "testsuiteType", "testsuites" ]
joyxu/autotest
client/tools/JUnit_api.py
Python
gpl-2.0
65,100
#include <QFile> #include <QMessageBox> #include "pkg_bind.h" #include "config.h" PkgBind *PkgBind::instance = NULL; /* Constructor */ PkgBind::PkgBind() { loadCommandList(); }; /* Get the unique instance * or create it if there isn't any */ PkgBind *PkgBind::getInstance() { if(instance==NULL) instance = new PkgBind(); return instance; } /* Load the command list from a file */ void PkgBind::loadCommandList() { QString path = PKG_CMD_PATH; QFile file(path); if(file.open(QIODevice::ReadOnly)) { char buffer[1024]; int len; while((len = file.readLine(buffer, sizeof(buffer))) > -1) { if(buffer[len - 1] == '\n') buffer[len - 1] = '\0'; commands << QString(buffer); } printf("[PkgBind::loadCommandList] '%s' loaded\n", path.toLocal8Bit().constData()); }else{ printf("[PkgBind::loadCommandList] '%s' can not be loaded\n", path.toLocal8Bit().constData()); } } /* Check if a symbol is defined * as a funciont included in some package */ bool PkgBind::checkSymbol(const QString &s) { return commands.contains(s); } /* Invoke the package manager * for install the package with the command * "cmd" */ void PkgBind::invokePackageManager(const QString &s) { QMessageBox *msgBox = new QMessageBox(QMessageBox::Question, "Package Manager", "There is a package that provides the command '" + s + "'\n" "Do you want to try to install it now?", QMessageBox::Yes | QMessageBox::No); invokeCmd = QString("qtoctave_pkg -s ") + s + "&"; connect(msgBox, SIGNAL(finished(int)), this, SLOT(invokeResponse(int))); msgBox->show(); } /* The dialog response */ void PkgBind::invokeResponse(int result) { if(result == QMessageBox::Yes) system(invokeCmd.toLocal8Bit().constData()); }
luisivan/QtOctave
qtoctave/src/pkg_bind.cpp
C++
gpl-2.0
1,792
<?php die("Access Denied"); ?>#x#a:2:{s:6:"output";s:0:"";s:6:"result";s:4:"9243";}
jolay/pesatec
cache/mod_vvisit_counter/860aea6b5aac75573e8d7d8ebc839c97-cache-mod_vvisit_counter-12c8414db0decbe26a3df6aa66213421.php
PHP
gpl-2.0
83
#include "SampleCode.h" #include "SkView.h" #include "SkBlurMaskFilter.h" #include "SkCanvas.h" #include "SkGradientShader.h" #include "SkGraphics.h" #include "SkImageDecoder.h" #include "SkPath.h" #include "SkRandom.h" #include "SkRegion.h" #include "SkShader.h" #include "SkUtils.h" #include "SkXfermode.h" #include "SkColorPriv.h" #include "SkColorFilter.h" #include "SkTime.h" #include "SkTypeface.h" #include "SkTextBox.h" #include "SkOSFile.h" #include "SkStream.h" #include "SkSVGParser.h" class SVGView : public SkView { public: SVGView() { SkXMLParserError err; SkFILEStream stream("/testsvg2.svg"); SkSVGParser parser(&err); if (parser.parse(stream)) { const char* text = parser.getFinal(); SkFILEWStream output("/testanim.txt"); output.write(text, strlen(text)); } } protected: // overrides from SkEventSink virtual bool onQuery(SkEvent* evt) { if (SampleCode::TitleQ(*evt)) { SkString str("SVG"); SampleCode::TitleR(evt, str.c_str()); return true; } return this->INHERITED::onQuery(evt); } void drawBG(SkCanvas* canvas) { canvas->drawColor(SK_ColorWHITE); } virtual void onDraw(SkCanvas* canvas) { this->drawBG(canvas); } virtual SkView::Click* onFindClickHandler(SkScalar x, SkScalar y) { return new Click(this); } virtual bool onClick(Click* click) { int y = click->fICurr.fY; if (y < 0) { y = 0; } else if (y > 255) { y = 255; } fByte = y; this->inval(NULL); return true; } private: int fByte; typedef SkView INHERITED; }; ////////////////////////////////////////////////////////////////////////////// static SkView* MyFactory() { return new SVGView; } static SkViewRegister reg(MyFactory);
highfellow/inkscape-remove-duplicates
app/main.cpp
C++
gpl-2.0
2,030
// We do this in this rather complicated manner since Joomla groups // external javascript includes and script declarations seperately // and this call has to be made right after loading jQuery. jQuery.noConflict();
lau-ibarra/ETISIGChacoJoomla
tmp/install_515c4270221dc/plg_system_jquery/site/jquery/no_conflict.js
JavaScript
gpl-2.0
218
<?php /** * Magento * * 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 license@magentocommerce.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magentocommerce.com for more information. * * @category Mage * @package Mage_Catalog * @copyright Copyright (c) 2008 Irubin Consulting Inc. DBA Varien (http://www.varien.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /** * Catalog entity abstract model * * @category Mage * @package Mage_Catalog * @author Magento Core Team <core@magentocommerce.com> */ abstract class Mage_Catalog_Model_Resource_Eav_Mysql4_Abstract extends Mage_Eav_Model_Entity_Abstract { /** * Redeclare attribute model * * @return string */ protected function _getDefaultAttributeModel() { return 'catalog/resource_eav_attribute'; } public function getDefaultStoreId() { return Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID; } /** * Check whether the attribute is Applicable to the object * * @param Varien_Object $object * @param Mage_Catalog_Model_Resource_Eav_Attribute $attribute * @return boolean */ protected function _isApplicableAttribute ($object, $attribute) { $applyTo = $attribute->getApplyTo(); return count($applyTo) == 0 || in_array($object->getTypeId(), $applyTo); } /** * Retrieve select object for loading entity attributes values * * Join attribute store value * * @param Varien_Object $object * @param mixed $rowId * @return Zend_Db_Select */ protected function _getLoadAttributesSelect($object, $table) { /** * This condition is applicable for all cases when we was work in not single * store mode, customize some value per specific store view and than back * to single store mode. We should load correct values */ if (Mage::app()->isSingleStoreMode()) { $storeId = Mage::app()->getStore(true)->getId(); } else { $storeId = $object->getStoreId(); } $select = $this->_read->select() ->from(array('default' => $table)); if ($setId = $object->getAttributeSetId()) { $select->join( array('set_table' => $this->getTable('eav/entity_attribute')), 'default.attribute_id=set_table.attribute_id AND ' . 'set_table.attribute_set_id=' . intval($setId), array() ); } $joinCondition = 'main.attribute_id=default.attribute_id AND ' . $this->_read->quoteInto('main.store_id=? AND ', intval($storeId)) . $this->_read->quoteInto('main.'.$this->getEntityIdField() . '=?', $object->getId()); $select->joinLeft( array('main' => $table), $joinCondition, array( 'store_value_id' => 'value_id', 'store_value' => 'value' )) ->where('default.'.$this->getEntityIdField() . '=?', $object->getId()) ->where('default.store_id=?', $this->getDefaultStoreId()); return $select; } /** * Initialize attribute value for object * * @param Varien_Object $object * @param array $valueRow * @return Mage_Eav_Model_Entity_Abstract */ protected function _setAttribteValue($object, $valueRow) { parent::_setAttribteValue($object, $valueRow); if ($attribute = $this->getAttribute($valueRow['attribute_id'])) { $attributeCode = $attribute->getAttributeCode(); if (isset($valueRow['store_value'])) { $object->setAttributeDefaultValue($attributeCode, $valueRow['value']); $object->setData($attributeCode, $valueRow['store_value']); $attribute->getBackend()->setValueId($valueRow['store_value_id']); } } return $this; } /** * Insert entity attribute value * * Insert attribute value we do only for default store * * @param Varien_Object $object * @param Mage_Eav_Model_Entity_Attribute_Abstract $attribute * @param mixed $value * @return Mage_Eav_Model_Entity_Abstract */ protected function _insertAttribute($object, $attribute, $value) { $entityIdField = $attribute->getBackend()->getEntityIdField(); $row = array( $entityIdField => $object->getId(), 'entity_type_id'=> $object->getEntityTypeId(), 'attribute_id' => $attribute->getId(), 'value' => $this->_prepareValueForSave($value, $attribute), 'store_id' => $this->getDefaultStoreId() ); $fields = array(); $values = array(); foreach ($row as $k => $v) { $fields[] = $this->_getWriteAdapter()->quoteIdentifier('?', $k); $values[] = $this->_getWriteAdapter()->quoteInto('?', $v); } $sql = sprintf('INSERT IGNORE INTO %s (%s) VALUES(%s)', $this->_getWriteAdapter()->quoteIdentifier($attribute->getBackend()->getTable()), join(',', array_keys($row)), join(',', $values)); $this->_getWriteAdapter()->query($sql); if (!$lastId = $this->_getWriteAdapter()->lastInsertId()) { $select = $this->_getReadAdapter()->select() ->from($attribute->getBackend()->getTable(), 'value_id') ->where($entityIdField . '=?', $row[$entityIdField]) ->where('entity_type_id=?', $row['entity_type_id']) ->where('attribute_id=?', $row['attribute_id']) ->where('store_id=?', $row['store_id']); $lastId = $select->query()->fetchColumn(); } if ($object->getStoreId() != $this->getDefaultStoreId()) { $this->_updateAttribute($object, $attribute, $lastId, $value); } return $this; } /** * Update entity attribute value * * @param Varien_Object $object * @param Mage_Eav_Model_Entity_Attribute_Abstract $attribute * @param mixed $valueId * @param mixed $value * @return Mage_Eav_Model_Entity_Abstract */ protected function _updateAttribute($object, $attribute, $valueId, $value) { /** * If we work in single store mode all values should be saved just * for default store id * In this case we clear all not default values */ if (Mage::app()->isSingleStoreMode()) { $this->_getWriteAdapter()->delete( $attribute->getBackend()->getTable(), $this->_getWriteAdapter()->quoteInto('attribute_id=?', $attribute->getId()) . $this->_getWriteAdapter()->quoteInto(' AND entity_id=?', $object->getId()) . $this->_getWriteAdapter()->quoteInto(' AND store_id!=?', Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID) ); } /** * Update attribute value for store */ if ($attribute->isScopeStore()) { $this->_updateAttributeForStore($object, $attribute, $value, $object->getStoreId()); } /** * Update attribute value for website */ elseif ($attribute->isScopeWebsite()) { if ($object->getStoreId() == 0) { $this->_updateAttributeForStore($object, $attribute, $value, $object->getStoreId()); } else { if (is_array($object->getWebsiteStoreIds())) { foreach ($object->getWebsiteStoreIds() as $storeId) { $this->_updateAttributeForStore($object, $attribute, $value, $storeId); } } } } else { $this->_getWriteAdapter()->update($attribute->getBackend()->getTable(), array('value' => $this->_prepareValueForSave($value, $attribute)), 'value_id='.(int)$valueId ); } return $this; } /** * Update attribute value for specific store * * @param Mage_Catalog_Model_Abstract $object * @param object $attribute * @param mixed $value * @param int $storeId * @return Mage_Catalog_Model_Resource_Eav_Mysql4_Abstract */ protected function _updateAttributeForStore($object, $attribute, $value, $storeId) { $entityIdField = $attribute->getBackend()->getEntityIdField(); $select = $this->_getWriteAdapter()->select() ->from($attribute->getBackend()->getTable(), 'value_id') ->where('entity_type_id=?', $object->getEntityTypeId()) ->where("$entityIdField=?",$object->getId()) ->where('store_id=?', $storeId) ->where('attribute_id=?', $attribute->getId()); /** * When value for store exist */ if ($valueId = $this->_getWriteAdapter()->fetchOne($select)) { $this->_getWriteAdapter()->update($attribute->getBackend()->getTable(), array('value' => $this->_prepareValueForSave($value, $attribute)), 'value_id='.$valueId ); } else { $this->_getWriteAdapter()->insert($attribute->getBackend()->getTable(), array( $entityIdField => $object->getId(), 'entity_type_id'=> $object->getEntityTypeId(), 'attribute_id' => $attribute->getId(), 'value' => $this->_prepareValueForSave($value, $attribute), 'store_id' => $storeId )); } return $this; } /** * Delete entity attribute values * * @param Varien_Object $object * @param string $table * @param array $info * @return Varien_Object */ protected function _deleteAttributes($object, $table, $info) { $entityIdField = $this->getEntityIdField(); $globalValues = array(); $websiteAttributes = array(); $storeAttributes = array(); /** * Separate attributes by scope */ foreach ($info as $itemData) { $attribute = $this->getAttribute($itemData['attribute_id']); if ($attribute->isScopeStore()) { $storeAttributes[] = $itemData['attribute_id']; } elseif ($attribute->isScopeWebsite()) { $websiteAttributes[] = $itemData['attribute_id']; } else { $globalValues[] = $itemData['value_id']; } } /** * Delete global scope attributes */ if (!empty($globalValues)) { $condition = $this->_getWriteAdapter()->quoteInto('value_id IN (?)', $globalValues); $this->_getWriteAdapter()->delete($table, $condition); } $condition = $this->_getWriteAdapter()->quoteInto("$entityIdField=?", $object->getId()) . $this->_getWriteAdapter()->quoteInto(' AND entity_type_id=?', $object->getEntityTypeId()); /** * Delete website scope attributes */ if (!empty($websiteAttributes)) { $storeIds = $object->getWebsiteStoreIds(); if (!empty($storeIds)) { $delCondition = $condition . $this->_getWriteAdapter()->quoteInto(' AND attribute_id IN(?)', $websiteAttributes) . $this->_getWriteAdapter()->quoteInto(' AND store_id IN(?)', $storeIds); $this->_getWriteAdapter()->delete($table, $delCondition); } } /** * Delete store scope attributes */ if (!empty($storeAttributes)) { $delCondition = $condition . $this->_getWriteAdapter()->quoteInto(' AND attribute_id IN(?)', $storeAttributes) . $this->_getWriteAdapter()->quoteInto(' AND store_id =?', $object->getStoreId()); $this->_getWriteAdapter()->delete($table, $delCondition);; } return $this; } protected function _getOrigObject($object) { $className = get_class($object); $origObject = new $className(); $origObject->setData(array()); $origObject->setStoreId($object->getStoreId()); $this->load($origObject, $object->getData($this->getEntityIdField())); return $origObject; } protected function _collectOrigData($object) { $this->loadAllAttributes($object); if ($this->getUseDataSharing()) { $storeId = $object->getStoreId(); } else { $storeId = $this->getStoreId(); } $allStores = Mage::getConfig()->getStoresConfigByPath('system/store/id', array(), 'code'); //echo "<pre>".print_r($allStores ,1)."</pre>"; exit; $data = array(); foreach ($this->getAttributesByTable() as $table=>$attributes) { $entityIdField = current($attributes)->getBackend()->getEntityIdField(); $select = $this->_read->select() ->from($table) ->where($this->getEntityIdField()."=?", $object->getId()); $where = $this->_read->quoteInto("store_id=?", $storeId); $globalAttributeIds = array(); foreach ($attributes as $attrCode=>$attr) { if ($attr->getIsGlobal()) { $globalAttributeIds[] = $attr->getId(); } } if (!empty($globalAttributeIds)) { $where .= ' or '.$this->_read->quoteInto('attribute_id in (?)', $globalAttributeIds); } $select->where($where); $values = $this->_read->fetchAll($select); if (empty($values)) { continue; } foreach ($values as $row) { $data[$this->getAttribute($row['attribute_id'])->getName()][$row['store_id']] = $row; } foreach ($attributes as $attrCode=>$attr) { } } return $data; } }
tonio-44/tikflak
shop/app/code/core/Mage/Catalog/Model/Resource/Eav/Mysql4/Abstract.php
PHP
gpl-2.0
14,799
/** * Copyright (c) 2009 Pyxis Technologies inc. * * This 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 software 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, * or see the FSF site: http://www.fsf.org. */ package com.greenpepper.interpreter.flow.scenario; import com.greenpepper.converter.*; public class ExpectationTypeConverter extends AbstractTypeConverter { @SuppressWarnings("unchecked") public boolean canConvertTo(Class type) { return Expectation.class.isAssignableFrom( type ); } protected Object doConvert(String value) { return new Expectation( value ); } }
hwellmann/greenpepper-core
src/main/java/com/greenpepper/interpreter/flow/scenario/ExpectationTypeConverter.java
Java
gpl-2.0
1,216