text
stringlengths
2
100k
meta
dict
#region File Description //----------------------------------------------------------------------------- // KeyFrameSequence.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Collections.Generic; using System.Text; using Microsoft.Xna.Framework; using RobotGameData.Helper; #endregion namespace RobotGameData.GameObject { #region enum public enum AnimPlayMode { /// <summary> /// plays once. /// </summary> Once = 0, /// <summary> /// keeps repeating. /// </summary> Repeat, } #endregion #region key frame data /// <summary> /// key data of animation for one frame /// </summary> public struct KeyFrame { public bool HasTranslation; public bool HasRotation; public bool HasScale; public Vector3 Translation; public Quaternion Rotation; public Vector3 Scale; } #endregion /// <summary> /// this is the basic unit of animation which has single bone key frame. /// It calculates by interpolating two key frames. /// </summary> [Serializable] public class KeyFrameSequence { #region Fields public String BoneName = String.Empty; /// <summary> /// Key frame count /// </summary> public int KeyCount = 0; /// <summary> /// Animation playing time /// </summary> public float Duration = 0.0f; /// <summary> /// Gap of time for the each frame. /// </summary> public float KeyInterval = 0.0f; public bool HasTranslation = false; public bool HasRotation = false; public bool HasScale = false; public bool HasTime = false; /// <summary> /// If this flag is set to true, the first key frame’s translation value will be /// fixed during all key frame of the animation. /// </summary> public bool FixedTranslation = false; /// <summary> /// If this flag is set to true, the first key frame’s rotaion value will be /// fixed during all key frame of the animation. /// </summary> public bool FixedRotation = false; /// <summary> /// If this flag is set to true, the first key frame’s scale value will be /// fixed during all key frame of the animation. /// </summary> public bool FixedScale = false; /// <summary> /// The translation value in the list. /// </summary> public List<Vector3> Translation = null; /// <summary> /// The rotation value in the list. /// </summary> public List<Quaternion> Rotation = null; /// <summary> /// The scale value in the list. /// </summary> public List<Vector3> Scale = null; /// <summary> /// The time value in the list. /// </summary> public List<float> Time = null; #endregion /// <summary> /// Gets a key frame matrix by index /// </summary> /// <param name="keyIndex">key frame index</param> /// <returns></returns> public Matrix GetMatrix(int keyIndex) { Matrix mat = Matrix.Identity; if (HasRotation ) // Calculates rotation matrix using quaternion { if (FixedRotation ) mat = Matrix.CreateFromQuaternion(Rotation[0]); else mat = Matrix.CreateFromQuaternion(Rotation[keyIndex]); } if (HasTranslation ) // Calculates position { if (FixedRotation ) mat.Translation = Translation[0]; else mat.Translation = Translation[keyIndex]; } if (HasScale ) // Calculates scale { if (FixedRotation ) mat = mat * Matrix.CreateScale(Scale[0]); else mat = mat * Matrix.CreateScale(Scale[keyIndex]); } return mat; } /// <summary> /// calculates by interpolating two key frames. /// </summary> /// <param name="keyIndex1">key frame index 1</param> /// <param name="keyIndex2">key frame index 2</param> /// <param name="t">interpolate time (0.0 to 1.0)</param> /// <returns>Interpolated key frame matrix</returns> public Matrix GetInterpolateMatrix(int keyIndex1, int keyIndex2, float t) { // Calculate KeyFrame interpolated matrix Matrix mat = Matrix.Identity; // Interpolate rotation value by Slerp if (HasRotation ) { Quaternion q = Quaternion.Identity; if (FixedRotation ) q = Rotation[0]; else q = Quaternion.Slerp(Rotation[keyIndex1], Rotation[keyIndex2], t); // Apply interpolate rotation to matrix mat = Matrix.CreateFromQuaternion(q); } // Interpolate translation value by Lerp if (HasTranslation ) { // Apply interpolate translation to matrix if (FixedTranslation ) mat.Translation = Translation[0]; else mat.Translation = Vector3.Lerp(Translation[keyIndex1], Translation[keyIndex2], t); } // Interpolate scale value by Lerp if (HasScale ) { Vector3 v = Vector3.Zero; if (FixedScale ) v = Scale[0]; else v = Vector3.Lerp(Scale[keyIndex1], Scale[keyIndex2], t); // Apply interpolate scale to matrix mat = mat * Matrix.CreateScale(v); } return mat; } /// <summary> /// calculates by interpolating two key frames. /// </summary> /// <param name="keyIndex1">key frame index 1</param> /// <param name="keyIndex2">key frame index 2</param> /// <param name="t">interpolate time (0.0 to 1.0)</param> /// <returns>Interpolated key frame</returns> public KeyFrame GetInterpolateKeyFrame(int keyIndex1, int keyIndex2, float t) { // Calculate KeyFrame interpolated matrix KeyFrame keyFrame; // Interpolate rotation value by Slerp if (HasRotation ) { if (FixedRotation ) keyFrame.Rotation = Rotation[0]; else keyFrame.Rotation = Quaternion.Slerp( Rotation[keyIndex1], Rotation[keyIndex2], t); } else { keyFrame.Rotation = Quaternion.Identity; } keyFrame.HasRotation = HasRotation; // Interpolate translation value by Lerp if (HasTranslation ) { if (FixedTranslation ) keyFrame.Translation = Translation[0]; else keyFrame.Translation = Vector3.Lerp( Translation[keyIndex1], Translation[keyIndex2], t); } else { keyFrame.Translation = Vector3.Zero; } keyFrame.HasTranslation = HasTranslation; // Interpolate scale value by Lerp if (HasScale ) { if (FixedScale ) keyFrame.Scale = Scale[0]; else keyFrame.Scale = Vector3.Lerp(Scale[keyIndex1], Scale[keyIndex2], t); } else { keyFrame.Scale = Vector3.One; } keyFrame.HasScale = HasScale; return keyFrame; } public Matrix GetInterpolateMatrix(float localTime, AnimPlayMode mode) { int index1 = 0; // first key frame index int index2 = 0; // second key frame index float interpolateTime = 0.0f; CalculateKeyFrameIndex(localTime, mode, out index1, out index2, out interpolateTime); // Calcurate interpolate key frame matrix between KeyFrame1 and KeyFrame2 return GetInterpolateMatrix(index1, index2, interpolateTime); } public KeyFrame GetInterpolateKeyFrame(float localTime, AnimPlayMode mode) { int index1 = 0; // first key frame index int index2 = 0; // second key frame index float interpolateTime = 0.0f; CalculateKeyFrameIndex(localTime, mode, out index1, out index2, out interpolateTime); // Calcurate interpolate key frame matrix between KeyFrame1 and KeyFrame2 return GetInterpolateKeyFrame(index1, index2, interpolateTime); } /// <summary> /// returns two key frame index, which is included in the specified time. /// </summary> public void CalculateKeyFrameIndex(float localTime, AnimPlayMode mode, out int index1, out int index2, out float interpolateTime) { index1 = 0; // first key frame index index2 = 0; // second key frame index interpolateTime = 0.0f; // Calculate first key frame index if (HasTime ) index1 = GetKeyFrameIndex(localTime); else index1 = (int)(localTime / KeyInterval); // Calculate second key frame index by play mode switch (mode) { case AnimPlayMode.Once: // Just play once { // if index1 is last index index2 = (index1 >= KeyCount - 1 ? index1 : index1 + 1); } break; case AnimPlayMode.Repeat: // Play looping { // if index1 is last index, index2 must be begin (looping) index2 = (index1 >= KeyCount - 1 ? 0 : index1 + 1); } break; default: throw new NotSupportedException("Not supported play mode"); } if (index1 >= KeyCount - 1) { index1 = index2 = KeyCount - 1; interpolateTime = 1.0f; } else { if (HasTime ) { interpolateTime = (localTime - Time[index1]) / (Time[index2] - Time[index1]); } else { interpolateTime = HelperMath.CalculateModulo(localTime, KeyInterval) / KeyInterval; } } } /// <summary> /// returns two key frame index, which is included in the specified time. /// </summary> public int GetKeyFrameIndex(float localTime) { // Calculate index between two key frame on this time int startIndex, endIndex, middleIndex; startIndex = 0; endIndex = KeyCount - 1; if (localTime >= Time[endIndex]) { return endIndex; } do { middleIndex = (startIndex + endIndex) / 2; if ((endIndex - startIndex) <= 1) { break; } else if (Time[middleIndex] < localTime) { startIndex = middleIndex; } else if (Time[middleIndex] > localTime) { endIndex = middleIndex; } else { startIndex = middleIndex; break; } } while ((endIndex - startIndex) > 1); return startIndex; } } }
{ "pile_set_name": "Github" }
/* SPDX-License-Identifier: GPL-2.0-only */ /* Copyright (c) 2016-2018, The Linux Foundation. All rights reserved. */ #ifndef _DPU_CORE_PERF_H_ #define _DPU_CORE_PERF_H_ #include <linux/types.h> #include <linux/dcache.h> #include <linux/mutex.h> #include <drm/drm_crtc.h> #include "dpu_hw_catalog.h" #define DPU_PERF_DEFAULT_MAX_CORE_CLK_RATE 412500000 /** * enum dpu_core_perf_data_bus_id - data bus identifier * @DPU_CORE_PERF_DATA_BUS_ID_MNOC: DPU/MNOC data bus * @DPU_CORE_PERF_DATA_BUS_ID_LLCC: MNOC/LLCC data bus * @DPU_CORE_PERF_DATA_BUS_ID_EBI: LLCC/EBI data bus */ enum dpu_core_perf_data_bus_id { DPU_CORE_PERF_DATA_BUS_ID_MNOC, DPU_CORE_PERF_DATA_BUS_ID_LLCC, DPU_CORE_PERF_DATA_BUS_ID_EBI, DPU_CORE_PERF_DATA_BUS_ID_MAX, }; /** * struct dpu_core_perf_params - definition of performance parameters * @max_per_pipe_ib: maximum instantaneous bandwidth request * @bw_ctl: arbitrated bandwidth request * @core_clk_rate: core clock rate request */ struct dpu_core_perf_params { u64 max_per_pipe_ib; u64 bw_ctl; u64 core_clk_rate; }; /** * struct dpu_core_perf_tune - definition of performance tuning control * @mode: performance mode * @min_core_clk: minimum core clock * @min_bus_vote: minimum bus vote */ struct dpu_core_perf_tune { u32 mode; u64 min_core_clk; u64 min_bus_vote; }; /** * struct dpu_core_perf - definition of core performance context * @dev: Pointer to drm device * @debugfs_root: top level debug folder * @catalog: Pointer to catalog configuration * @core_clk: Pointer to core clock structure * @core_clk_rate: current core clock rate * @max_core_clk_rate: maximum allowable core clock rate * @perf_tune: debug control for performance tuning * @enable_bw_release: debug control for bandwidth release * @fix_core_clk_rate: fixed core clock request in Hz used in mode 2 * @fix_core_ib_vote: fixed core ib vote in bps used in mode 2 * @fix_core_ab_vote: fixed core ab vote in bps used in mode 2 */ struct dpu_core_perf { struct drm_device *dev; struct dentry *debugfs_root; struct dpu_mdss_cfg *catalog; struct dss_clk *core_clk; u64 core_clk_rate; u64 max_core_clk_rate; struct dpu_core_perf_tune perf_tune; u32 enable_bw_release; u64 fix_core_clk_rate; u64 fix_core_ib_vote; u64 fix_core_ab_vote; }; /** * dpu_core_perf_crtc_check - validate performance of the given crtc state * @crtc: Pointer to crtc * @state: Pointer to new crtc state * return: zero if success, or error code otherwise */ int dpu_core_perf_crtc_check(struct drm_crtc *crtc, struct drm_crtc_state *state); /** * dpu_core_perf_crtc_update - update performance of the given crtc * @crtc: Pointer to crtc * @params_changed: true if crtc parameters are modified * @stop_req: true if this is a stop request * return: zero if success, or error code otherwise */ int dpu_core_perf_crtc_update(struct drm_crtc *crtc, int params_changed, bool stop_req); /** * dpu_core_perf_crtc_release_bw - release bandwidth of the given crtc * @crtc: Pointer to crtc */ void dpu_core_perf_crtc_release_bw(struct drm_crtc *crtc); /** * dpu_core_perf_destroy - destroy the given core performance context * @perf: Pointer to core performance context */ void dpu_core_perf_destroy(struct dpu_core_perf *perf); /** * dpu_core_perf_init - initialize the given core performance context * @perf: Pointer to core performance context * @dev: Pointer to drm device * @catalog: Pointer to catalog * @core_clk: pointer to core clock */ int dpu_core_perf_init(struct dpu_core_perf *perf, struct drm_device *dev, struct dpu_mdss_cfg *catalog, struct dss_clk *core_clk); struct dpu_kms; /** * dpu_core_perf_debugfs_init - initialize debugfs for core performance context * @dpu_kms: Pointer to the dpu_kms struct * @debugfs_parent: Pointer to parent debugfs */ int dpu_core_perf_debugfs_init(struct dpu_kms *dpu_kms, struct dentry *parent); #endif /* _DPU_CORE_PERF_H_ */
{ "pile_set_name": "Github" }
/** @file * * @par History * - 2005/06/01 Shinigami: added getmapshapes - to get access to mapshapes * - added getstatics - to fill a list with statics * - 2005/06/06 Shinigami: added readmultis derivative - to get a list of statics */ #ifndef POL_REALM_H #define POL_REALM_H #include <memory> #include <set> #include <stddef.h> #include <string> #include <vector> #include "plib/mapshape.h" #include "plib/realmdescriptor.h" #include "plib/uconst.h" #include "plib/udatfile.h" #include "realms/WorldChangeReasons.h" namespace Pol { namespace Core { class ItemsVector; class ULWObject; struct Zone; } namespace Mobile { class Character; } namespace Items { class Item; } namespace Multi { class UMulti; } namespace Plib { class MapServer; class MapTileServer; class StaticEntryList; class StaticServer; struct MAPTILE_CELL; } namespace Realms { typedef std::vector<Multi::UMulti*> MultiList; class Realm { public: explicit Realm( const std::string& realm_name, const std::string& realm_path = "" ); explicit Realm( const std::string& realm_name, Realm* realm ); ~Realm(); bool is_shadowrealm; unsigned int shadowid; Realm* baserealm; const std::string shadowname; unsigned short width() const; unsigned short height() const; unsigned short grid_width() const; unsigned short grid_height() const; unsigned season() const; bool valid( unsigned short x, unsigned short y, short z ) const; const std::string name() const; // functions to broadcast entered- and leftarea events to items and npcs in the realm void notify_moved( Mobile::Character& whomoved ); void notify_unhid( Mobile::Character& whounhid ); void notify_resurrected( Mobile::Character& whoressed ); void notify_entered( Mobile::Character& whoentered ); void notify_left( Mobile::Character& wholeft ); void add_mobile( const Mobile::Character& chr, WorldChangeReason reason ); void remove_mobile( const Mobile::Character& chr, WorldChangeReason reason ); void add_toplevel_item( const Items::Item& item ); void remove_toplevel_item( const Items::Item& item ); void add_multi( const Multi::UMulti& multi ); void remove_multi( const Multi::UMulti& multi ); unsigned int mobile_count() const; unsigned int offline_mobile_count() const; unsigned int toplevel_item_count() const; unsigned int multi_count() const; bool walkheight( unsigned short x, unsigned short y, short oldz, short* newz, Multi::UMulti** pmulti, Items::Item** pwalkon, bool doors_block, Plib::MOVEMODE movemode, short* gradual_boost = nullptr ); bool walkheight( const Mobile::Character* chr, unsigned short x, unsigned short y, short oldz, short* newz, Multi::UMulti** pmulti, Items::Item** pwalkon, short* gradual_boost = nullptr ); bool lowest_walkheight( unsigned short x, unsigned short y, short oldz, short* newz, Multi::UMulti** pmulti, Items::Item** pwalkon, bool doors_block, Plib::MOVEMODE movemode, short* gradual_boost = nullptr ); bool dropheight( unsigned short dropx, unsigned short dropy, short dropz, short chrz, short* newz, Multi::UMulti** pmulti ); bool has_los( const Core::ULWObject& att, const Core::ULWObject& tgt ) const; bool navigable( unsigned short x, unsigned short y, short z, short height ) const; Multi::UMulti* find_supporting_multi( unsigned short x, unsigned short y, short z ) const; bool lowest_standheight( unsigned short x, unsigned short y, short* z ) const; bool findstatic( unsigned short x, unsigned short y, unsigned short objtype ) const; void getstatics( Plib::StaticEntryList& statics, unsigned short x, unsigned short y ) const; bool groundheight( unsigned short x, unsigned short y, short* z ) const; Plib::MAPTILE_CELL getmaptile( unsigned short x, unsigned short y ) const; void getmapshapes( Plib::MapShapeList& shapes, unsigned short x, unsigned short y, unsigned int anyflags ) const; void readmultis( Plib::MapShapeList& vec, unsigned short x, unsigned short y, unsigned int flags ) const; void readmultis( Plib::MapShapeList& vec, unsigned short x, unsigned short y, unsigned int flags, MultiList& mvec ) const; void readmultis( Plib::StaticList& vec, unsigned short x, unsigned short y ) const; Core::Zone** zone; std::set<unsigned int> global_hulls; // xy-smashed together unsigned getUOMapID() const; unsigned getNumStaticPatches() const; unsigned getNumMapPatches() const; static unsigned int encode_global_hull( unsigned short ax, unsigned short ay ); protected: struct LosCache { LosCache() : last_x( 0 ), last_y( 0 ), shapes(), dyn_items(){}; unsigned short last_x; unsigned short last_y; Plib::MapShapeList shapes; std::vector<Items::Item*> dyn_items; }; static void standheight( Plib::MOVEMODE movemode, Plib::MapShapeList& shapes, short oldz, bool* result, short* newz, short* gradual_boost = nullptr ); static void lowest_standheight( Plib::MOVEMODE movemode, Plib::MapShapeList& shapes, short oldz, bool* result, short* newz, short* gradual_boost = nullptr ); static bool dropheight( Plib::MapShapeList& shapes, short dropz, short chrz, short* newz ); void readdynamics( Plib::MapShapeList& vec, unsigned short x, unsigned short y, Core::ItemsVector& walkon_items, bool doors_block ); static bool dynamic_item_blocks_los( unsigned short x, unsigned short y, short z, LosCache& cache ); bool static_item_blocks_los( unsigned short x, unsigned short y, short z, LosCache& cache ) const; bool los_blocked( const Core::ULWObject& att, const Core::ULWObject& target, unsigned short x, unsigned short y, short z, LosCache& cache ) const; Multi::UMulti* find_supporting_multi( MultiList& mvec, short z ) const; private: const Plib::RealmDescriptor _descriptor; unsigned int _mobile_count; unsigned int _offline_count; unsigned int _toplevel_item_count; unsigned int _multi_count; std::unique_ptr<Plib::MapServer> _mapserver; std::unique_ptr<Plib::StaticServer> _staticserver; std::unique_ptr<Plib::MapTileServer> _maptileserver; private: // not implemented: Realm& operator=( const Realm& ); Realm( const Realm& ); public: size_t sizeEstimate() const; }; inline unsigned int Realm::mobile_count() const { return _mobile_count; } inline unsigned int Realm::offline_mobile_count() const { return _offline_count; } inline unsigned int Realm::toplevel_item_count() const { return _toplevel_item_count; } inline unsigned int Realm::multi_count() const { return _multi_count; } inline void Realm::add_toplevel_item( const Items::Item& /*item*/ ) { ++_toplevel_item_count; } inline void Realm::remove_toplevel_item( const Items::Item& /*item*/ ) { --_toplevel_item_count; } inline void Realm::add_multi( const Multi::UMulti& /*multi*/ ) { ++_multi_count; } inline void Realm::remove_multi( const Multi::UMulti& /*multi*/ ) { --_multi_count; } inline unsigned Realm::getUOMapID() const { return _descriptor.uomapid; }; inline unsigned Realm::getNumStaticPatches() const { return _descriptor.num_static_patches; }; inline unsigned Realm::getNumMapPatches() const { return _descriptor.num_map_patches; }; inline unsigned int Realm::encode_global_hull( unsigned short ax, unsigned short ay ) { return ( static_cast<unsigned int>( ax ) << 16 ) | ay; } inline unsigned short Realm::width() const { return _descriptor.width; } inline unsigned short Realm::height() const { return _descriptor.height; } } } #endif
{ "pile_set_name": "Github" }
<refentry xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xi="http://www.w3.org/2001/XInclude" xmlns:src="http://nwalsh.com/xmlns/litprog/fragment" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="5.0" xml:id="callout.defaultcolumn"> <refmeta> <refentrytitle>callout.defaultcolumn</refentrytitle> <refmiscinfo class="other" otherclass="datatype">integer</refmiscinfo> </refmeta> <refnamediv> <refname>callout.defaultcolumn</refname> <refpurpose>Indicates what column callouts appear in by default</refpurpose> </refnamediv> <refsynopsisdiv> <src:fragment xml:id="callout.defaultcolumn.frag"> <xsl:param name="callout.defaultcolumn">60</xsl:param> </src:fragment> </refsynopsisdiv> <refsection><info><title>Description</title></info> <para>If a callout does not identify a column (for example, if it uses the <literal>linerange</literal> <tag class="attribute">unit</tag>), it will appear in the default column. </para> </refsection> </refentry>
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <cobra document="https://github.com/WhaleShark-Team/cobra"> <name value="file_get_contents导致的SSRF"/> <language value="php"/> <match mode="function-param-controllable"><![CDATA[file_get_contents]]></match> <level value="7"/> <test> <case assert="true"><![CDATA[ $url = $_GET['url']; echo file_get_contents($url); ]]></case> <case assert="false"><![CDATA[ $url = "http://www.example.com"; echo file_get_contents($url); ]]></case> </test> <solution> ## 安全风险 SSRF漏洞(Server-Side Request Forgery) ### 形成原理 SSRF形成的原因大都是由于服务端提供了从其他服务器应用获取数据的功能且没有对目标地址做过滤与限制。 ### 风险 1、攻击者可以对外网、服务器所在内网、本地进行端口扫描,获取服务的banner信息。 2、攻击运行在内网或本地的应用程序。 3、对内网web应用进行指纹识别。 4、攻击内外网的web应用。 5、利用file协议读取本地文件等。 ## 修复方案 1. 限制协议为HTTP、HTTPS 2. 限制请求域名白名单 3. 禁止30x跳转 ## 举例 ```php $url = $_GET['url'];; echo file_get_contents($url); //对用户可控的参数没有进行过滤,攻击者恶意构造输入就可能导致SSRF ``` </solution> <status value="on"/> <author name="JoyChou" email="[email protected]"/> </cobra>
{ "pile_set_name": "Github" }
package pipe.gui.widget; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class GenerateResultsForm { /** * Maximum number of threads allowed */ private static final int MAX_THREADS = 100; /** * Error message if processing threads is incorrect */ private static final String THREADS_ERROR_MESSAGE = "Error! Please enter a valid number of threads between 1-" + MAX_THREADS; /** * Action to perform when the go button is pressed */ private final GoAction goAction; /** * Panel containing number of threads and go button */ private JPanel generatePanel; /** * Number of threads text */ private JTextField numberOfThreadsText; /** * Load results button */ private JButton goButton; /** * Main panel containing the generate Panel */ private JPanel mainPanel; public GenerateResultsForm(GoAction goAction) { this.goAction = goAction; goButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { go(); } }); } /** * Attempts to start the specified procedure by gathering the number * of threads to use. If it is not between 1 and MAX_THREADS then we display * and error and do not perform the action */ private void go() { try { int threads = Integer.valueOf(numberOfThreadsText.getText()); if (threads < 1 || threads > MAX_THREADS) { displayThreadErrorMessage(); return; } goAction.go(threads); } catch (NumberFormatException e) { displayThreadErrorMessage(); } } /** * Displays an error message depicting that the number of threads * entered does not conform to the expected values */ private void displayThreadErrorMessage() { JOptionPane.showMessageDialog(mainPanel, THREADS_ERROR_MESSAGE, "GSPN Analysis Error", JOptionPane.ERROR_MESSAGE); } /** * @return panel to add to other GUI's */ public JPanel getPanel() { return mainPanel; } /** * Interface used to programmatically decide what happens when the generate * button is pressed */ public interface GoAction { void go(int threads); } }
{ "pile_set_name": "Github" }
if ('undefined' == typeof window) { module.exports = require('./lib/debug'); } else { module.exports = require('./debug'); }
{ "pile_set_name": "Github" }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.stratos.autoscaler.exception.policy; public class InvalidDeploymentPolicyException extends Exception { private static final long serialVersionUID = -3086971886563007853L; private String message; public InvalidDeploymentPolicyException(String message) { super(message); this.setMessage(message); } public InvalidDeploymentPolicyException(String message, Exception e) { super(message, e); this.setMessage(message); } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
{ "pile_set_name": "Github" }
(function( factory ) { if ( typeof define === "function" && define.amd ) { define( ["jquery", "../jquery.validate"], factory ); } else if (typeof module === "object" && module.exports) { module.exports = factory( require( "jquery" ) ); } else { factory( jQuery ); } }(function( $ ) { /* * Translated default messages for the jQuery validation plugin. * Locale: ID (Indonesia; Indonesian) */ $.extend( $.validator.messages, { required: "Kolom ini diperlukan.", remote: "Harap benarkan kolom ini.", email: "Silakan masukkan format email yang benar.", url: "Silakan masukkan format URL yang benar.", date: "Silakan masukkan format tanggal yang benar.", dateISO: "Silakan masukkan format tanggal(ISO) yang benar.", number: "Silakan masukkan angka yang benar.", digits: "Harap masukan angka saja.", creditcard: "Harap masukkan format kartu kredit yang benar.", equalTo: "Harap masukkan nilai yg sama dengan sebelumnya.", maxlength: $.validator.format( "Input dibatasi hanya {0} karakter." ), minlength: $.validator.format( "Input tidak kurang dari {0} karakter." ), rangelength: $.validator.format( "Panjang karakter yg diizinkan antara {0} dan {1} karakter." ), range: $.validator.format( "Harap masukkan nilai antara {0} dan {1}." ), max: $.validator.format( "Harap masukkan nilai lebih kecil atau sama dengan {0}." ), min: $.validator.format( "Harap masukkan nilai lebih besar atau sama dengan {0}." ) } ); return $; }));
{ "pile_set_name": "Github" }
apiVersion: tekton.dev/v1beta1 kind: TaskRun metadata: name: build-and-push spec: serviceAccountName: build-sa taskRef: name: build-and-push resources: inputs: - name: repo resourceRef: name: cnych-tekton-example
{ "pile_set_name": "Github" }
/* * Copyright 2011 The Apache Software Foundation * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.codefollower.douyu.core; /** * * @author ZHH * */ public class JavacException extends RuntimeException { private static final long serialVersionUID = 1L; public JavacException() { super(); } public JavacException(String message) { super(message); } public JavacException(Throwable cause) { super(cause); } public JavacException(String message, Throwable cause) { super(message, cause); } }
{ "pile_set_name": "Github" }
--- layout: post title: Announcing Scala.js 0.6.13 category: news tags: [releases] permalink: /news/2016/10/17/announcing-scalajs-0.6.13/ --- We are excited to announce the release of Scala.js 0.6.13! This release contains one particularly anticipated feature: the ability to generate CommonJS modules with Scala.js! It also standardizes on Node.js as the default runner for all sbt projects (with `sbt run` and `sbt test`), which constitutes a breaking change for builds. Read on for more details! <!--more--> ## Getting started If you are new to Scala.js, head over to [the tutorial]({{ BASE_PATH }}/tutorial/). ## Release notes As a minor release, 0.6.13 is backward source and binary compatible with previous releases in the 0.6.x series, although *build* definitions are not. Libraries compiled with earlier versions can be used with 0.6.13 without change. However, it is not forward compatible: libraries compiled with 0.6.13 cannot be used by projects using 0.6.{0-12}. Please report any issues [on GitHub](https://github.com/scala-js/scala-js/issues). ## Breaking changes This release changes the default JavaScript interpreters used to perform `sbt run` and `sbt test`. Until 0.6.12 (and since 0.6.6), the defaults were: * Rhino by default * Node.js with `scalaJSUseRhino in Global := false` * PhantomJS with `scalaJSUseRhino in Global := false` and `jsDependencies += RuntimeDOM` The new defaults are the following: * Node.js by default * Node.js + [`jsdom`](https://github.com/jsdom/jsdom) with `jsDependencies += RuntimeDOM` Note that Node.js and jsdom need to be installed separately on your system. * [Download Node.js here](https://nodejs.org/en/download/) * Install jsdom with `npm install jsdom` (either in your project's root directory, or [globally](https://docs.npmjs.com/getting-started/installing-npm-packages-globally)) We decided to standardize on Node.js for all command-line executions by default because it is always the best alternative. Rhino is extremely slow. Although using it by default works out-of-the-box, it caused a number of users to stick to it and discovering months or years later that their tests could run 10x-100x faster by switching to Node.js. PhantomJS, on the other hand, [reportedly suffers from significant issues](https://github.com/scala-js/scala-js/issues/1881). `jsdom` seems to be better maintained at this point. You can restore the previous behaviors with the following sbt settings: * Rhino: `scalaJSUseRhino in Global := true`. Rhino is however *deprecated*, and will not be supported anymore in 1.0.0. * PhantomJS: `jsEnv := PhantomJSEnv().value`. Remember that you can also use Selenium with Scala.js, using [scalajs-env-selenium](https://github.com/scala-js/scala-js-env-selenium). ## Deprecation: `@JSGlobalScope` replaces `extends js.GlobalScope` As indicated by a deprecation warning, `extends js.GlobalScope` should not be used anymore. Instead, you should annotate the object with `@JSGlobalScope`. For example, this old snippet: {% highlight scala %} import scala.scalajs.js @js.native object Foo extends js.GlobalScope {% endhighlight %} should be replaced with {% highlight scala %} import scala.scalajs.js import js.annotation._ @js.native @JSGlobalScope object Foo extends js.Object {% endhighlight %} ## `@JSImport` and emitting CommonJS modules This is a long-awaited feature! Scala.js can now emit CommonJS modules (i.e., those used by Node.js, as well as several bundlers). ### Enabling CommonJS module You can enable emission of a CommonJS module with the following sbt setting: {% highlight scala %} scalaJSModuleKind := ModuleKind.CommonJSModule {% endhighlight %} When emitting a CommonJS module, top-level `@JSExport`ed classes and objects are stored in the `exports` object, so that they can be required from other CommonJS modules. Obviously, this requires that you use Node.js for `sbt run` and `sbt test` (should you use them at all), and that you use a JavaScript bundler such as [Webpack](https://webpack.github.io/docs/) to create a bundle fit for use in the browser. At the moment, Scala.js does not provide any facility to do so. Emitting CommonJS modules is also not compatible with `persistLauncher := true`, as a different launcher needs to be emitted for fastOpt versus fullOpt. You can find more information on module support [in the documentation]({{ BASE_PATH }}/doc/project/module.html). ### Importing stuff from other CommonJS modules To import other CommonJS modules from Scala.js, you should use `@JSImport` ([Scaladoc]({{ site.production_url }}/api/scalajs-library/0.6.13/#scala.scalajs.js.annotation.JSImport)). Semantically speaking, `@JSImport` is an [ECMAScript 2015 import](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import), but Scala.js desugars it into a CommonJS `require`. Let us see an example first: {% highlight scala %} import scala.scalajs.js import js.annotation._ // ES6: import { Foo } from "bar.js" // CommonJS: var Foo = require("bar.js").Foo; @js.native @JSImport("bar.js", "Foo") class Foobaz(var bar: Int) extends js.Object val foo = new Foobaz(5) // JS: new Foo(5) {% endhighlight %} If the module exports top-level functions or variables, you should create an `object` representing the module itself, like this: {% highlight scala %} // ES6: import * as bar from "bar.js" // CommonJS: var bar = require("bar.js"); @js.native @JSImport("bar.js", JSImport.Namespace) object Bar extends js.Object { def aFunction(x: Int): Int = js.native } val result = Bar.aFunction(5) // JS: bar.aFunction(5) {% endhighlight %} Note that importing with `@JSImport` is completely incompatible with the `jsDependencies` mechanism. If you use `@JSImport`, you have to manage your JavaScript dependencies on your own (possibly through `npm`). You can find more information on `@JSImport` [in the facade types documentation]({{ BASE_PATH }}/doc/interoperability/facade-types.html#import). ### New Java libraries * `java.util.Timer` * `java.util.concurrent.atomic.AtomicLongArray` * `java.io.DataInputStream` (was already available with `scalajs-javalib-ex`, but is now available by default) ## Bug fixes Among others, the following bugs have been fixed in 0.6.13: * [#2592](https://github.com/scala-js/scala-js/issues/2592) Yet another String.split() inconcistency * [#2598](https://github.com/scala-js/scala-js/issues/2598) FrameworkDetector swallows the stderr output of the JS env * [#2602](https://github.com/scala-js/scala-js/issues/2602) Linker thinks it's used concurrently when in fact it's been made invalid after an exception * [#2603](https://github.com/scala-js/scala-js/issues/2603) Inner def with default param in a Scala.js-defined JS class produces invalid IR * [#2625](https://github.com/scala-js/scala-js/issues/2625) Outer pointer checks fail in 2.12 (not fixed in 2.12.0-RC1) * [#2382](https://github.com/scala-js/scala-js/issues/2382) Name clash for $outer pointers of two different nesting levels, only for 2.12.0-RC2 onwards (not fixed in 2.10, 2.11, nor 2.12.0-RC1) You can find the full list [on GitHub](https://github.com/scala-js/scala-js/milestone/41?closed=1).
{ "pile_set_name": "Github" }
#ifndef DIFFICULTY_DISPLAY_H #define DIFFICULTY_DISPLAY_H #include "GameConstantsAndTypes.h" #include "Sprite.h" #include "ActorFrame.h" #include "Difficulty.h" class Song; class DifficultyDisplay : public ActorFrame { public: DifficultyDisplay(); void SetDifficulties( const Song* pSong, StepsType curType ); void UnsetDifficulties(); protected: Sprite m_difficulty[NUM_DIFFICULTIES]; }; #endif /* * (c) 2003 Steven Towle * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, and/or sell copies of the Software, and to permit persons to * whom the Software is furnished to do so, provided that the above * copyright notice(s) and this permission notice appear in all copies of * the Software and that both the above copyright notice(s) and this * permission notice appear in supporting documentation. * * 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 OF * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */
{ "pile_set_name": "Github" }
'use strict'; var path = require('path'); var amd = require('amd-optimize'); var vueify = require('vueify'); var through = require('through2'); module.exports = function (basePath) { return amd.loader(function (moduleName) { return path.join(basePath, moduleName); }, function () { var translator = function (file, enc, cb) { var fileContents = file.contents.toString('utf8'); var filePath = file.path; process.env.VUEIFY_TEST = 1; vueify.compiler.compile(fileContents, filePath, function (err, result) { var js = 'define(function (require, exports, module) {\n' + result + '});\n'; file.path = filePath.replace(/\.vue$/, '.js'); file.contents = new Buffer(js); cb(null, file); }); }; return through.obj(translator); }); };
{ "pile_set_name": "Github" }
/* * 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. */ package com.google.gwt.dev.testdata.incrementalbuildsystem; /** * A test class that exists only to give a test module something to compile. */ public class SomeClass { }
{ "pile_set_name": "Github" }
/** * Copyright 2014 the original author or authors. * * Licensed under the Baidu company (the "License"); * you may not use this file except in compliance with the License. * */ package com.baidu.bjf.remoting.protobuf.enumeration; import com.baidu.bjf.remoting.protobuf.FieldType; import com.baidu.bjf.remoting.protobuf.annotation.Protobuf; /** * Simple pojo enumeration class * * @author xiemalin * @since 1.4.0 */ public class EnumPOJOClass { @Protobuf(fieldType = FieldType.ENUM) public EnumAttrPOJO enumAttr; }
{ "pile_set_name": "Github" }
{ "images" : [ { "size" : "20x20", "idiom" : "iphone", "filename" : "[email protected]", "scale" : "2x" }, { "size" : "20x20", "idiom" : "iphone", "filename" : "[email protected]", "scale" : "3x" }, { "size" : "29x29", "idiom" : "iphone", "filename" : "[email protected]", "scale" : "2x" }, { "size" : "29x29", "idiom" : "iphone", "filename" : "[email protected]", "scale" : "3x" }, { "size" : "40x40", "idiom" : "iphone", "filename" : "[email protected]", "scale" : "2x" }, { "size" : "40x40", "idiom" : "iphone", "filename" : "[email protected]", "scale" : "3x" }, { "size" : "60x60", "idiom" : "iphone", "filename" : "[email protected]", "scale" : "2x" }, { "size" : "60x60", "idiom" : "iphone", "filename" : "[email protected]", "scale" : "3x" }, { "size" : "20x20", "idiom" : "ipad", "filename" : "[email protected]", "scale" : "1x" }, { "size" : "20x20", "idiom" : "ipad", "filename" : "[email protected]", "scale" : "2x" }, { "size" : "29x29", "idiom" : "ipad", "filename" : "[email protected]", "scale" : "1x" }, { "size" : "29x29", "idiom" : "ipad", "filename" : "[email protected]", "scale" : "2x" }, { "size" : "40x40", "idiom" : "ipad", "filename" : "[email protected]", "scale" : "1x" }, { "size" : "40x40", "idiom" : "ipad", "filename" : "[email protected]", "scale" : "2x" }, { "size" : "76x76", "idiom" : "ipad", "filename" : "[email protected]", "scale" : "1x" }, { "size" : "76x76", "idiom" : "ipad", "filename" : "[email protected]", "scale" : "2x" }, { "size" : "83.5x83.5", "idiom" : "ipad", "filename" : "[email protected]", "scale" : "2x" }, { "size" : "1024x1024", "idiom" : "ios-marketing", "filename" : "[email protected]", "scale" : "1x" } ], "info" : { "version" : 1, "author" : "xcode" }, "properties" : { "pre-rendered" : true } }
{ "pile_set_name": "Github" }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-2 12H6v-2h12v2zm0-3H6V9h12v2zm0-3H6V6h12v2z" /> , 'Message');
{ "pile_set_name": "Github" }
#ifndef __L1Analysis_L1AnalysisRecoTrackDataFormat_H__ #define __L1Analysis_L1AnalysisRecoTrackDataFormat_H__ //------------------------------------------------------------------------------- // Created 15/04/2010 - E. Conte, A.C. Le Bihan // // // Original code : L1Trigger/L1TNtuples/L1TrackVertexRecoTreeProducer - Jim Brooke //------------------------------------------------------------------------------- #include <vector> namespace L1Analysis { struct L1AnalysisRecoTrackDataFormat { L1AnalysisRecoTrackDataFormat() { Reset(); }; ~L1AnalysisRecoTrackDataFormat() { Reset(); }; void Reset() { nTrk = 0; nHighPurity = 0; fHighPurity = 0.; } unsigned int nTrk; unsigned int nHighPurity; double fHighPurity; }; } // namespace L1Analysis #endif
{ "pile_set_name": "Github" }
/* * Copyright (c) 2014. Marshal Chen. */ package com.marshalchen.common.demoofui.dragSortListview; import com.marshalchen.common.demoofui.R; import com.marshalchen.common.uimodule.dragSortListView.DragSortController; import android.support.v4.app.DialogFragment; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; /** * Simply passes remove mode back to OnOkListener */ public class RemoveModeDialog extends DialogFragment { private int mRemoveMode; private RemoveOkListener mListener; public RemoveModeDialog() { super(); mRemoveMode = DragSortController.FLING_REMOVE; } public RemoveModeDialog(int inRemoveMode) { super(); mRemoveMode = inRemoveMode; } public interface RemoveOkListener { public void onRemoveOkClick(int removeMode); } public void setRemoveOkListener(RemoveOkListener l) { mListener = l; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); // Set the dialog title builder.setTitle(R.string.select_remove_mode) .setSingleChoiceItems(R.array.remove_mode_labels, mRemoveMode, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mRemoveMode = which; } }) // Set the action buttons .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { if (mListener != null) { mListener.onRemoveOkClick(mRemoveMode); } } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { } }); return builder.create(); } }
{ "pile_set_name": "Github" }
.site-navbar { background-color: #333; border: 0px; .navbar-nav > li > a:hover { background-color: @brand-primary; color: #fff; } }
{ "pile_set_name": "Github" }
#ifndef __X86_64_FLOAT_H__ #define __X86_64_FLOAT_H__ /* * values for FLT_EVAL_METHOD * -1 - indeterminable * 0 - evaluate just to the range and precision of the type * 1 - evaluate float and double to the range and precision of double * evaluate long double to its range and precision * 2 - evaluate all operations and constants to the range and precision of * long double */ #undef FLT_EVAL_METHOD #define FLT_EVAL_METHOD 0 #endif /* __X86_64_FLOAT_H__ */
{ "pile_set_name": "Github" }
/* pathtracer.cu - Copyright 2019/2020 Utrecht University Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. This file implements the shading stage of the wavefront algorithm. It takes a buffer of hit results and populates a new buffer with extension rays. Shadow rays are added with 'potential contributions' as fire-and-forget rays, to be traced later. Streams are compacted using simple atomics. The kernel is a 'persistent kernel': a fixed number of threads fights for food by atomically decreasing a counter. The implemented path tracer is deliberately simple. This file is as similar as possible to the one in OptixPrime_B. */ #include "noerrors.h" // path state flags #define S_SPECULAR 1 // previous path vertex was specular #define S_BOUNCED 2 // path encountered a diffuse vertex #define S_VIASPECULAR 4 // path has seen at least one specular vertex // readability defines; data layout is optimized for 128-bit accesses #define PRIMIDX __float_as_int( hitData.z ) #define INSTANCEIDX __float_as_int( hitData.y ) #define HIT_U ((__float_as_uint( hitData.x ) & 65535) * (1.0f / 65535.0f)) #define HIT_V ((__float_as_uint( hitData.x ) >> 16) * (1.0f / 65535.0f)) #define HIT_T hitData.w #define RAY_O make_float3( O4 ) #define FLAGS data #define PATHIDX (data >> 6) // helpers for storing filter data LH2_DEVFUNC void PackFeatures( uint4& features, const uint albedo, const uint packedNormal, const float t, uint isSpecular, uint matid ) { features = make_uint4( albedo, packedNormal, __float_as_uint( t ), (isSpecular << 4) + (matid << 6) + (features.w & 15) /* leave history count intact */ ); } LH2_DEVFUNC void calculateDepthDerivatives( const int x, const int y, const int w, const int h, const float depth, const CoreTri4& tri, float4* deltaDepth, const float3& p1, const float3& p2 /* actually: p2 - p1 */, const float3& p3 /* actually: p3 - p1 */, const float3& pos ) { const float3 triNormal = make_float3( tri.vN0.w, tri.vN1.w, tri.vN2.w ); // intersect ray through (x+1,y) and (x,y+1) with plane through the triangle float3 rayDXDir = normalize( (p1 + (float)(x + 0.5f + 1) * (1.0f / w) * p2 + (float)(y + 0.5f) * (1.0f / h) * p3) - pos ); float rayDXDepth = dot( make_float3( tri.vertex[0] ) - pos, triNormal ) / dot( triNormal, rayDXDir ); float3 rayDYDir = normalize( (p1 + (float)(x + 0.5f) * (1.0f / w) * p2 + (float)(y + 0.5f + 1) * (1.0f / h) * p3) - pos ); float rayDYDepth = dot( make_float3( tri.vertex[0] ) - pos, triNormal ) / dot( triNormal, rayDYDir ); deltaDepth[x + y * w] = make_float4( 0, 0, rayDXDepth - depth, rayDYDepth - depth ); } // +-----------------------------------------------------------------------------+ // | shadeKernel | // | Implements the shade phase of the wavefront path tracer. LH2'19| // +-----------------------------------------------------------------------------+ #if __CUDA_ARCH__ > 700 // Volta deliberately excluded __global__ __launch_bounds__( 128 /* max block size */, 4 /* min blocks per sm TURING */ ) #else __global__ __launch_bounds__( 128 /* max block size */, 8 /* min blocks per sm, PASCAL, VOLTA */ ) #endif void shadeKernel( float4* accumulator, const uint stride, uint4* features, float4* worldPos, float4* deltaDepth, float4* pathStates, const float4* hits, float4* connections, const uint R0, const uint* blueNoise, const int blueSlot, const int pass, const int probePixelIdx, const int pathLength, const int w, const int h, const float spreadAngle, const float3 p1, const float3 p2, const float3 p3, const float3 pos, const uint pathCount ) { // respect boundaries int jobIndex = threadIdx.x + blockIdx.x * blockDim.x; if (jobIndex >= pathCount) return; // gather data by reading sets of four floats for optimal throughput const float4 O4 = pathStates[jobIndex]; // ray origin xyz, w can be ignored const float4 D4 = pathStates[jobIndex + stride]; // ray direction xyz float4 T4 = pathLength == 1 ? make_float4( 1 ) /* faster */ : pathStates[jobIndex + stride * 2]; // path thoughput rgb const float4 hitData = hits[jobIndex]; const float bsdfPdf = T4.w; // derived data uint data = __float_as_uint( O4.w ); // prob.density of the last sampled dir, postponed because of MIS const float3 D = make_float3( D4 ); float3 throughput = make_float3( T4 ); const CoreTri4* instanceTriangles = (const CoreTri4*)instanceDescriptors[INSTANCEIDX].triangles; const uint pathIdx = PATHIDX; const uint pixelIdx = (pathIdx % (w * h)) + ((features != 0) && ((FLAGS & S_BOUNCED) != 0) ? (w * h) : 0); const uint sampleIdx = pathIdx / (w * h) + pass; // initialize filter data bool firstHitToBeStored = ((FLAGS & S_BOUNCED) == 0) && sampleIdx == 0 && features != 0; if (pathLength == 1 && firstHitToBeStored) { PackFeatures( features[pathIdx], 0, 0, 1e34f, 0, 0 ); worldPos[pathIdx] = make_float4( 0, 0, 0, __uint_as_float( 0 ) ); deltaDepth[pathIdx] = make_float4( 0 ); } // initialize depth in accumulator for DOF shader if (pathLength == 1) accumulator[pixelIdx].w += PRIMIDX == NOHIT ? 10000 : HIT_T; // use skydome if we didn't hit any geometry if (PRIMIDX == NOHIT) { float3 contribution = throughput * SampleSkydome( -worldToSky.TransformVector( D ) ) * (1.0f / bsdfPdf); CLAMPINTENSITY; // limit magnitude of thoughput vector to combat fireflies FIXNAN_FLOAT3( contribution ); accumulator[pixelIdx] += make_float4( contribution, 0 ); if (firstHitToBeStored) { // we only initialized the filter data, but the path ends here: store something reasonable for the filter. const uint isSpecular = FLAGS & S_VIASPECULAR ? 1 : 0; const uint packedNormal = PackNormal2( D * -1.0f ) + isSpecular; PackFeatures( features[pathIdx], HDRtoRGB32( contribution ), packedNormal, HIT_T, isSpecular, 0 ); worldPos[pathIdx] = make_float4( RAY_O + 50000 * D, __uint_as_float( packedNormal ) ); deltaDepth[pathIdx] = make_float4( 0 ); } return; } // object picking if (pixelIdx == probePixelIdx && pathLength == 1 && sampleIdx == 0) counters->probedInstid = INSTANCEIDX, // record instace id at the selected pixel counters->probedTriid = PRIMIDX, // record primitive id at the selected pixel counters->probedDist = HIT_T; // record primary ray hit distance // get shadingData and normals ShadingData shadingData; float3 N, iN, fN, T; const float3 I = RAY_O + HIT_T * D; const float coneWidth = spreadAngle * HIT_T; GetShadingData( D, HIT_U, HIT_V, coneWidth, instanceTriangles[PRIMIDX], INSTANCEIDX, shadingData, N, iN, fN, T ); // we need to detect alpha in the shading code. if (shadingData.flags & 1) { if (pathLength == MAXPATHLENGTH) { // it ends here, so store something sensible (otherwise alpha doesn't reproject) if (features != 0 && sampleIdx == 0 && ((FLAGS & S_BOUNCED) == 0)) { const uint isSpecular = FLAGS & S_VIASPECULAR ? 1 : 0; const uint packedNormal = PackNormal2( N ) + isSpecular; PackFeatures( features[pathIdx], 0, packedNormal, HIT_T, isSpecular, 0 ); worldPos[pathIdx] = make_float4( I, __uint_as_float( packedNormal ) ); } } else { const uint extensionRayIdx = atomicAdd( &counters->extensionRays, 1 ); pathStates[extensionRayIdx] = make_float4( I + D * geometryEpsilon, O4.w ); pathStates[extensionRayIdx + stride] = D4; if (!(isfinite( T4.x + T4.y + T4.z ))) T4 = make_float4( 0, 0, 0, T4.w ); pathStates[extensionRayIdx + stride * 2] = T4; } return; } // path regularization // if (FLAGS & S_BOUNCED) shadingData.roughness2 = max( 0.7f, shadingData.roughness2 ); // stop on light if (shadingData.IsEmissive() /* r, g or b exceeds 1 */) { const float DdotNL = -dot( D, N ); float3 contribution = make_float3( 0 ); // initialization required. if (DdotNL > 0 /* lights are not double sided */) { if (pathLength == 1 || (FLAGS & S_SPECULAR) > 0 || connections == 0) { // accept light contribution if previous vertex was specular contribution = shadingData.color; } else { // last vertex was not specular: apply MIS const float3 lastN = UnpackNormal( __float_as_uint( D4.w ) ); const CoreTri& tri = (const CoreTri&)instanceTriangles[PRIMIDX]; const float lightPdf = CalculateLightPDF( D, HIT_T, tri.area, N ); const float pickProb = LightPickProb( tri.ltriIdx, RAY_O, lastN, I /* the N at the previous vertex */ ); if ((bsdfPdf + lightPdf * pickProb) > 0) contribution = throughput * shadingData.color * (1.0f / (bsdfPdf + lightPdf * pickProb)); } CLAMPINTENSITY; FIXNAN_FLOAT3( contribution ); accumulator[pixelIdx] += make_float4( contribution, 0 ); } if (firstHitToBeStored) { // we only initialized the filter data, but the path ends here. Let's finalize the filter data with what we have. const uint isSpecular = FLAGS & S_VIASPECULAR ? 1 : 0; const uint packedNormal = PackNormal2( N ) + isSpecular; PackFeatures( features[pathIdx], HDRtoRGB32( shadingData.color ), packedNormal, HIT_T, isSpecular, shadingData.matID ); worldPos[pathIdx] = make_float4( I, __uint_as_float( packedNormal ) ); calculateDepthDerivatives( pathIdx % w, pathIdx / w, w, h, HIT_T, instanceTriangles[PRIMIDX], deltaDepth, p1, p2 - p1, p3 - p1, pos ); } return; } // detect specular surfaces if (ROUGHNESS <= 0.001f || TRANSMISSION > 0.999f) FLAGS |= S_SPECULAR; /* detect pure speculars; skip NEE for these */ else FLAGS &= ~S_SPECULAR; // initialize seed based on pixel index uint seed = WangHash( pathIdx * 17 + R0 /* well-seeded xor32 is all you need */ ); // store albedo, normal, depth in features buffer const float flip = (dot( D, N ) > 0) ? -1 : 1; if (firstHitToBeStored) { if (FLAGS & S_SPECULAR) { // first hit is pure specular; store albedo. Will be modulated by first diffuse hit later. features[pathIdx].x = HDRtoRGB32( shadingData.color ); } else { // first hit is diffuse; store normal, albedo, world space coordinate float3 albedo = shadingData.color; if (FLAGS & S_VIASPECULAR) albedo *= RGB32toHDR( features[pathIdx].x ); // this is the first diffuse vertex; store the data for the filter const uint isSpecular = FLAGS & S_VIASPECULAR ? 1 : 0; const uint packedNormal = PackNormal2( flip ? (fN * -1.0f) : fN ) + isSpecular; PackFeatures( features[pathIdx], HDRtoRGB32( albedo ), packedNormal, HIT_T, isSpecular, shadingData.matID ); worldPos[pathIdx] = make_float4( I, __uint_as_float( packedNormal ) ); calculateDepthDerivatives( pathIdx % w, pathIdx / w, w, h, HIT_T, instanceTriangles[PRIMIDX], deltaDepth, p1, p2 - p1, p3 - p1, pos ); } } // normal alignment for backfacing polygons const float faceDir = (dot( D, N ) > 0) ? -1 : 1; if (faceDir == 1) shadingData.transmittance = make_float3( 0 ); // apply postponed bsdf pdf throughput *= 1.0f / bsdfPdf; // next event estimation: connect eye path to light if ((FLAGS & S_SPECULAR) == 0 && connections != 0) // skip for specular vertices { float r0, r1, pickProb, lightPdf = 0; if (sampleIdx < 2) { const uint x = (pixelIdx % w) & 127, y = (pixelIdx / w) & 127; r0 = blueNoiseSampler( blueNoise, x, y, sampleIdx + blueSlot, 4 + 4 * pathLength ); r1 = blueNoiseSampler( blueNoise, x, y, sampleIdx + blueSlot, 5 + 4 * pathLength ); } else { r0 = RandomFloat( seed ); r1 = RandomFloat( seed ); } float3 lightColor, L = RandomPointOnLight( r0, r1, I, fN * faceDir, pickProb, lightPdf, lightColor ) - I; const float dist = length( L ); L *= 1.0f / dist; const float NdotL = dot( L, fN * faceDir ); if (NdotL > 0 && lightPdf > 0) { float bsdfPdf; #ifdef BSDF_HAS_PURE_SPECULARS // see note in lambert.h const float3 sampledBSDF = EvaluateBSDF( shadingData, fN /* * faceDir */, T, D * -1.0f, L, bsdfPdf ) * ROUGHNESS; #else const float3 sampledBSDF = EvaluateBSDF( shadingData, fN /* * faceDir */, T, D * -1.0f, L, bsdfPdf ); #endif if (bsdfPdf > 0) { // calculate potential contribution float3 contribution = throughput * sampledBSDF * lightColor * (NdotL / (pickProb * lightPdf + bsdfPdf)); FIXNAN_FLOAT3( contribution ); CLAMPINTENSITY; // add fire-and-forget shadow ray to the connections buffer const uint shadowRayIdx = atomicAdd( &counters->shadowRays, 1 ); // compaction connections[shadowRayIdx] = make_float4( SafeOrigin( I, L, N, geometryEpsilon ), 0 ); // O4 connections[shadowRayIdx + stride * 2] = make_float4( L, dist - 2 * geometryEpsilon ); // D4 connections[shadowRayIdx + stride * 2 * 2] = make_float4( contribution, __int_as_float( pixelIdx ) ); // E4 } } } // cap at one diffuse bounce (because of this we also don't need Russian roulette) if (FLAGS & S_BOUNCED) return; // depth cap if (pathLength == MAXPATHLENGTH /* don't fill arrays with rays we won't trace */) { // it ends here, and we didn't finalize the filter data, so store something sensible if (firstHitToBeStored) { const uint isSpecular = FLAGS & S_VIASPECULAR ? 1 : 0; const uint packedNormal = PackNormal2( N ) + isSpecular; PackFeatures( features[pathIdx], 0, packedNormal, HIT_T, isSpecular, 0 ); worldPos[pathIdx] = make_float4( I, __uint_as_float( packedNormal ) ); } return; } // evaluate bsdf to obtain direction for next path segment float3 R; float newBsdfPdf, r3, r4; if (sampleIdx < 256) { const uint x = (pixelIdx % w) & 127, y = (pixelIdx / w) & 127; r3 = blueNoiseSampler( blueNoise, x, y, sampleIdx + blueSlot, 6 + 4 * pathLength ); r4 = blueNoiseSampler( blueNoise, x, y, sampleIdx + blueSlot, 7 + 4 * pathLength ); } else { r3 = RandomFloat( seed ); r4 = RandomFloat( seed ); } bool specular = false; const float3 bsdf = SampleBSDF( shadingData, fN, N, T, D * -1.0f, HIT_T, r3, r4, RandomFloat( seed ), R, newBsdfPdf, specular ); if (newBsdfPdf < EPSILON || isnan( newBsdfPdf )) return; if (specular) FLAGS |= S_SPECULAR; // write extension ray const uint extensionRayIdx = atomicAdd( &counters->extensionRays, 1 ); // compact const uint packedNormal = PackNormal( fN * faceDir ); if (!(FLAGS & S_SPECULAR)) FLAGS |= S_BOUNCED; else FLAGS |= S_VIASPECULAR; pathStates[extensionRayIdx] = make_float4( SafeOrigin( I, R, N, geometryEpsilon ), __uint_as_float( FLAGS ) ); pathStates[extensionRayIdx + stride] = make_float4( R, __uint_as_float( packedNormal ) ); FIXNAN_FLOAT3( throughput ); pathStates[extensionRayIdx + stride * 2] = make_float4( throughput * bsdf * abs( dot( fN, R ) ), newBsdfPdf ); } // +-----------------------------------------------------------------------------+ // | shadeKernel | // | Host-side access point for the shadeKernel code. LH2'19| // +-----------------------------------------------------------------------------+ __host__ void shade( const int pathCount, float4* accumulator, const uint stride, uint4* features, float4* worldPos, float4* deltaDepth, float4* pathStates, const float4* hits, float4* connections, const uint R0, const uint* blueNoise, const int blueSlot, const int pass, const int probePixelIdx, const int pathLength, const int scrwidth, const int scrheight, const float spreadAngle, const float3 p1, const float3 p2, const float3 p3, const float3 pos ) { const dim3 gridDim( NEXTMULTIPLEOF( pathCount, 128 ) / 128, 1 ), blockDim( 128, 1 ); shadeKernel << <gridDim.x, 128 >> > (accumulator, stride, features, worldPos, deltaDepth, pathStates, hits, connections, R0, blueNoise, blueSlot, pass, probePixelIdx, pathLength, scrwidth, scrheight, spreadAngle, p1, p2, p3, pos, pathCount); } // EOF
{ "pile_set_name": "Github" }
import React from 'react' import 'stylesheets/modules/header' import 'stylesheets/utilities/clearfix' const Header = React.createClass({ render () { return ( <div className='header u-clearfix'> Header </div> ) } }) export default Header
{ "pile_set_name": "Github" }
// Copyright 2016 Google Inc. All Rights Reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the COPYING file in the root of the source // tree. An additional intellectual property rights grant can be found // in the file PATENTS. All contributing project authors may // be found in the AUTHORS file in the root of the source tree. // ----------------------------------------------------------------------------- // // Image transform methods for lossless encoder. // // Authors: Vikas Arora ([email protected]) // Jyrki Alakuijala ([email protected]) // Urvang Joshi ([email protected]) // Vincent Rabaud ([email protected]) #include "src/dsp/lossless.h" #include "src/dsp/lossless_common.h" #include "src/enc/vp8li_enc.h" #define MAX_DIFF_COST (1e30f) static const float kSpatialPredictorBias = 15.f; static const int kPredLowEffort = 11; static const uint32_t kMaskAlpha = 0xff000000; // Mostly used to reduce code size + readability static WEBP_INLINE int GetMin(int a, int b) { return (a > b) ? b : a; } //------------------------------------------------------------------------------ // Methods to calculate Entropy (Shannon). static float PredictionCostSpatial(const int counts[256], int weight_0, double exp_val) { const int significant_symbols = 256 >> 4; const double exp_decay_factor = 0.6; double bits = weight_0 * counts[0]; int i; for (i = 1; i < significant_symbols; ++i) { bits += exp_val * (counts[i] + counts[256 - i]); exp_val *= exp_decay_factor; } return (float)(-0.1 * bits); } static float PredictionCostSpatialHistogram(const int accumulated[4][256], const int tile[4][256]) { int i; double retval = 0; for (i = 0; i < 4; ++i) { const double kExpValue = 0.94; retval += PredictionCostSpatial(tile[i], 1, kExpValue); retval += VP8LCombinedShannonEntropy(tile[i], accumulated[i]); } return (float)retval; } static WEBP_INLINE void UpdateHisto(int histo_argb[4][256], uint32_t argb) { ++histo_argb[0][argb >> 24]; ++histo_argb[1][(argb >> 16) & 0xff]; ++histo_argb[2][(argb >> 8) & 0xff]; ++histo_argb[3][argb & 0xff]; } //------------------------------------------------------------------------------ // Spatial transform functions. static WEBP_INLINE void PredictBatch(int mode, int x_start, int y, int num_pixels, const uint32_t* current, const uint32_t* upper, uint32_t* out) { if (x_start == 0) { if (y == 0) { // ARGB_BLACK. VP8LPredictorsSub[0](current, NULL, 1, out); } else { // Top one. VP8LPredictorsSub[2](current, upper, 1, out); } ++x_start; ++out; --num_pixels; } if (y == 0) { // Left one. VP8LPredictorsSub[1](current + x_start, NULL, num_pixels, out); } else { VP8LPredictorsSub[mode](current + x_start, upper + x_start, num_pixels, out); } } #if (WEBP_NEAR_LOSSLESS == 1) static WEBP_INLINE int GetMax(int a, int b) { return (a < b) ? b : a; } static int MaxDiffBetweenPixels(uint32_t p1, uint32_t p2) { const int diff_a = abs((int)(p1 >> 24) - (int)(p2 >> 24)); const int diff_r = abs((int)((p1 >> 16) & 0xff) - (int)((p2 >> 16) & 0xff)); const int diff_g = abs((int)((p1 >> 8) & 0xff) - (int)((p2 >> 8) & 0xff)); const int diff_b = abs((int)(p1 & 0xff) - (int)(p2 & 0xff)); return GetMax(GetMax(diff_a, diff_r), GetMax(diff_g, diff_b)); } static int MaxDiffAroundPixel(uint32_t current, uint32_t up, uint32_t down, uint32_t left, uint32_t right) { const int diff_up = MaxDiffBetweenPixels(current, up); const int diff_down = MaxDiffBetweenPixels(current, down); const int diff_left = MaxDiffBetweenPixels(current, left); const int diff_right = MaxDiffBetweenPixels(current, right); return GetMax(GetMax(diff_up, diff_down), GetMax(diff_left, diff_right)); } static uint32_t AddGreenToBlueAndRed(uint32_t argb) { const uint32_t green = (argb >> 8) & 0xff; uint32_t red_blue = argb & 0x00ff00ffu; red_blue += (green << 16) | green; red_blue &= 0x00ff00ffu; return (argb & 0xff00ff00u) | red_blue; } static void MaxDiffsForRow(int width, int stride, const uint32_t* const argb, uint8_t* const max_diffs, int used_subtract_green) { uint32_t current, up, down, left, right; int x; if (width <= 2) return; current = argb[0]; right = argb[1]; if (used_subtract_green) { current = AddGreenToBlueAndRed(current); right = AddGreenToBlueAndRed(right); } // max_diffs[0] and max_diffs[width - 1] are never used. for (x = 1; x < width - 1; ++x) { up = argb[-stride + x]; down = argb[stride + x]; left = current; current = right; right = argb[x + 1]; if (used_subtract_green) { up = AddGreenToBlueAndRed(up); down = AddGreenToBlueAndRed(down); right = AddGreenToBlueAndRed(right); } max_diffs[x] = MaxDiffAroundPixel(current, up, down, left, right); } } // Quantize the difference between the actual component value and its prediction // to a multiple of quantization, working modulo 256, taking care not to cross // a boundary (inclusive upper limit). static uint8_t NearLosslessComponent(uint8_t value, uint8_t predict, uint8_t boundary, int quantization) { const int residual = (value - predict) & 0xff; const int boundary_residual = (boundary - predict) & 0xff; const int lower = residual & ~(quantization - 1); const int upper = lower + quantization; // Resolve ties towards a value closer to the prediction (i.e. towards lower // if value comes after prediction and towards upper otherwise). const int bias = ((boundary - value) & 0xff) < boundary_residual; if (residual - lower < upper - residual + bias) { // lower is closer to residual than upper. if (residual > boundary_residual && lower <= boundary_residual) { // Halve quantization step to avoid crossing boundary. This midpoint is // on the same side of boundary as residual because midpoint >= residual // (since lower is closer than upper) and residual is above the boundary. return lower + (quantization >> 1); } return lower; } else { // upper is closer to residual than lower. if (residual <= boundary_residual && upper > boundary_residual) { // Halve quantization step to avoid crossing boundary. This midpoint is // on the same side of boundary as residual because midpoint <= residual // (since upper is closer than lower) and residual is below the boundary. return lower + (quantization >> 1); } return upper & 0xff; } } static WEBP_INLINE uint8_t NearLosslessDiff(uint8_t a, uint8_t b) { return (uint8_t)((((int)(a) - (int)(b))) & 0xff); } // Quantize every component of the difference between the actual pixel value and // its prediction to a multiple of a quantization (a power of 2, not larger than // max_quantization which is a power of 2, smaller than max_diff). Take care if // value and predict have undergone subtract green, which means that red and // blue are represented as offsets from green. static uint32_t NearLossless(uint32_t value, uint32_t predict, int max_quantization, int max_diff, int used_subtract_green) { int quantization; uint8_t new_green = 0; uint8_t green_diff = 0; uint8_t a, r, g, b; if (max_diff <= 2) { return VP8LSubPixels(value, predict); } quantization = max_quantization; while (quantization >= max_diff) { quantization >>= 1; } if ((value >> 24) == 0 || (value >> 24) == 0xff) { // Preserve transparency of fully transparent or fully opaque pixels. a = NearLosslessDiff((value >> 24) & 0xff, (predict >> 24) & 0xff); } else { a = NearLosslessComponent(value >> 24, predict >> 24, 0xff, quantization); } g = NearLosslessComponent((value >> 8) & 0xff, (predict >> 8) & 0xff, 0xff, quantization); if (used_subtract_green) { // The green offset will be added to red and blue components during decoding // to obtain the actual red and blue values. new_green = ((predict >> 8) + g) & 0xff; // The amount by which green has been adjusted during quantization. It is // subtracted from red and blue for compensation, to avoid accumulating two // quantization errors in them. green_diff = NearLosslessDiff(new_green, (value >> 8) & 0xff); } r = NearLosslessComponent(NearLosslessDiff((value >> 16) & 0xff, green_diff), (predict >> 16) & 0xff, 0xff - new_green, quantization); b = NearLosslessComponent(NearLosslessDiff(value & 0xff, green_diff), predict & 0xff, 0xff - new_green, quantization); return ((uint32_t)a << 24) | ((uint32_t)r << 16) | ((uint32_t)g << 8) | b; } #endif // (WEBP_NEAR_LOSSLESS == 1) // Stores the difference between the pixel and its prediction in "out". // In case of a lossy encoding, updates the source image to avoid propagating // the deviation further to pixels which depend on the current pixel for their // predictions. static WEBP_INLINE void GetResidual( int width, int height, uint32_t* const upper_row, uint32_t* const current_row, const uint8_t* const max_diffs, int mode, int x_start, int x_end, int y, int max_quantization, int exact, int used_subtract_green, uint32_t* const out) { if (exact) { PredictBatch(mode, x_start, y, x_end - x_start, current_row, upper_row, out); } else { const VP8LPredictorFunc pred_func = VP8LPredictors[mode]; int x; for (x = x_start; x < x_end; ++x) { uint32_t predict; uint32_t residual; if (y == 0) { predict = (x == 0) ? ARGB_BLACK : current_row[x - 1]; // Left. } else if (x == 0) { predict = upper_row[x]; // Top. } else { predict = pred_func(current_row[x - 1], upper_row + x); } #if (WEBP_NEAR_LOSSLESS == 1) if (max_quantization == 1 || mode == 0 || y == 0 || y == height - 1 || x == 0 || x == width - 1) { residual = VP8LSubPixels(current_row[x], predict); } else { residual = NearLossless(current_row[x], predict, max_quantization, max_diffs[x], used_subtract_green); // Update the source image. current_row[x] = VP8LAddPixels(predict, residual); // x is never 0 here so we do not need to update upper_row like below. } #else (void)max_diffs; (void)height; (void)max_quantization; (void)used_subtract_green; residual = VP8LSubPixels(current_row[x], predict); #endif if ((current_row[x] & kMaskAlpha) == 0) { // If alpha is 0, cleanup RGB. We can choose the RGB values of the // residual for best compression. The prediction of alpha itself can be // non-zero and must be kept though. We choose RGB of the residual to be // 0. residual &= kMaskAlpha; // Update the source image. current_row[x] = predict & ~kMaskAlpha; // The prediction for the rightmost pixel in a row uses the leftmost // pixel // in that row as its top-right context pixel. Hence if we change the // leftmost pixel of current_row, the corresponding change must be // applied // to upper_row as well where top-right context is being read from. if (x == 0 && y != 0) upper_row[width] = current_row[0]; } out[x - x_start] = residual; } } } // Returns best predictor and updates the accumulated histogram. // If max_quantization > 1, assumes that near lossless processing will be // applied, quantizing residuals to multiples of quantization levels up to // max_quantization (the actual quantization level depends on smoothness near // the given pixel). static int GetBestPredictorForTile(int width, int height, int tile_x, int tile_y, int bits, int accumulated[4][256], uint32_t* const argb_scratch, const uint32_t* const argb, int max_quantization, int exact, int used_subtract_green, const uint32_t* const modes) { const int kNumPredModes = 14; const int start_x = tile_x << bits; const int start_y = tile_y << bits; const int tile_size = 1 << bits; const int max_y = GetMin(tile_size, height - start_y); const int max_x = GetMin(tile_size, width - start_x); // Whether there exist columns just outside the tile. const int have_left = (start_x > 0); // Position and size of the strip covering the tile and adjacent columns if // they exist. const int context_start_x = start_x - have_left; #if (WEBP_NEAR_LOSSLESS == 1) const int context_width = max_x + have_left + (max_x < width - start_x); #endif const int tiles_per_row = VP8LSubSampleSize(width, bits); // Prediction modes of the left and above neighbor tiles. const int left_mode = (tile_x > 0) ? (modes[tile_y * tiles_per_row + tile_x - 1] >> 8) & 0xff : 0xff; const int above_mode = (tile_y > 0) ? (modes[(tile_y - 1) * tiles_per_row + tile_x] >> 8) & 0xff : 0xff; // The width of upper_row and current_row is one pixel larger than image width // to allow the top right pixel to point to the leftmost pixel of the next row // when at the right edge. uint32_t* upper_row = argb_scratch; uint32_t* current_row = upper_row + width + 1; uint8_t* const max_diffs = (uint8_t*)(current_row + width + 1); float best_diff = MAX_DIFF_COST; int best_mode = 0; int mode; int histo_stack_1[4][256]; int histo_stack_2[4][256]; // Need pointers to be able to swap arrays. int (*histo_argb)[256] = histo_stack_1; int (*best_histo)[256] = histo_stack_2; int i, j; uint32_t residuals[1 << MAX_TRANSFORM_BITS]; assert(bits <= MAX_TRANSFORM_BITS); assert(max_x <= (1 << MAX_TRANSFORM_BITS)); for (mode = 0; mode < kNumPredModes; ++mode) { float cur_diff; int relative_y; memset(histo_argb, 0, sizeof(histo_stack_1)); if (start_y > 0) { // Read the row above the tile which will become the first upper_row. // Include a pixel to the left if it exists; include a pixel to the right // in all cases (wrapping to the leftmost pixel of the next row if it does // not exist). memcpy(current_row + context_start_x, argb + (start_y - 1) * width + context_start_x, sizeof(*argb) * (max_x + have_left + 1)); } for (relative_y = 0; relative_y < max_y; ++relative_y) { const int y = start_y + relative_y; int relative_x; uint32_t* tmp = upper_row; upper_row = current_row; current_row = tmp; // Read current_row. Include a pixel to the left if it exists; include a // pixel to the right in all cases except at the bottom right corner of // the image (wrapping to the leftmost pixel of the next row if it does // not exist in the current row). memcpy(current_row + context_start_x, argb + y * width + context_start_x, sizeof(*argb) * (max_x + have_left + (y + 1 < height))); #if (WEBP_NEAR_LOSSLESS == 1) if (max_quantization > 1 && y >= 1 && y + 1 < height) { MaxDiffsForRow(context_width, width, argb + y * width + context_start_x, max_diffs + context_start_x, used_subtract_green); } #endif GetResidual(width, height, upper_row, current_row, max_diffs, mode, start_x, start_x + max_x, y, max_quantization, exact, used_subtract_green, residuals); for (relative_x = 0; relative_x < max_x; ++relative_x) { UpdateHisto(histo_argb, residuals[relative_x]); } } cur_diff = PredictionCostSpatialHistogram( (const int (*)[256])accumulated, (const int (*)[256])histo_argb); // Favor keeping the areas locally similar. if (mode == left_mode) cur_diff -= kSpatialPredictorBias; if (mode == above_mode) cur_diff -= kSpatialPredictorBias; if (cur_diff < best_diff) { int (*tmp)[256] = histo_argb; histo_argb = best_histo; best_histo = tmp; best_diff = cur_diff; best_mode = mode; } } for (i = 0; i < 4; i++) { for (j = 0; j < 256; j++) { accumulated[i][j] += best_histo[i][j]; } } return best_mode; } // Converts pixels of the image to residuals with respect to predictions. // If max_quantization > 1, applies near lossless processing, quantizing // residuals to multiples of quantization levels up to max_quantization // (the actual quantization level depends on smoothness near the given pixel). static void CopyImageWithPrediction(int width, int height, int bits, uint32_t* const modes, uint32_t* const argb_scratch, uint32_t* const argb, int low_effort, int max_quantization, int exact, int used_subtract_green) { const int tiles_per_row = VP8LSubSampleSize(width, bits); // The width of upper_row and current_row is one pixel larger than image width // to allow the top right pixel to point to the leftmost pixel of the next row // when at the right edge. uint32_t* upper_row = argb_scratch; uint32_t* current_row = upper_row + width + 1; uint8_t* current_max_diffs = (uint8_t*)(current_row + width + 1); #if (WEBP_NEAR_LOSSLESS == 1) uint8_t* lower_max_diffs = current_max_diffs + width; #endif int y; for (y = 0; y < height; ++y) { int x; uint32_t* const tmp32 = upper_row; upper_row = current_row; current_row = tmp32; memcpy(current_row, argb + y * width, sizeof(*argb) * (width + (y + 1 < height))); if (low_effort) { PredictBatch(kPredLowEffort, 0, y, width, current_row, upper_row, argb + y * width); } else { #if (WEBP_NEAR_LOSSLESS == 1) if (max_quantization > 1) { // Compute max_diffs for the lower row now, because that needs the // contents of argb for the current row, which we will overwrite with // residuals before proceeding with the next row. uint8_t* const tmp8 = current_max_diffs; current_max_diffs = lower_max_diffs; lower_max_diffs = tmp8; if (y + 2 < height) { MaxDiffsForRow(width, width, argb + (y + 1) * width, lower_max_diffs, used_subtract_green); } } #endif for (x = 0; x < width;) { const int mode = (modes[(y >> bits) * tiles_per_row + (x >> bits)] >> 8) & 0xff; int x_end = x + (1 << bits); if (x_end > width) x_end = width; GetResidual(width, height, upper_row, current_row, current_max_diffs, mode, x, x_end, y, max_quantization, exact, used_subtract_green, argb + y * width + x); x = x_end; } } } } // Finds the best predictor for each tile, and converts the image to residuals // with respect to predictions. If near_lossless_quality < 100, applies // near lossless processing, shaving off more bits of residuals for lower // qualities. void VP8LResidualImage(int width, int height, int bits, int low_effort, uint32_t* const argb, uint32_t* const argb_scratch, uint32_t* const image, int near_lossless_quality, int exact, int used_subtract_green) { const int tiles_per_row = VP8LSubSampleSize(width, bits); const int tiles_per_col = VP8LSubSampleSize(height, bits); int tile_y; int histo[4][256]; const int max_quantization = 1 << VP8LNearLosslessBits(near_lossless_quality); if (low_effort) { int i; for (i = 0; i < tiles_per_row * tiles_per_col; ++i) { image[i] = ARGB_BLACK | (kPredLowEffort << 8); } } else { memset(histo, 0, sizeof(histo)); for (tile_y = 0; tile_y < tiles_per_col; ++tile_y) { int tile_x; for (tile_x = 0; tile_x < tiles_per_row; ++tile_x) { const int pred = GetBestPredictorForTile(width, height, tile_x, tile_y, bits, histo, argb_scratch, argb, max_quantization, exact, used_subtract_green, image); image[tile_y * tiles_per_row + tile_x] = ARGB_BLACK | (pred << 8); } } } CopyImageWithPrediction(width, height, bits, image, argb_scratch, argb, low_effort, max_quantization, exact, used_subtract_green); } //------------------------------------------------------------------------------ // Color transform functions. static WEBP_INLINE void MultipliersClear(VP8LMultipliers* const m) { m->green_to_red_ = 0; m->green_to_blue_ = 0; m->red_to_blue_ = 0; } static WEBP_INLINE void ColorCodeToMultipliers(uint32_t color_code, VP8LMultipliers* const m) { m->green_to_red_ = (color_code >> 0) & 0xff; m->green_to_blue_ = (color_code >> 8) & 0xff; m->red_to_blue_ = (color_code >> 16) & 0xff; } static WEBP_INLINE uint32_t MultipliersToColorCode( const VP8LMultipliers* const m) { return 0xff000000u | ((uint32_t)(m->red_to_blue_) << 16) | ((uint32_t)(m->green_to_blue_) << 8) | m->green_to_red_; } static float PredictionCostCrossColor(const int accumulated[256], const int counts[256]) { // Favor low entropy, locally and globally. // Favor small absolute values for PredictionCostSpatial static const double kExpValue = 2.4; return VP8LCombinedShannonEntropy(counts, accumulated) + PredictionCostSpatial(counts, 3, kExpValue); } static float GetPredictionCostCrossColorRed( const uint32_t* argb, int stride, int tile_width, int tile_height, VP8LMultipliers prev_x, VP8LMultipliers prev_y, int green_to_red, const int accumulated_red_histo[256]) { int histo[256] = { 0 }; float cur_diff; VP8LCollectColorRedTransforms(argb, stride, tile_width, tile_height, green_to_red, histo); cur_diff = PredictionCostCrossColor(accumulated_red_histo, histo); if ((uint8_t)green_to_red == prev_x.green_to_red_) { cur_diff -= 3; // favor keeping the areas locally similar } if ((uint8_t)green_to_red == prev_y.green_to_red_) { cur_diff -= 3; // favor keeping the areas locally similar } if (green_to_red == 0) { cur_diff -= 3; } return cur_diff; } static void GetBestGreenToRed( const uint32_t* argb, int stride, int tile_width, int tile_height, VP8LMultipliers prev_x, VP8LMultipliers prev_y, int quality, const int accumulated_red_histo[256], VP8LMultipliers* const best_tx) { const int kMaxIters = 4 + ((7 * quality) >> 8); // in range [4..6] int green_to_red_best = 0; int iter, offset; float best_diff = GetPredictionCostCrossColorRed( argb, stride, tile_width, tile_height, prev_x, prev_y, green_to_red_best, accumulated_red_histo); for (iter = 0; iter < kMaxIters; ++iter) { // ColorTransformDelta is a 3.5 bit fixed point, so 32 is equal to // one in color computation. Having initial delta here as 1 is sufficient // to explore the range of (-2, 2). const int delta = 32 >> iter; // Try a negative and a positive delta from the best known value. for (offset = -delta; offset <= delta; offset += 2 * delta) { const int green_to_red_cur = offset + green_to_red_best; const float cur_diff = GetPredictionCostCrossColorRed( argb, stride, tile_width, tile_height, prev_x, prev_y, green_to_red_cur, accumulated_red_histo); if (cur_diff < best_diff) { best_diff = cur_diff; green_to_red_best = green_to_red_cur; } } } best_tx->green_to_red_ = (green_to_red_best & 0xff); } static float GetPredictionCostCrossColorBlue( const uint32_t* argb, int stride, int tile_width, int tile_height, VP8LMultipliers prev_x, VP8LMultipliers prev_y, int green_to_blue, int red_to_blue, const int accumulated_blue_histo[256]) { int histo[256] = { 0 }; float cur_diff; VP8LCollectColorBlueTransforms(argb, stride, tile_width, tile_height, green_to_blue, red_to_blue, histo); cur_diff = PredictionCostCrossColor(accumulated_blue_histo, histo); if ((uint8_t)green_to_blue == prev_x.green_to_blue_) { cur_diff -= 3; // favor keeping the areas locally similar } if ((uint8_t)green_to_blue == prev_y.green_to_blue_) { cur_diff -= 3; // favor keeping the areas locally similar } if ((uint8_t)red_to_blue == prev_x.red_to_blue_) { cur_diff -= 3; // favor keeping the areas locally similar } if ((uint8_t)red_to_blue == prev_y.red_to_blue_) { cur_diff -= 3; // favor keeping the areas locally similar } if (green_to_blue == 0) { cur_diff -= 3; } if (red_to_blue == 0) { cur_diff -= 3; } return cur_diff; } #define kGreenRedToBlueNumAxis 8 #define kGreenRedToBlueMaxIters 7 static void GetBestGreenRedToBlue( const uint32_t* argb, int stride, int tile_width, int tile_height, VP8LMultipliers prev_x, VP8LMultipliers prev_y, int quality, const int accumulated_blue_histo[256], VP8LMultipliers* const best_tx) { const int8_t offset[kGreenRedToBlueNumAxis][2] = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}, {-1, -1}, {-1, 1}, {1, -1}, {1, 1}}; const int8_t delta_lut[kGreenRedToBlueMaxIters] = { 16, 16, 8, 4, 2, 2, 2 }; const int iters = (quality < 25) ? 1 : (quality > 50) ? kGreenRedToBlueMaxIters : 4; int green_to_blue_best = 0; int red_to_blue_best = 0; int iter; // Initial value at origin: float best_diff = GetPredictionCostCrossColorBlue( argb, stride, tile_width, tile_height, prev_x, prev_y, green_to_blue_best, red_to_blue_best, accumulated_blue_histo); for (iter = 0; iter < iters; ++iter) { const int delta = delta_lut[iter]; int axis; for (axis = 0; axis < kGreenRedToBlueNumAxis; ++axis) { const int green_to_blue_cur = offset[axis][0] * delta + green_to_blue_best; const int red_to_blue_cur = offset[axis][1] * delta + red_to_blue_best; const float cur_diff = GetPredictionCostCrossColorBlue( argb, stride, tile_width, tile_height, prev_x, prev_y, green_to_blue_cur, red_to_blue_cur, accumulated_blue_histo); if (cur_diff < best_diff) { best_diff = cur_diff; green_to_blue_best = green_to_blue_cur; red_to_blue_best = red_to_blue_cur; } if (quality < 25 && iter == 4) { // Only axis aligned diffs for lower quality. break; // next iter. } } if (delta == 2 && green_to_blue_best == 0 && red_to_blue_best == 0) { // Further iterations would not help. break; // out of iter-loop. } } best_tx->green_to_blue_ = green_to_blue_best & 0xff; best_tx->red_to_blue_ = red_to_blue_best & 0xff; } #undef kGreenRedToBlueMaxIters #undef kGreenRedToBlueNumAxis static VP8LMultipliers GetBestColorTransformForTile( int tile_x, int tile_y, int bits, VP8LMultipliers prev_x, VP8LMultipliers prev_y, int quality, int xsize, int ysize, const int accumulated_red_histo[256], const int accumulated_blue_histo[256], const uint32_t* const argb) { const int max_tile_size = 1 << bits; const int tile_y_offset = tile_y * max_tile_size; const int tile_x_offset = tile_x * max_tile_size; const int all_x_max = GetMin(tile_x_offset + max_tile_size, xsize); const int all_y_max = GetMin(tile_y_offset + max_tile_size, ysize); const int tile_width = all_x_max - tile_x_offset; const int tile_height = all_y_max - tile_y_offset; const uint32_t* const tile_argb = argb + tile_y_offset * xsize + tile_x_offset; VP8LMultipliers best_tx; MultipliersClear(&best_tx); GetBestGreenToRed(tile_argb, xsize, tile_width, tile_height, prev_x, prev_y, quality, accumulated_red_histo, &best_tx); GetBestGreenRedToBlue(tile_argb, xsize, tile_width, tile_height, prev_x, prev_y, quality, accumulated_blue_histo, &best_tx); return best_tx; } static void CopyTileWithColorTransform(int xsize, int ysize, int tile_x, int tile_y, int max_tile_size, VP8LMultipliers color_transform, uint32_t* argb) { const int xscan = GetMin(max_tile_size, xsize - tile_x); int yscan = GetMin(max_tile_size, ysize - tile_y); argb += tile_y * xsize + tile_x; while (yscan-- > 0) { VP8LTransformColor(&color_transform, argb, xscan); argb += xsize; } } void VP8LColorSpaceTransform(int width, int height, int bits, int quality, uint32_t* const argb, uint32_t* image) { const int max_tile_size = 1 << bits; const int tile_xsize = VP8LSubSampleSize(width, bits); const int tile_ysize = VP8LSubSampleSize(height, bits); int accumulated_red_histo[256] = { 0 }; int accumulated_blue_histo[256] = { 0 }; int tile_x, tile_y; VP8LMultipliers prev_x, prev_y; MultipliersClear(&prev_y); MultipliersClear(&prev_x); for (tile_y = 0; tile_y < tile_ysize; ++tile_y) { for (tile_x = 0; tile_x < tile_xsize; ++tile_x) { int y; const int tile_x_offset = tile_x * max_tile_size; const int tile_y_offset = tile_y * max_tile_size; const int all_x_max = GetMin(tile_x_offset + max_tile_size, width); const int all_y_max = GetMin(tile_y_offset + max_tile_size, height); const int offset = tile_y * tile_xsize + tile_x; if (tile_y != 0) { ColorCodeToMultipliers(image[offset - tile_xsize], &prev_y); } prev_x = GetBestColorTransformForTile(tile_x, tile_y, bits, prev_x, prev_y, quality, width, height, accumulated_red_histo, accumulated_blue_histo, argb); image[offset] = MultipliersToColorCode(&prev_x); CopyTileWithColorTransform(width, height, tile_x_offset, tile_y_offset, max_tile_size, prev_x, argb); // Gather accumulated histogram data. for (y = tile_y_offset; y < all_y_max; ++y) { int ix = y * width + tile_x_offset; const int ix_end = ix + all_x_max - tile_x_offset; for (; ix < ix_end; ++ix) { const uint32_t pix = argb[ix]; if (ix >= 2 && pix == argb[ix - 2] && pix == argb[ix - 1]) { continue; // repeated pixels are handled by backward references } if (ix >= width + 2 && argb[ix - 2] == argb[ix - width - 2] && argb[ix - 1] == argb[ix - width - 1] && pix == argb[ix - width]) { continue; // repeated pixels are handled by backward references } ++accumulated_red_histo[(pix >> 16) & 0xff]; ++accumulated_blue_histo[(pix >> 0) & 0xff]; } } } } }
{ "pile_set_name": "Github" }
/* pass 9 * * - optimize usage of temporary variables */ if (ZEND_OPTIMIZER_PASS_9 & OPTIMIZATION_LEVEL) { optimize_temporary_variables(op_array); }
{ "pile_set_name": "Github" }
<!doctype html> <!-- @license Copyright (c) 2015 The Polymer Project Authors. All rights reserved. This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by Google as part of the polymer project is also subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt --> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes"> <title>iron-validatable-behavior</title> <script src="../webcomponentsjs/webcomponents-lite.js"></script> <link rel="import" href="../polymer/polymer.html"> <link rel="import" href="../iron-component-page/iron-component-page.html"> </head> <body> <iron-component-page></iron-component-page> </body> </html>
{ "pile_set_name": "Github" }
<link rel="stylesheet" href="../dist/neutrine.css"> <link rel="stylesheet" href="../bower_components/siimple/dist/siimple.min.css"> <script type="text/javascript" src="../node_modules/react/umd/react.development.js"></script> <script type="text/javascript" src="../node_modules/react-dom/umd/react-dom.development.js"></script> <script type="text/javascript" src="../dist/neutrine.js"></script> <div id="root"></div> <script type="text/javascript"> let options = { "cancellable": true }; let toast = ReactDOM.render(React.createElement(Neutrine.Toast, options), document.getElementById("root")); </script>
{ "pile_set_name": "Github" }
package com.twobbble.presenter import com.twobbble.R import com.twobbble.application.App import com.twobbble.biz.api.IDetailsBiz import com.twobbble.biz.impl.DetailsBiz import com.twobbble.entity.Comment import com.twobbble.entity.LikeShotResponse import com.twobbble.tools.NetObserver import com.twobbble.tools.log import com.twobbble.tools.obtainString import com.twobbble.view.api.IDetailsView import org.jetbrains.annotations.NotNull /** * Created by liuzipeng on 2017/3/1. */ class DetailsPresenter(val mDetailsView: IDetailsView) : BasePresenter() { private val mDetailsBiz: IDetailsBiz by lazy { DetailsBiz() } fun getComments(@NotNull id: Long, @NotNull token: String, page: Int?) { mDetailsBiz.getComments(id, token, page, NetObserver({ mDisposables.add(it) }, { mDetailsView.getCommentsSuccess(it) }, { mDetailsView.getCommentsFailed(it) }, mDetailsView)) } fun likeShot(@NotNull id: Long, @NotNull token: String) { mDetailsBiz.likeShot(id, token, NetObserver({ mDisposables.add(it) }, { if (it != null) mDetailsView.likeShotSuccess() else mDetailsView.likeShotFailed(App.instance.obtainString(R.string.like_failed)) }, { mDetailsView.likeShotFailed("${App.instance.obtainString(R.string.like_failed)}:$it") })) } fun checkIfLikeShot(@NotNull id: Long, @NotNull token: String) { mDetailsBiz.checkIfLikeShot(id, token, NetObserver({ mDisposables.add(it) }, { if (it != null) mDetailsView.checkIfLikeSuccess() else mDetailsView.checkIfLikeFailed() }, { mDetailsView.checkIfLikeFailed() })) } fun unlikeShot(@NotNull id: Long, @NotNull token: String) { mDetailsBiz.unlikeShot(id, token, NetObserver({ mDisposables.add(it) }, { mDetailsView.unLikeShotSuccess() }, { mDetailsView.unLikeShotFailed("${App.instance.obtainString(R.string.unlike_failed)}:$it") })) } fun createComment(@NotNull id: Long, @NotNull token: String, @NotNull body: String) { mDetailsBiz.createComment(id, token, body, NetObserver({ mDetailsView.showSendProgress() mDisposables.add(it) }, { mDetailsView.hideSendProgress() mDetailsView.addCommentSuccess(it) }, { mDetailsView.hideSendProgress() mDetailsView.addCommentFailed("${App.instance.obtainString(R.string.account_not_player)}:$it") })) } }
{ "pile_set_name": "Github" }
WEBVTT 00:00:20.187 --> 00:00:21.021 <c.magenta>早上好</c> 00:00:21.522 --> 00:00:23.757 <c.magenta>欢迎各位出席</c> <c.magenta>“用ReplayKit直播”</c> 00:00:24.324 --> 00:00:26.026 <c.magenta>在这次演讲中</c> <c.magenta>我们将告诉你关于</c> 00:00:26.093 --> 00:00:28.529 <c.magenta>我们加入到这个框架中的所有新特性</c> 00:00:28.996 --> 00:00:30.063 <c.magenta>我是Ben Harry</c> 00:00:30.130 --> 00:00:32.999 <c.magenta>Apple游戏技术组的软件工程师</c> 00:00:33.400 --> 00:00:35.802 <c.magenta>稍后你们会听到</c> <c.magenta>Edwin Iskander的演讲</c> 00:00:37.137 --> 00:00:39.773 <c.magenta>现在我们知道人们喜欢录制他们</c> <c.magenta>的游戏</c> 00:00:40.073 --> 00:00:42.042 <c.magenta>并在社交媒体上分享那些录像</c> 00:00:43.210 --> 00:00:45.379 <c.magenta>ReplayKit给</c> <c.magenta>我们的用户提供这些功能</c> 00:00:45.546 --> 00:00:47.915 <c.magenta>而只需要你 开发者 做很少量的</c> <c.magenta>工作</c> 00:00:49.716 --> 00:00:50.918 <c.magenta>今天的开始</c> 00:00:50.984 --> 00:00:51.985 <c.magenta>我会花几分钟</c> 00:00:52.052 --> 00:00:55.122 <c.magenta>谈谈ReplayKit已提供的功能</c> 00:00:57.691 --> 00:01:01.195 <c.magenta>ReplayKit提供录制应用的</c> <c.magenta>音频和视觉内容的功能</c> 00:00:57.691 --> 00:01:01.195 <c.magenta>ReplayKit提供录制应用的</c> <c.magenta>音频和视觉内容的功能</c> 00:01:01.828 --> 00:01:04.397 <c.magenta>此外你可以启用麦克风录制</c> 00:01:05.032 --> 00:01:08.902 <c.magenta>通过这样做 你的用户在玩游戏时</c> <c.magenta>可以提供声音说明</c> 00:01:09.369 --> 00:01:10.904 <c.magenta>当用户完成了一个录像</c> 00:01:11.371 --> 00:01:13.607 <c.magenta>他们可以在游戏中分享录像</c> 00:01:13.674 --> 00:01:15.008 <c.magenta>通过系统共享表</c> 00:01:16.643 --> 00:01:19.580 <c.magenta>ReplayKit有一个简单API</c> <c.magenta>你今天会看到它</c> 00:01:19.980 --> 00:01:23.450 <c.magenta>将这些功能加入你的游戏</c> <c.magenta>需要少量的代码</c> 00:01:25.285 --> 00:01:28.689 <c.magenta>以后ReplayKit将产生</c> <c.magenta>HD质量的视频</c> 00:01:29.022 --> 00:01:31.191 <c.magenta>并且对游戏性能的影响很小</c> 00:01:31.325 --> 00:01:34.461 <c.magenta>并且从设备电池中使用最少的电量</c> 00:01:35.929 --> 00:01:39.566 <c.magenta>在Apple 用户隐私对我们很重要</c> 00:01:40.200 --> 00:01:42.436 <c.magenta>所以我们实现了一些隐私保护措施</c> 00:01:42.703 --> 00:01:46.373 <c.magenta>比如我们在用户开始录制前会</c> <c.magenta>显示一个提示</c> 00:01:46.907 --> 00:01:50.043 <c.magenta>用户可以在录制他们的游戏前</c> <c.magenta>给予许可</c> 00:01:50.844 --> 00:01:51.678 <c.magenta>而且</c> 00:01:52.179 --> 00:01:55.182 <c.magenta>录制会排除系统UI</c> <c.magenta>包括通知</c> 00:01:55.782 --> 00:01:56.617 <c.magenta>所以</c> 00:01:56.817 --> 00:01:59.186 <c.magenta>当你在玩游戏时收到文字消息时</c> 00:01:59.253 --> 00:02:01.054 <c.magenta>这条消息不会被录下来</c> 00:01:59.253 --> 00:02:01.054 <c.magenta>这条消息不会被录下来</c> 00:02:03.190 --> 00:02:06.460 <c.magenta>最后 ReplayKit</c> <c.magenta>在iOS 9中可用</c> 00:02:07.160 --> 00:02:10.364 <c.magenta>这是一个ReplayKit目前的</c> <c.magenta>特性的列表</c> 00:02:11.031 --> 00:02:13.367 <c.magenta>现在我会花一些时间</c> 00:02:13.433 --> 00:02:16.503 <c.magenta>来列举ReplayKit框架中</c> <c.magenta>加入的新特性</c> 00:02:17.704 --> 00:02:20.507 <c.magenta>首先 我们把ReplayKit</c> <c.magenta>支持带到了Apple TV</c> 00:02:21.308 --> 00:02:23.877 <c.magenta>所以现在</c> <c.magenta>你可以录制你的游戏</c> 00:02:23.944 --> 00:02:26.246 <c.magenta>并且直接分享它</c> <c.magenta>从你的tvOS游戏中</c> 00:02:27.114 --> 00:02:29.716 <c.magenta>下一个我们加入的新特性是直播</c> 00:02:30.217 --> 00:02:33.554 <c.magenta>现在用户可以广播游戏</c> 00:02:33.620 --> 00:02:36.323 <c.magenta>实时地发送给第三方广播服务</c> 00:02:37.457 --> 00:02:39.059 <c.magenta>第三个也是最后一个特性</c> 00:02:39.426 --> 00:02:42.396 <c.magenta>我们增加了录制FaceTime</c> <c.magenta>摄像头的支持</c> 00:02:43.263 --> 00:02:47.134 <c.magenta>此外 我们增强了麦克风录制API</c> 00:02:49.570 --> 00:02:51.772 <c.magenta>所以当我进入ReplayKit</c> <c.magenta>和Apple TV之前</c> 00:02:51.839 --> 00:02:54.708 <c.magenta>我会给你一个ReplayKit</c> <c.magenta>结构的概览</c> 00:02:55.475 --> 00:02:56.877 <c.magenta>我想向你们展示你们的应用如何</c> 00:02:56.944 --> 00:02:59.813 <c.magenta>使用这个框架来和操作系统互动</c> 00:02:59.880 --> 00:03:00.981 <c.magenta>来创建录像</c> 00:02:59.880 --> 00:03:00.981 <c.magenta>来创建录像</c> 00:03:03.684 --> 00:03:05.152 <c.magenta>所以这里我们有你的应用</c> 00:03:05.552 --> 00:03:07.721 <c.magenta>你的应用通知操作系统</c> 00:03:07.788 --> 00:03:09.256 <c.magenta>它什么时候想要开始录制</c> 00:03:10.324 --> 00:03:13.193 <c.magenta>所以ReplayKit提供</c> <c.magenta>RPScreenRecorder类</c> 00:03:13.560 --> 00:03:15.529 <c.magenta>你会告诉这个类开始录制</c> 00:03:16.330 --> 00:03:19.066 <c.magenta>这时</c> <c.magenta>一条消息被发送给重播守护进程</c> 00:03:19.499 --> 00:03:22.202 <c.magenta>重播守护进程会开始写入你应用的数据</c> 00:03:22.703 --> 00:03:24.037 <c.magenta>到一个电影文件</c> 00:03:25.939 --> 00:03:28.475 <c.magenta>当你告诉RPScreenRecorder停止录像</c> 00:03:28.842 --> 00:03:31.512 <c.magenta>重播守护进程会结束你的电影</c> 00:03:32.246 --> 00:03:34.081 <c.magenta>现在我们在系统里有一个电影</c> 00:03:34.248 --> 00:03:37.050 <c.magenta>现在这个电影需要回到你的应用</c> 00:03:37.117 --> 00:03:41.455 <c.magenta>这样用户可以预览他们刚完成的</c> <c.magenta>录制</c> 00:03:42.022 --> 00:03:42.856 <c.magenta>要这么做</c> 00:03:43.724 --> 00:03:46.360 <c.magenta>我们提供RPpreviewViewController</c> 00:03:46.927 --> 00:03:48.996 <c.magenta>你在游戏中使用这个视图控制器</c> 00:03:49.396 --> 00:03:51.899 <c.magenta>这样用户有一个界面来预览</c> 00:03:51.965 --> 00:03:54.902 <c.magenta>他们可以编辑和分享刚完成的视频</c> 00:03:57.938 --> 00:04:00.874 <c.magenta>就像我们刚刚看到的 我们有</c> <c.magenta>RPScreenRecorder类</c> 00:03:57.938 --> 00:04:00.874 <c.magenta>就像我们刚刚看到的 我们有</c> <c.magenta>RPScreenRecorder类</c> 00:04:01.074 --> 00:04:04.778 <c.magenta>你会用这个类来开始 停止和抛弃录制</c> 00:04:05.312 --> 00:04:08.782 <c.magenta>你还会用它来检查</c> <c.magenta>是否能在这台设备上录像</c> 00:04:09.716 --> 00:04:12.152 <c.magenta>RPScreenRecorder</c> <c.magenta>有一个代理属性</c> 00:04:12.219 --> 00:04:15.856 <c.magenta>当能否在设备上录像发生改变时</c> <c.magenta>会通知你</c> 00:04:16.523 --> 00:04:19.927 <c.magenta>它也会在因为错误停止录制时通知你</c> 00:04:21.928 --> 00:04:24.631 <c.magenta>第二个类是RPPreviewController</c> 00:04:24.998 --> 00:04:27.000 <c.magenta>这个视图控制器出现在你的游戏中</c> 00:04:27.167 --> 00:04:30.804 <c.magenta>使你的用户能够预览录像</c> 00:04:30.871 --> 00:04:32.773 <c.magenta>在iOS上编辑和剪接录像</c> 00:04:33.240 --> 00:04:35.676 <c.magenta>直接从游戏里分享录像</c> 00:04:36.643 --> 00:04:38.612 <c.magenta>这个类还有委托方法</c> 00:04:38.812 --> 00:04:41.181 <c.magenta>它们会让你知道什么时候用户完成了</c> 00:04:41.248 --> 00:04:42.716 <c.magenta>在预览用户界面中完成了</c> 00:04:44.518 --> 00:04:47.387 <c.magenta>这就是你要使用的</c> 00:04:47.454 --> 00:04:51.024 <c.magenta>用来在iOS和tvOS上</c> <c.magenta>录制和分享内容的结构和类</c> 00:04:51.658 --> 00:04:53.961 <c.magenta>现在让我来到ReplayKit和Apple TV</c> 00:04:54.394 --> 00:04:56.396 <c.magenta>我会从一个演示开始</c> 00:05:06.073 --> 00:05:08.175 <c.magenta>我有一个游戏叫做狐狸</c> 00:05:08.242 --> 00:05:12.412 <c.magenta>狐狸是为2015年的 WWDC</c> <c.magenta>开发的它是用SceneKit开发的</c> 00:05:13.614 --> 00:05:14.748 <c.magenta>你可能认出它了</c> 00:05:14.815 --> 00:05:17.684 <c.magenta>因为在我们的开发者网站上它被</c> <c.magenta>做为代码的例子</c> 00:05:18.285 --> 00:05:19.953 <c.magenta>目标是在这关走动</c> 00:05:20.020 --> 00:05:22.022 <c.magenta>收集这些花像我刚刚得到的这朵</c> 00:05:22.723 --> 00:05:25.459 <c.magenta>我会走过这一关并收集花</c> 00:05:25.526 --> 00:05:27.594 <c.magenta>这关有三朵花并且我得到了第一朵</c> 00:05:28.128 --> 00:05:30.564 <c.magenta>你可以在路上选择性的收集这些珍珠</c> 00:05:31.031 --> 00:05:33.400 <c.magenta>但是我会把注意力集中在花上</c> <c.magenta>我得到了两朵</c> 00:05:33.867 --> 00:05:36.770 <c.magenta>我知道第三朵花在顶部的中间</c> 00:05:36.837 --> 00:05:38.005 <c.magenta>在这块石头上</c> 00:05:40.507 --> 00:05:42.709 <c.magenta>所以在此我要打开</c> 00:05:42.776 --> 00:05:44.978 <c.magenta>我要打开游戏菜单</c> 00:05:45.979 --> 00:05:48.715 <c.magenta>我想要录制它 前面有一个障碍</c> 00:05:48.782 --> 00:05:51.018 <c.magenta>我上周练习了很多</c> 00:05:51.318 --> 00:05:54.054 <c.magenta>所以我想要把这和我的朋友分享</c> <c.magenta>来向他们表明</c> 00:05:54.488 --> 00:05:56.523 <c.magenta>现在大部分时间我都可以穿过这个障碍</c> 00:05:57.357 --> 00:05:58.892 <c.magenta>我要开始我的录制</c> 00:05:58.959 --> 00:06:01.061 <c.magenta>这是我提过的同意提示</c> 00:05:58.959 --> 00:06:01.061 <c.magenta>这是我提过的同意提示</c> 00:06:01.862 --> 00:06:03.330 <c.magenta>我会给许可</c> 00:06:04.631 --> 00:06:05.766 <c.magenta>所以我现在在录制</c> 00:06:06.867 --> 00:06:09.469 <c.magenta>请注意在屏幕顶端的录制指示器</c> 00:06:10.838 --> 00:06:12.906 <c.magenta>这表明录制正在进行</c> 00:06:12.973 --> 00:06:14.274 <c.magenta>好的 我穿过了火</c> 00:06:14.775 --> 00:06:16.910 <c.magenta>现在我要做的就是走到终点</c> 00:06:17.244 --> 00:06:18.478 <c.magenta>来得到最后一朵花</c> 00:06:19.613 --> 00:06:20.714 <c.magenta>这样我就能结束这关</c> 00:06:21.148 --> 00:06:22.916 <c.magenta>并且结束录制</c> 00:06:26.720 --> 00:06:27.588 <c.magenta>就是这些了</c> 00:06:28.388 --> 00:06:29.756 <c.magenta>我要停止录制</c> 00:06:30.390 --> 00:06:32.559 <c.magenta>一旦停止了 我可以选择</c> 00:06:32.626 --> 00:06:35.963 <c.magenta>预览或分享我刚录制的视频</c> <c.magenta>所以我要开始预览</c> 00:06:36.997 --> 00:06:38.365 <c.magenta>所以我们有一个视频播放</c> 00:06:38.432 --> 00:06:40.934 <c.magenta>我们有一个进度条可以用来向前向后跳</c> 00:06:41.535 --> 00:06:43.070 <c.magenta>我要开始播放它</c> 00:06:44.872 --> 00:06:48.041 <c.magenta>请注意录制指示器不会出现在录像中</c> 00:06:48.208 --> 00:06:50.711 <c.magenta>我等会会向你们展示这是如何完成的</c> 00:06:51.545 --> 00:06:54.147 <c.magenta>我有一个视频 我对它感到满意</c> 00:06:54.781 --> 00:06:55.849 <c.magenta>所以想要分享它</c> 00:06:56.650 --> 00:06:58.385 <c.magenta>我会来到这选择分享</c> 00:07:00.153 --> 00:07:02.422 <c.magenta>我们会看到一个AirDrop界面</c> 00:07:03.056 --> 00:07:04.324 <c.magenta>我会拿到我的手机</c> 00:07:08.562 --> 00:07:09.863 <c.magenta>我会选择我的手机</c> 00:07:15.202 --> 00:07:19.540 <c.magenta>当我在手机上接受这个文件</c> 00:07:19.606 --> 00:07:20.774 <c.magenta>文件被传输了</c> 00:07:21.074 --> 00:07:23.277 <c.magenta>一旦它在我的手机上</c> 00:07:23.343 --> 00:07:24.711 <c.magenta>我可以预览视频</c> 00:07:25.012 --> 00:07:27.447 <c.magenta>如果我想我可以编辑和剪接视频</c> 00:07:27.514 --> 00:07:30.217 <c.magenta>我可把它分享到最喜欢的社交媒体网站</c> 00:07:36.290 --> 00:07:38.926 <c.magenta>这就是ReplayKit在</c> <c.magenta>Apple TV上看起来的样子</c> 00:07:39.826 --> 00:07:41.395 <c.magenta>我现在想花一点时间</c> 00:07:41.461 --> 00:07:43.730 <c.magenta>来强调这个演示里的4个主要重点</c> 00:07:44.464 --> 00:07:46.133 <c.magenta>然后我会向你们展示代码</c> 00:07:46.200 --> 00:07:48.836 <c.magenta>和那些重点对应的代码</c> 00:07:49.303 --> 00:07:51.371 <c.magenta>让我开始 我会有游戏中的菜单</c> 00:07:51.438 --> 00:07:52.773 <c.magenta>在这我可以开始录制</c> 00:07:54.474 --> 00:07:57.544 <c.magenta>然后我们继续玩游戏</c> <c.magenta>屏幕上会有录制指示器</c> 00:07:59.213 --> 00:08:01.548 <c.magenta>回到游戏菜单来停止录制</c> 00:07:59.213 --> 00:08:01.548 <c.magenta>回到游戏菜单来停止录制</c> 00:08:02.516 --> 00:08:04.551 <c.magenta>当我停止录制时 我有不同的选项</c> 00:08:04.618 --> 00:08:07.321 <c.magenta>预览或者分享录制的视频</c> 00:08:08.488 --> 00:08:10.090 <c.magenta>我会浏览它们每一个</c> 00:08:10.157 --> 00:08:12.092 <c.magenta>并向你们展示相应的代码</c> 00:08:12.593 --> 00:08:14.027 <c.magenta>让我们从开始录制开始</c> 00:08:14.828 --> 00:08:16.697 <c.magenta>当我按下开始录制按钮</c> 00:08:16.763 --> 00:08:20.267 <c.magenta>首先我要获得共享的</c> <c.magenta>RPScreeningRecorder实例</c> 00:08:21.401 --> 00:08:23.637 <c.magenta>我简单地告诉它开始录制</c> 00:08:24.037 --> 00:08:26.907 <c.magenta>一旦我在录制</c> <c.magenta>我们显示指示器视图</c> 00:08:29.676 --> 00:08:31.211 <c.magenta>像我在视频中提到的</c> 00:08:31.278 --> 00:08:33.447 <c.magenta>指示器不会包含在录像中</c> 00:08:33.714 --> 00:08:37.484 <c.magenta>这是因为ReplayKit</c> <c.magenta>只会录制应用的主窗口</c> 00:08:37.784 --> 00:08:38.652 <c.magenta>所以</c> 00:08:38.919 --> 00:08:40.921 <c.magenta>我会新建一个UI窗口</c> 00:08:42.289 --> 00:08:43.190 <c.magenta>这个指示器视图</c> 00:08:43.256 --> 00:08:45.993 <c.magenta>创建这个指示器视图是你的责任</c> 00:08:46.360 --> 00:08:49.263 <c.magenta>这是因为你可使它和你的游戏样式匹配</c> 00:08:49.329 --> 00:08:50.397 <c.magenta>一个指示器视图</c> 00:08:50.464 --> 00:08:53.133 <c.magenta>我会初始化一个指示器视图的实例</c> 00:08:53.200 --> 00:08:56.036 <c.magenta>并简单地把它做为一个子视图</c> <c.magenta>加到我创建的主窗口中</c> 00:08:56.103 --> 00:08:58.138 <c.magenta>在我上面创建的窗口</c> 00:08:58.572 --> 00:09:00.374 <c.magenta>现在指示器视图出现在屏幕上</c> 00:08:58.572 --> 00:09:00.374 <c.magenta>现在指示器视图出现在屏幕上</c> 00:09:01.175 --> 00:09:02.442 <c.magenta>我们知道我们在录制</c> 00:09:03.644 --> 00:09:04.845 <c.magenta>当我们完成了录制</c> 00:09:05.445 --> 00:09:06.880 <c.magenta>我们按下停止录制按钮</c> 00:09:07.447 --> 00:09:10.584 <c.magenta>再一次 我要获得共享的</c> <c.magenta>RPScreenRecorder实例</c> 00:09:11.552 --> 00:09:13.954 <c.magenta>现在注意我们返回预览视图控制器</c> 00:09:14.021 --> 00:09:17.324 <c.magenta>是我早前提过的</c> <c.magenta>RPPreviewController类</c> 00:09:18.625 --> 00:09:20.227 <c.magenta>我要隐藏我的指示器视图</c> 00:09:20.827 --> 00:09:23.063 <c.magenta>在这有一个重要的地方是保留一个引用</c> 00:09:23.130 --> 00:09:24.665 <c.magenta>预览视图控制器的引用</c> 00:09:25.132 --> 00:09:27.467 <c.magenta>因为我们会用它来显示下一步</c> 00:09:27.534 --> 00:09:29.903 <c.magenta>用来预览或分享视频</c> 00:09:30.904 --> 00:09:32.606 <c.magenta>最后我会设置代表</c> 00:09:34.775 --> 00:09:36.944 <c.magenta>这样我们看到我们有一个预览控制器</c> 00:09:37.010 --> 00:09:39.880 <c.magenta>但是我们有两个界面</c> <c.magenta>一个用来预览 一个用来分享</c> 00:09:41.181 --> 00:09:43.750 <c.magenta>在Apple TV中</c> <c.magenta>我们引入了一个新的模式属性</c> 00:09:44.852 --> 00:09:47.855 <c.magenta>当我们想要预览时</c> <c.magenta>我们简单地把模式设置成预览</c> 00:09:47.921 --> 00:09:49.656 <c.magenta>然后显示一个视图控制器</c> 00:09:51.191 --> 00:09:52.593 <c.magenta>类似的 要分享</c> 00:09:53.327 --> 00:09:54.761 <c.magenta>我们有模式属性</c> 00:09:55.128 --> 00:09:57.798 <c.magenta>我们要把模式设置成分享</c> 00:09:57.865 --> 00:09:59.600 <c.magenta>再一次显示视图控制器</c> 00:09:59.900 --> 00:10:02.236 <c.magenta>现在我们会显示AirDrop界面</c> 00:09:59.900 --> 00:10:02.236 <c.magenta>现在我们会显示AirDrop界面</c> 00:10:04.872 --> 00:10:07.641 <c.magenta>在两种情况下 当用户完成了每个界面</c> 00:10:07.708 --> 00:10:09.743 <c.magenta>我们有委托方法会被调用</c> 00:10:10.010 --> 00:10:11.645 <c.magenta>预览控制器结束</c> 00:10:12.679 --> 00:10:15.015 <c.magenta>很重要的一点是它会被调用时</c> <c.magenta>你刚好——</c> 00:10:15.082 --> 00:10:16.783 <c.magenta>你让预览控制器离开</c> 00:10:16.850 --> 00:10:19.319 <c.magenta>因为你的应用需要负责显示它</c> 00:10:21.588 --> 00:10:22.589 <c.magenta>最后</c> 00:10:22.656 --> 00:10:25.859 <c.magenta>当你完成了录制而且我们知道</c> <c.magenta>我们不再需要它</c> 00:10:25.926 --> 00:10:28.095 <c.magenta>一个好的惯例是删除录像</c> 00:10:28.395 --> 00:10:31.431 <c.magenta>现在ReplayKit</c> <c.magenta>会自动删除之前的录像</c> 00:10:31.498 --> 00:10:32.900 <c.magenta>当新的录像开始时</c> 00:10:33.500 --> 00:10:36.303 <c.magenta>这是因为一次一个应用只允许一个录像</c> 00:10:37.337 --> 00:10:39.673 <c.magenta>你也可以明确的删除这个录像</c> 00:10:39.740 --> 00:10:41.975 <c.magenta>当你知道预览不可用</c> 00:10:42.276 --> 00:10:44.144 <c.magenta>比如 可能在这关的最后</c> 00:10:44.211 --> 00:10:46.880 <c.magenta>没有机会显示预览</c> 00:10:47.281 --> 00:10:49.149 <c.magenta>这样你就可以明确地删除它</c> 00:10:49.216 --> 00:10:51.985 <c.magenta>通过调用RPScreenRecorder的</c> <c.magenta>删除录像方法</c> 00:10:54.254 --> 00:10:55.856 <c.magenta>在最后这几张幻灯片中</c> 00:10:55.923 --> 00:10:58.125 <c.magenta>我向你们展示了需要的代码量</c> 00:10:58.192 --> 00:11:00.894 <c.magenta>来把这些功能加入你的tvOS游戏</c> 00:10:58.192 --> 00:11:00.894 <c.magenta>来把这些功能加入你的tvOS游戏</c> 00:11:01.828 --> 00:11:04.731 <c.magenta>我鼓励你们都把ReplayKit</c> <c.magenta>添加到你们的tvOS应用中</c> 00:11:04.998 --> 00:11:07.501 <c.magenta>也添加到iOS应用中</c> <c.magenta>如果你们还没有这么做</c> 00:11:10.671 --> 00:11:13.473 <c.magenta>我们花点时间总结ReplayKit</c> <c.magenta>和Apple TV</c> 00:11:14.374 --> 00:11:15.876 <c.magenta>现在有了ReplayKit</c> <c.magenta>和Apple TV</c> 00:11:15.943 --> 00:11:18.745 <c.magenta>你可以录制应用的音频和视频内容</c> 00:11:19.980 --> 00:11:23.483 <c.magenta>在Apple TV中</c> <c.magenta>麦克风被系统保留了</c> 00:11:23.917 --> 00:11:27.054 <c.magenta>所以你不能在这个平台上提供语音说明</c> 00:11:27.788 --> 00:11:30.257 <c.magenta>但是你可以允许用户预览视频</c> 00:11:30.324 --> 00:11:32.860 <c.magenta>而且直接在游戏中分享视频</c> 00:11:34.962 --> 00:11:37.064 <c.magenta>如你所见 我们有一个很简单的API</c> 00:11:37.130 --> 00:11:40.400 <c.magenta>其实这和我们提供给</c> <c.magenta>iOS的API是相同的</c> 00:11:41.268 --> 00:11:45.405 <c.magenta>现在所有提供给Apple TV的</c> <c.magenta>这些特性将在tvOS 10中可用</c> 00:11:47.107 --> 00:11:48.942 <c.magenta>这就是ReplayKit</c> <c.magenta>和Apple TV</c> 00:11:49.409 --> 00:11:52.045 <c.magenta>现在是时间来到我们的第二个新特性</c> 00:11:52.112 --> 00:11:54.448 <c.magenta>我个人对它感到很兴奋</c> 00:11:55.048 --> 00:11:58.252 <c.magenta>现在请欢迎</c> <c.magenta>Edwin Iskandar上台</c> 00:12:02.523 --> 00:12:03.624 <c.magenta>好的谢谢大家</c> 00:12:05.559 --> 00:12:06.527 <c.magenta>嘿你们好吗?</c> 00:12:06.593 --> 00:12:08.996 <c.magenta>我是Edwin Iskandar</c> <c.magenta>软件工程师</c> 00:12:09.062 --> 00:12:11.064 <c.magenta>在Apple的游戏技术组</c> 00:12:11.331 --> 00:12:13.433 <c.magenta>和Ben一样我也非常高兴</c> 00:12:13.500 --> 00:12:15.369 <c.magenta>和你们谈论我们的下一个特性</c> 00:12:15.769 --> 00:12:16.737 <c.magenta>直播</c> 00:12:18.672 --> 00:12:19.740 <c.magenta>有了直播</c> 00:12:19.806 --> 00:12:23.644 <c.magenta>玩家可以广播他们的游戏到第三方服务</c> 00:12:23.710 --> 00:12:26.513 <c.magenta>直接从他们的iOS或tvOS设备</c> 00:12:27.381 --> 00:12:28.615 <c.magenta>这很令人兴奋</c> 00:12:28.682 --> 00:12:31.018 <c.magenta>因为这第一次成为可能</c> 00:12:31.084 --> 00:12:32.553 <c.magenta>无需额外的硬件</c> 00:12:32.886 --> 00:12:34.188 <c.magenta>或者第三方SDK</c> 00:12:35.622 --> 00:12:37.124 <c.magenta>允许用户利用</c> 00:12:37.191 --> 00:12:40.627 <c.magenta>他们的设备的强大的FaceTime</c> <c.magenta>摄像头和麦克风</c> 00:12:40.694 --> 00:12:42.796 <c.magenta>来提供实时的丰富的说明</c> 00:12:43.864 --> 00:12:45.866 <c.magenta>最后我们所做的一切都是安全的</c> 00:12:45.933 --> 00:12:49.603 <c.magenta>保证所有的音频和视频都只有</c> <c.magenta>系统</c> 00:12:50.270 --> 00:12:51.471 <c.magenta>以及广播服务可以访问</c> 00:12:52.973 --> 00:12:54.441 <c.magenta>那么它是怎么工作的</c> 00:12:54.508 --> 00:12:57.578 <c.magenta>我们和Flaregames</c> <c.magenta>一起实现了广播功能</c> 00:12:57.644 --> 00:12:59.847 <c.magenta>及他们的旗舰游戏</c> <c.magenta>Olympus Rising</c> 00:13:00.347 --> 00:13:02.749 <c.magenta>它现是app store中</c> <c.magenta>一个很棒的游戏</c> 00:13:03.450 --> 00:13:07.087 <c.magenta>它独特的混合了</c> <c.magenta>策略 RPG和动作元素</c> 00:13:08.322 --> 00:13:10.390 <c.magenta>现在我们有一个游戏作为广播源</c> 00:13:10.724 --> 00:13:12.693 <c.magenta>我们还需要广播目标</c> 00:13:13.794 --> 00:13:15.963 <c.magenta>所以我们还和</c> <c.magenta>Mob Crush一起工作</c> 00:13:16.029 --> 00:13:18.632 <c.magenta>它是一个特别针对移动游戏的广播服务</c> 00:13:19.867 --> 00:13:22.970 <c.magenta>所以现在我们有了一个游戏和</c> <c.magenta>一个服务 我们准备好开始了</c> 00:13:23.237 --> 00:13:24.471 <c.magenta>让我们看看在运行的它们</c> 00:13:26.006 --> 00:13:27.941 <c.magenta>在Olympus Rising中</c> <c.magenta>Flare的开发者们</c> 00:13:28.008 --> 00:13:30.978 <c.magenta>实现了游戏中的一个按钮来开始广播</c> 00:13:31.578 --> 00:13:33.947 <c.magenta>要开始广播 用户点击这个按钮</c> 00:13:34.648 --> 00:13:36.583 <c.magenta>然后显示</c> 00:13:36.650 --> 00:13:38.719 <c.magenta>他们已经在设备上安装好的广播服务</c> 00:13:39.019 --> 00:13:42.022 <c.magenta>在这个例子中</c> <c.magenta>用户安装了Mob Crush应用</c> 00:13:42.256 --> 00:13:43.357 <c.magenta>所以它出现在该列表中</c> 00:13:45.225 --> 00:13:47.494 <c.magenta>在这时用户点击</c> <c.magenta>Mob Crush图标</c> 00:13:47.928 --> 00:13:50.864 <c.magenta>他们接着看到Mob Crush</c> <c.magenta>用来设置广播的UI</c> 00:13:52.366 --> 00:13:55.135 <c.magenta>用户继续添加一个标题给这个广播</c> 00:13:56.170 --> 00:13:57.137 <c.magenta>一旦完成了</c> 00:13:57.204 --> 00:13:59.373 <c.magenta>他们简单的按开始广播按钮</c> 00:14:00.541 --> 00:14:03.477 <c.magenta>会回到游戏并显示一个倒计时</c> 00:14:03.544 --> 00:14:04.978 <c.magenta>所以用户可以预备</c> 00:14:05.412 --> 00:14:06.380 <c.magenta>并且最后开始直播</c> 00:14:08.315 --> 00:14:10.717 <c.magenta>现在他们在直播</c> <c.magenta>当用户游玩时</c> 00:14:10.784 --> 00:14:13.520 <c.magenta>视频和音频数据会流入广播服务</c> 00:14:13.820 --> 00:14:16.523 <c.magenta>全球观众可以启动</c> <c.magenta>Mob Crush应用</c> 00:14:16.590 --> 00:14:19.960 <c.magenta>从他们的设备并且几乎实时地观看游戏</c> 00:14:20.494 --> 00:14:21.662 <c.magenta>在Mob Crush应用中</c> 00:14:21.728 --> 00:14:24.398 <c.magenta>观众还可以在观看的同时讨论游戏</c> 00:14:24.464 --> 00:14:28.068 <c.magenta>更酷的是广播者甚至可以马上收到通知</c> 00:14:28.135 --> 00:14:29.870 <c.magenta>当这发生时 当玩他们的游戏时</c> 00:14:30.904 --> 00:14:32.005 <c.magenta>就像在体育中</c> 00:14:32.072 --> 00:14:35.108 <c.magenta>看一些直播的事件会有一些很特别的事</c> 00:14:35.809 --> 00:14:40.581 <c.magenta>现在iOS和tvOS游戏原生</c> <c.magenta>有这些功能</c> 00:14:43.951 --> 00:14:45.686 <c.magenta>我们现在已经看过了整个流程</c> 00:14:45.853 --> 00:14:47.020 <c.magenta>做为一个游戏开发者</c> 00:14:47.087 --> 00:14:49.790 <c.magenta>你可能想知道怎么在你的游戏中</c> <c.magenta>实现这些?</c> 00:14:51.225 --> 00:14:52.826 <c.magenta>这是分解了的玩家流程</c> 00:14:53.126 --> 00:14:54.962 <c.magenta>如你所见 有很多步</c> 00:14:55.429 --> 00:14:56.630 <c.magenta>初始化广播</c> 00:14:57.564 --> 00:14:58.999 <c.magenta>选择一个广播服务</c> 00:14:59.333 --> 00:15:00.501 <c.magenta>设置这个广播</c> 00:14:59.333 --> 00:15:00.501 <c.magenta>设置这个广播</c> 00:15:02.803 --> 00:15:04.538 <c.magenta>开始和停止广播</c> 00:15:04.872 --> 00:15:06.773 <c.magenta>标明一个广播正在进行中</c> 00:15:07.207 --> 00:15:10.310 <c.magenta>上传视频和音频数据到后台服务器</c> 00:15:10.711 --> 00:15:12.813 <c.magenta>这最初看起来可能让人望而却步</c> 00:15:12.880 --> 00:15:14.982 <c.magenta>但是对游戏开发者的好消息是</c> 00:15:15.048 --> 00:15:18.452 <c.magenta>其中的三步被ReplayKit</c> <c.magenta>和广播服务处理</c> 00:15:24.958 --> 00:15:27.327 <c.magenta>所以让我们看看每一步的代码</c> 00:15:27.694 --> 00:15:29.963 <c.magenta>要用程序初始化一次广播</c> 00:15:30.030 --> 00:15:33.400 <c.magenta>我们用一个新的类名叫RP</c> <c.magenta>BroadcastActivityViewController</c> 00:15:33.467 --> 00:15:35.569 <c.magenta>且调用它的载入方法</c> <c.magenta>来获得它的一个实例</c> 00:15:36.236 --> 00:15:39.439 <c.magenta>然后我们简单地显示它</c> <c.magenta>就像其他UI视图控制器一样</c> 00:15:40.040 --> 00:15:42.809 <c.magenta>会给用户显示一个广播服务的列表</c> 00:15:42.876 --> 00:15:45.345 <c.magenta>最终允许用户建立广播</c> 00:15:46.213 --> 00:15:47.548 <c.magenta>在我们开始做这些前</c> 00:15:47.614 --> 00:15:50.450 <c.magenta>我们还设置</c> <c.magenta>ActivityViewController委托方法</c> 00:15:51.285 --> 00:15:53.820 <c.magenta>因为我们想要当设置完成时收到通知</c> 00:15:55.722 --> 00:15:58.492 <c.magenta>在这时 用户可以选择要广播到的服务</c> 00:15:58.825 --> 00:16:00.093 <c.magenta>建立广播</c> 00:15:58.825 --> 00:16:00.093 <c.magenta>建立广播</c> 00:16:00.460 --> 00:16:01.828 <c.magenta>一旦你完成了设置</c> 00:16:02.095 --> 00:16:04.698 <c.magenta>活动视图控制器的委托方法就被触发</c> 00:16:05.232 --> 00:16:08.802 <c.magenta>这个委托方法被另一个新类提供</c> 00:16:08.869 --> 00:16:10.470 <c.magenta>RPBroadcastController</c> 00:16:10.537 --> 00:16:12.306 <c.magenta>它允许我们开始广播</c> 00:16:12.940 --> 00:16:15.375 <c.magenta>但是在我们这么做之前 我们还希望</c> 00:16:15.943 --> 00:16:19.546 <c.magenta>抛弃ActivityViewController</c> <c.magenta>因为是我们显示了它</c> 00:16:20.214 --> 00:16:22.049 <c.magenta>开始在游戏中显示倒计时</c> 00:16:22.616 --> 00:16:24.184 <c.magenta>当倒计时结束</c> 00:16:24.918 --> 00:16:28.355 <c.magenta>我们最终开始广播</c> <c.magenta>通过调用开始广播</c> 00:16:28.422 --> 00:16:32.359 <c.magenta>在新的RPBroadcastController</c> <c.magenta>被传入的实例</c> 00:16:34.294 --> 00:16:35.128 <c.magenta>现在我们在直播了</c> 00:16:35.529 --> 00:16:37.130 <c.magenta>因为我们在直播</c> 00:16:37.264 --> 00:16:39.233 <c.magenta>我们需要清楚地向用户指明这点</c> 00:16:39.933 --> 00:16:41.969 <c.magenta>Olympus Rising</c> <c.magenta>在这点上做得很好</c> 00:16:42.035 --> 00:16:43.637 <c.magenta>通过给广播按钮加动画效果</c> 00:16:44.538 --> 00:16:46.607 <c.magenta>因为这个游戏有很复杂的操作</c> 00:16:46.673 --> 00:16:50.310 <c.magenta>他们重用按钮UI</c> <c.magenta>来指示正在进行的广播</c> 00:16:50.611 --> 00:16:52.412 <c.magenta>来最大化可用的屏幕空间</c> 00:16:53.447 --> 00:16:57.150 <c.magenta>一些需要注意的事是指示器是</c> <c.magenta>广播过程中严格要求的</c> 00:16:57.217 --> 00:16:58.986 <c.magenta>会在应用审核时强制实行</c> 00:17:00.287 --> 00:17:01.755 <c.magenta>在你把它加入游戏前</c> 00:17:02.723 --> 00:17:05.392 <c.magenta>所以用程序检查是否在进行广播</c> 00:17:05.459 --> 00:17:08.929 <c.magenta>简单地查询broadcastController</c> <c.magenta>的isBroadcasting属性</c> 00:17:09.396 --> 00:17:11.397 <c.magenta>你可以使用这个属性的值</c> 00:17:11.464 --> 00:17:14.334 <c.magenta>来开始或停止你的指示UI动画</c> 00:17:16.869 --> 00:17:20.174 <c.magenta>要允许用户结束广播</c> <c.magenta>Flare的开发者实现了</c> 00:17:20.240 --> 00:17:23.844 <c.magenta>一个弹出式UI来显示一个包含</c> <c.magenta>停止按钮的子菜单</c> 00:17:24.678 --> 00:17:26.579 <c.magenta>当用户按下停止按钮</c> 00:17:27.146 --> 00:17:30.417 <c.magenta>我们简单地在控制器上调用</c> <c.magenta>结束广播</c> 00:17:31.385 --> 00:17:34.021 <c.magenta>当广播结束时 我们更新UI</c> 00:17:35.088 --> 00:17:36.924 <c.magenta>现在我们覆盖了基本的流程</c> 00:17:36.990 --> 00:17:39.860 <c.magenta>让我们看看更多细节 比如错误处理</c> 00:17:41.862 --> 00:17:44.031 <c.magenta>因为这个功能有很多部分</c> 00:17:44.097 --> 00:17:45.966 <c.magenta>有可能事情出错</c> 00:17:46.266 --> 00:17:48.268 <c.magenta>所以优美的处理它很重要</c> 00:17:49.002 --> 00:17:51.605 <c.magenta>让我们看看在广播中我们怎么做</c> 00:17:52.773 --> 00:17:55.943 <c.magenta>要处理错误 简单地在广播控制器中</c> <c.magenta>设置代表</c> 00:17:57.411 --> 00:18:00.881 <c.magenta>一旦设定好 你的代表会有</c> <c.magenta>它的didFinishWithError方法</c> 00:17:57.411 --> 00:18:00.881 <c.magenta>一旦设定好 你的代表会有</c> <c.magenta>它的didFinishWithError方法</c> 00:18:00.948 --> 00:18:02.316 <c.magenta>当错误发生时被调用</c> 00:18:02.983 --> 00:18:04.184 <c.magenta>当这被触发时</c> 00:18:04.251 --> 00:18:07.354 <c.magenta>你应该让用户知道它并且</c> <c.magenta>对UI做任何需要的更新</c> 00:18:09.456 --> 00:18:12.159 <c.magenta>现在另一个细节要考虑是当用户</c> <c.magenta>把应用放入后台</c> 00:18:12.226 --> 00:18:14.862 <c.magenta>或者应用在广播过程中被打断了</c> 00:18:14.928 --> 00:18:16.730 <c.magenta>比如说接到来电</c> 00:18:17.698 --> 00:18:19.499 <c.magenta>应用进入后台</c> 00:18:19.566 --> 00:18:22.169 <c.magenta>ReplayKit会自动暂停广播</c> 00:18:23.170 --> 00:18:25.105 <c.magenta>在这个例子中 当应用</c> 00:18:25.172 --> 00:18:27.508 <c.magenta>被重新激活并回到前台</c> 00:18:27.574 --> 00:18:30.677 <c.magenta>我们提示用户并询问他们</c> <c.magenta>是否想要继续广播</c> 00:18:31.078 --> 00:18:32.412 <c.magenta>如果用户想要继续</c> 00:18:32.913 --> 00:18:34.915 <c.magenta>调用继续广播的方法</c> 00:18:35.215 --> 00:18:38.185 <c.magenta>如果他们不想继续</c> <c.magenta>调用结束广播的方法</c> 00:18:39.653 --> 00:18:40.754 <c.magenta>这样就行了</c> 00:18:40.821 --> 00:18:43.223 <c.magenta>对这整个流程 游戏开发者需要</c> 00:18:43.290 --> 00:18:45.659 <c.magenta>和两个类及它们的代表互动</c> 00:18:45.726 --> 00:18:49.296 <c.magenta>RPBroadcastActivityView</c> <c.magenta>Controller代表广播服务</c> 00:18:49.363 --> 00:18:51.031 <c.magenta>允许用户建立一个广播</c> 00:18:51.565 --> 00:18:56.236 <c.magenta>RPBroadcastController用来开始</c> <c.magenta>暂停 继续和结束一个广播</c> 00:18:57.137 --> 00:19:00.807 <c.magenta>如你所见 把广播添加到你的游戏</c> <c.magenta>中不能更容易了</c> 00:18:57.137 --> 00:19:00.807 <c.magenta>如你所见 把广播添加到你的游戏</c> <c.magenta>中不能更容易了</c> 00:19:00.874 --> 00:19:03.410 <c.magenta>我催促你这么做 因为好处很大</c> 00:19:04.011 --> 00:19:06.113 <c.magenta>没有更好的方法来传播口碑</c> 00:19:06.446 --> 00:19:07.948 <c.magenta>增加玩家的参与</c> 00:19:08.248 --> 00:19:10.517 <c.magenta>甚至围绕你的游戏创建一个社区</c> 00:19:12.953 --> 00:19:14.588 <c.magenta>所以这些覆盖了游戏的实现</c> 00:19:14.755 --> 00:19:17.858 <c.magenta>但是关于玩家广播去的</c> <c.magenta>那些广播服务呢?</c> 00:19:17.958 --> 00:19:19.059 <c.magenta>比如Mob Crush?</c> 00:19:20.227 --> 00:19:23.697 <c.magenta>让我们花点时间简短地谈谈这些</c> <c.magenta>服务的职责是什么</c> 00:19:24.164 --> 00:19:27.367 <c.magenta>对所有在座及在网上观看的开发者们</c> 00:19:27.434 --> 00:19:28.836 <c.magenta>我想使它很清楚</c> 00:19:28.902 --> 00:19:31.038 <c.magenta>在下一部分讨论的话题</c> 00:19:31.104 --> 00:19:33.640 <c.magenta>不是你要负责在你的游戏中实现的</c> 00:19:35.809 --> 00:19:37.444 <c.magenta>让我们回到那个流程图</c> 00:19:37.978 --> 00:19:41.281 <c.magenta>我们看到玩家有责任开始一次广播</c> 00:19:41.882 --> 00:19:44.184 <c.magenta>并控制什么时候开始和结束广播</c> 00:19:44.785 --> 00:19:47.287 <c.magenta>我们还看到用来选择广播的UI是</c> 00:19:47.354 --> 00:19:50.757 <c.magenta>ReplayKit的BroadcastActivity</c> <c.magenta>ViewController负责</c> 00:19:51.258 --> 00:19:53.160 <c.magenta>这留给我们两个任务</c> 00:19:53.961 --> 00:19:55.095 <c.magenta>建立广播</c> 00:19:55.963 --> 00:19:58.665 <c.magenta>上传视频和音频数据给后台服务器</c> 00:20:00.167 --> 00:20:02.503 <c.magenta>使广播服务能完成它们的步骤</c> 00:20:02.569 --> 00:20:04.705 <c.magenta>我们引入了一对新的应用扩展</c> 00:20:04.771 --> 00:20:06.073 <c.magenta>特别针对这个功能</c> 00:20:07.574 --> 00:20:10.711 <c.magenta>一个UI扩展允许用户建立一个广播</c> 00:20:11.879 --> 00:20:13.780 <c.magenta>一个非UI扩展为了处理</c> 00:20:13.847 --> 00:20:16.149 <c.magenta>和上传音频和视频数据</c> 00:20:18.385 --> 00:20:20.387 <c.magenta>对那些不熟悉扩展的人</c> 00:20:20.621 --> 00:20:23.991 <c.magenta>它们会嵌入你的母应用</c> <c.magenta>并且是一种方法</c> 00:20:24.057 --> 00:20:26.960 <c.magenta>来扩展你的应用这样你可以和</c> <c.magenta>别的应用一起运行</c> 00:20:28.161 --> 00:20:30.664 <c.magenta>它们在一个来自你的母应用的</c> <c.magenta>一个分开的进程中运行</c> 00:20:30.864 --> 00:20:32.933 <c.magenta>但是可以和你的母应用共享数据</c> 00:20:32.999 --> 00:20:36.403 <c.magenta>可以很方便地用来共享东西</c> <c.magenta>比如授权数据</c> 00:20:37.437 --> 00:20:39.039 <c.magenta>一件要记住的事</c> 00:20:39.173 --> 00:20:42.342 <c.magenta>是和应用相比扩展的资源受限</c> 00:20:42.709 --> 00:20:46.213 <c.magenta>所以避免在它们中进行需要大量</c> <c.magenta>资源的任务</c> 00:20:47.447 --> 00:20:50.884 <c.magenta>我们使得通过Xcode模板来建立</c> <c.magenta>这些扩展变得难以置信的容易</c> 00:20:51.685 --> 00:20:55.088 <c.magenta>这些是iOS和tvOS中新的目标</c> 00:20:56.623 --> 00:20:59.459 <c.magenta>如果从这些模板中创建</c> <c.magenta>扩展将会预先设置好</c> 00:20:59.526 --> 00:21:02.796 <c.magenta>所以他们会出现在广播活动控制</c> <c.magenta>列表中 你看到的那个</c> 00:20:59.526 --> 00:21:02.796 <c.magenta>所以他们会出现在广播活动控制</c> <c.magenta>列表中 你看到的那个</c> 00:21:04.231 --> 00:21:06.400 <c.magenta>让我们看看这两个新扩展</c> 00:21:06.466 --> 00:21:08.468 <c.magenta>一个广播服务需要实现</c> 00:21:08.769 --> 00:21:10.704 <c.magenta>从广播UI扩展开始</c> 00:21:12.472 --> 00:21:14.842 <c.magenta>UI扩展有一些关键职责</c> 00:21:15.209 --> 00:21:17.544 <c.magenta>它负责授权用户</c> 00:21:17.611 --> 00:21:20.047 <c.magenta>并且提供注册</c> <c.magenta>如果用户还没有注册</c> 00:21:20.647 --> 00:21:23.016 <c.magenta>理想地 这些都应该在扩展中完成</c> 00:21:23.083 --> 00:21:25.319 <c.magenta>这样用户体验就没有被打断</c> 00:21:25.919 --> 00:21:27.654 <c.magenta>但是完全可以接受</c> 00:21:27.721 --> 00:21:29.556 <c.magenta>和母应用连接</c> 00:21:29.623 --> 00:21:32.626 <c.magenta>只要用户有办法回到游戏</c> 00:21:34.494 --> 00:21:36.797 <c.magenta>在注册过程中要求显示给用户</c> 00:21:36.864 --> 00:21:38.699 <c.magenta>使用这个服务的条款和条件</c> 00:21:39.132 --> 00:21:42.536 <c.magenta>并且可以接受或拒绝这些条款和条件</c> 00:21:44.037 --> 00:21:45.105 <c.magenta>我们早前看到</c> 00:21:45.172 --> 00:21:47.441 <c.magenta>UI扩展负责允许用户</c> 00:21:47.508 --> 00:21:49.843 <c.magenta>设置他们的广播</c> <c.magenta>比如添加标题</c> 00:21:50.878 --> 00:21:52.846 <c.magenta>它还允许用户</c> 00:21:52.913 --> 00:21:56.450 <c.magenta>通过社交媒体通知其他人</c> <c.magenta>广播将要开始</c> 00:21:58.352 --> 00:22:01.121 <c.magenta>其最终职责是通知ReplayKit</c> 00:21:58.352 --> 00:22:01.121 <c.magenta>其最终职责是通知ReplayKit</c> 00:22:01.188 --> 00:22:02.789 <c.magenta>以及最终这个游戏</c> 00:22:03.090 --> 00:22:04.758 <c.magenta>广播已经完成设置</c> 00:22:07.227 --> 00:22:11.031 <c.magenta>现在我们看过了UI扩展</c> <c.magenta>让我们转到上传扩展</c> 00:22:11.732 --> 00:22:15.035 <c.magenta>它负责接收和处理视频和音频数据</c> 00:22:15.903 --> 00:22:18.071 <c.magenta>并且上传数据给后端服务器</c> 00:22:19.373 --> 00:22:21.608 <c.magenta>我们知道有很多实现</c> 00:22:21.675 --> 00:22:24.378 <c.magenta>关于数据处理和上传到直播流</c> 00:22:24.845 --> 00:22:27.181 <c.magenta>所以我不会进入到</c> 00:22:27.247 --> 00:22:28.215 <c.magenta>这个会话中的特定实现</c> 00:22:28.615 --> 00:22:29.449 <c.magenta>反而</c> 00:22:29.783 --> 00:22:31.151 <c.magenta>如果你是广播服务</c> 00:22:31.251 --> 00:22:34.321 <c.magenta>请联系我们 这样我们可以直接</c> <c.magenta>和你合作</c> 00:22:34.888 --> 00:22:36.323 <c.magenta>这样我们可以实现一个方案</c> 00:22:36.390 --> 00:22:38.792 <c.magenta>将最好的体验带给我们的客户</c> 00:22:41.328 --> 00:22:42.930 <c.magenta>回到我们的流程图</c> 00:22:43.230 --> 00:22:45.832 <c.magenta>我们看过了广播的建立和上传</c> 00:22:47.234 --> 00:22:49.336 <c.magenta>我们已经看过了整个广播流程</c> 00:22:50.504 --> 00:22:53.373 <c.magenta>而且我们清楚地划分了职责给游戏</c> 00:22:54.274 --> 00:22:56.643 <c.magenta>ReplayKit和广播服务</c> 00:22:58.145 --> 00:22:59.580 <c.magenta>这就是直播的全部内容</c> 00:23:00.214 --> 00:23:02.683 <c.magenta>我们真的觉得这是一个</c> <c.magenta>改变游戏规则的功能</c> 00:23:03.283 --> 00:23:04.985 <c.magenta>你的玩家会爱上它</c> 00:23:05.352 --> 00:23:07.554 <c.magenta>对开发者 这会带来一个新方式</c> 00:23:07.621 --> 00:23:10.757 <c.magenta>为你的粉丝体验你的游戏</c> <c.magenta>不仅仅是玩它们</c> 00:23:10.824 --> 00:23:12.192 <c.magenta>还可以观看它们</c> 00:23:14.595 --> 00:23:15.495 <c.magenta>在我们结束前</c> 00:23:15.562 --> 00:23:18.398 <c.magenta>我想要以我们对API做的一些增强</c> <c.magenta>做为结尾</c> 00:23:18.465 --> 00:23:20.234 <c.magenta>关于iOS上的注释</c> 00:23:20.300 --> 00:23:22.369 <c.magenta>也就是支持前置摄像头</c> 00:23:22.469 --> 00:23:24.638 <c.magenta>和新的麦克风功能</c> 00:23:26.206 --> 00:23:28.542 <c.magenta>首先 我们加入了</c> <c.magenta>FaceTime摄像头支持</c> 00:23:28.775 --> 00:23:31.612 <c.magenta>使你可以方便添加</c> <c.magenta>picture in picture</c> 00:23:31.678 --> 00:23:33.113 <c.magenta>视频注释到你的游戏中</c> 00:23:33.747 --> 00:23:35.349 <c.magenta>玩家的反应是无价的</c> 00:23:35.682 --> 00:23:38.852 <c.magenta>永远把这种独特的风味添加到</c> <c.magenta>录像和广播中</c> 00:23:39.586 --> 00:23:41.388 <c.magenta>要在Olympus Rising中</c> <c.magenta>启用它</c> 00:23:41.455 --> 00:23:42.990 <c.magenta>Flare开发者添加了一个按钮</c> 00:23:43.056 --> 00:23:44.758 <c.magenta>在弹出菜单中切换摄像头</c> 00:23:45.459 --> 00:23:47.261 <c.magenta>按这个按钮启用摄像头</c> 00:23:47.327 --> 00:23:48.962 <c.magenta>在左上角显示一个预览</c> 00:23:50.831 --> 00:23:53.033 <c.magenta>让我们看看他们做到这使用的API</c> 00:23:55.035 --> 00:23:56.103 <c.magenta>要打开摄像头</c> 00:23:56.170 --> 00:23:59.673 <c.magenta>我们简单地设置IsCameraEnabled</c> <c.magenta>属性为真 在RPScreenRecorder中</c> 00:24:00.340 --> 00:24:01.875 <c.magenta>这打开摄像头硬件</c> 00:24:02.276 --> 00:24:04.811 <c.magenta>并弹出一个新的</c> <c.magenta>RPScreenRecorder</c> 00:24:04.878 --> 00:24:08.115 <c.magenta>叫做CameraPreviewView</c> <c.magenta>是UIView的一个子类</c> 00:24:08.949 --> 00:24:10.284 <c.magenta>因为它是UIView</c> 00:24:10.350 --> 00:24:12.586 <c.magenta>可简单把它做为一个子视图</c> <c.magenta>加到游戏视图中</c> 00:24:12.920 --> 00:24:16.557 <c.magenta>并且可以自由的给它设定位置来</c> <c.magenta>避免妨碍游戏</c> 00:24:17.991 --> 00:24:19.960 <c.magenta>你还可以附加一个调整或识别它</c> 00:24:20.027 --> 00:24:22.362 <c.magenta>来允许你手动调整它的位置</c> <c.magenta>如果你想的话</c> 00:24:23.564 --> 00:24:25.032 <c.magenta>来看看这的代码</c> 00:24:25.232 --> 00:24:27.367 <c.magenta>我们设置IsCameraEnabled属性为</c> 00:24:27.434 --> 00:24:29.069 <c.magenta>真 在录制广播时</c> 00:24:29.536 --> 00:24:31.939 <c.magenta>然后我们获得</c> <c.magenta>一个CameraPreviewView实例</c> 00:24:34.408 --> 00:24:38.111 <c.magenta>然后设置它的几何来给它定位</c> 00:24:38.912 --> 00:24:41.481 <c.magenta>然后简单地把它作为子视图添加</c> <c.magenta>到你的游戏视图</c> 00:24:43.750 --> 00:24:47.154 <c.magenta>所以现在我们有了视频注释</c> <c.magenta>我们还想要添加音频</c> 00:24:47.788 --> 00:24:51.058 <c.magenta>麦克风录制被包括在了</c> <c.magenta>去年的iOS 9中</c> 00:24:51.391 --> 00:24:54.795 <c.magenta>但是现在我们要添加在录制时</c> <c.magenta>静音的功能</c> 00:24:55.529 --> 00:24:56.597 <c.magenta>我们知道广播者</c> 00:24:56.663 --> 00:25:00.634 <c.magenta>总是有一些有趣的事想说</c> <c.magenta>但是有时他们要休息一下</c> 00:24:56.663 --> 00:25:00.634 <c.magenta>总是有一些有趣的事想说</c> <c.magenta>但是有时他们要休息一下</c> 00:25:01.835 --> 00:25:03.937 <c.magenta>Olympus Rising</c> <c.magenta>使得这变得简单 通过包括</c> 00:25:04.004 --> 00:25:05.873 <c.magenta>麦克风切换在他们的弹出菜单中</c> 00:25:07.708 --> 00:25:10.777 <c.magenta>实现麦克风的切换不能更简单了</c> 00:25:11.211 --> 00:25:13.614 <c.magenta>已有的IsMicrophoneEnabled属性</c> 00:25:13.680 --> 00:25:15.983 <c.magenta>RPScreenRecorder中</c> <c.magenta>可以被设为真</c> 00:25:16.116 --> 00:25:19.920 <c.magenta>如果你想要启用麦克风</c> <c.magenta>或为假如果你想将它静音</c> 00:25:20.888 --> 00:25:24.558 <c.magenta>这可以在广播或录制会话中进行</c> 00:25:27.561 --> 00:25:30.731 <c.magenta>本场演讲到此结束</c> <c.magenta>我希望你们喜欢</c> 00:25:31.064 --> 00:25:34.835 <c.magenta>有了强大的新广播功能和新的</c> <c.magenta>对Apple TV的支持</c> 00:25:34.902 --> 00:25:36.503 <c.magenta>我们等不及去玩</c> 00:25:36.570 --> 00:25:40.240 <c.magenta>和观看你的游戏直播</c> <c.magenta>在iOS和tvOS上</c> 00:25:41.375 --> 00:25:45.379 <c.magenta>想要了解更多信息</c> <c.magenta>请浏览屏幕上的网址</c> 00:25:46.647 --> 00:25:48.749 <c.magenta>在这周中 确保观看</c> 00:25:48.815 --> 00:25:50.450 <c.magenta>我们的其他游戏技术演讲</c> 00:25:50.517 --> 00:25:54.254 <c.magenta>GameplayKit SpriteKit和</c> <c.magenta>Game Center中的新特性</c> 00:25:55.556 --> 00:25:56.690 <c.magenta>好的 我要说的就这么多</c> 00:25:56.757 --> 00:25:58.458 <c.magenta>谢谢参加这次演讲</c> 00:25:58.525 --> 00:26:02.095 <c.magenta>希望你们喜欢这周接下来的 WWDC</c> 00:25:58.525 --> 00:26:02.095 <c.magenta>希望你们喜欢这周接下来的 WWDC</c> 00:26:02.162 --> 00:26:03.096 <c.magenta>谢谢</c>
{ "pile_set_name": "Github" }
(*--------------------------------------------------------------------------- Copyright 2015 Microsoft 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. File: client.fs Description: Prajna Client. A client that waits command to execute. Author: Jin Li, Principal Researcher Microsoft Research, One Microsoft Way Email: jinl at microsoft dot com Date: July. 2015 ---------------------------------------------------------------------------*) namespace Prajna.Core open System open System.Threading open System.Diagnostics open System.IO open System.Net.Sockets open System.Reflection open Prajna.Tools open Prajna.Tools.FSharp open Prajna.Tools.StringTools open Prajna.Tools.Process type internal ClientLauncher() = inherit System.MarshalByRefObject() static let Usage = "PrajnaClient \n\ Command line arguments:\n\ -logdir the dir for the log files\n\ -pwd the passwd used for job request authentication\n\ -mem maximum memory size in MB allowed for the client\n\ -port the port that is used to listen the request\n\ -jobports the range of ports for jobs\n\ " // The name of the semaphore that is informing the test host that the client is ready to serve static member private ReadySemaphoreName = "Prajna-Client-Local-Test-Ready-cd42c4c6-61d8-45fe-8bf9-5ab3345f4f29" // The name of the event that test host uses to inform the client to shutdown static member private ShutdownEventName = "Prajna-Client-Local-Test-Shutdown-cd42c4c6-61d8-45fe-8bf9-5ab3345f4f29" // The name of the event that client uses to notify the host that it has completed shutdown static member private ShutdownCompletionSemaphoreName = "Prajna-Client-Local-Test-Shutdown-Completion-cd42c4c6-61d8-45fe-8bf9-5ab3345f4f29" static member CreateReadySemaphore numClients = new Semaphore(0, numClients, ClientLauncher.ReadySemaphoreName) static member private NotifyClientReady () = let sem = Semaphore.OpenExisting(ClientLauncher.ReadySemaphoreName) sem.Release() |> ignore static member CreateShutdownEvent () = new EventWaitHandle(false, EventResetMode.ManualReset, ClientLauncher.ShutdownEventName) static member private CheckShutdownEvent () = let e = EventWaitHandle.OpenExisting(ClientLauncher.ShutdownEventName) e.WaitOne(0) static member CreateShutdownCompletionSemaphore numClients = new Semaphore(0, numClients, ClientLauncher.ShutdownCompletionSemaphoreName) static member private NotifyClientShutdownCompletion () = let sem = Semaphore.OpenExisting(ClientLauncher.ShutdownCompletionSemaphoreName) sem.Release() |> ignore static member Main orgargs = let args = Array.copy orgargs let firstParse = ArgumentParser(args, false) let logdir = // Keep "-dirlog" to not break existing scripts let d1 = firstParse.ParseString( "-dirlog", String.Empty ) let d2 = firstParse.ParseString( "-logdir", String.Empty ) if d1 = String.Empty && d2 = String.Empty then DeploymentSettings.LogFolder else if d2 <> String.Empty then d2 else d1 DeploymentSettings.LogFolder <- logdir let logdirInfo = FileTools.DirectoryInfoCreateIfNotExists( logdir ) let logFileName = Path.Combine( logdir, VersionToString( (PerfDateTime.UtcNow()) ) + ".log" ) let args2 = Array.concat (seq { yield (Array.copy args); yield [|"-log"; logFileName|] }) let parse = ArgumentParser(args2) let keyfile = parse.ParseString( "-keyfile", "" ) let keyfilepwd = parse.ParseString( "-keypwd", "" ) let pwd = parse.ParseString( "-pwd", "" ) let bAllowRelay = parse.ParseBoolean( "-allowrelay", DeploymentSettings.bDaemonRelayForJobAllowed ) let bAllowAD = parse.ParseBoolean( "-allowad", false ) let bLocal = parse.ParseBoolean( "-local", false ) let nTotalJob = parse.ParseInt( "-totaljob", -1 ) let bUseAllDrive = parse.ParseBoolean( "-usealldrives", false ) if bUseAllDrive then DeploymentSettings.UseAllDrivesForData() try use ramCounter = new System.Diagnostics.PerformanceCounter("Memory", "Available MBytes") // Find usable RAM space, leave 512MB, and use all. let usableRAM =( (int64 (ramCounter.NextValue())) - 512L ) <<< 20 if usableRAM > 0L then let maxWorkingSet = if IntPtr.Size = 4 then nativeint (Math.Min( usableRAM, 1300L<<<20 )) else nativeint usableRAM if maxWorkingSet > System.Diagnostics.Process.GetCurrentProcess().MinWorkingSet then System.Diagnostics.Process.GetCurrentProcess().MaxWorkingSet <- maxWorkingSet with | e -> // Exception here should not cause the program to fail, it's safe to continue Logger.LogF( LogLevel.Info, ( fun _ -> sprintf "ClientLauncher.Main: exception on reading perf counter and set MaxWorkingSet: %A" e)) if nTotalJob > 0 then DeploymentSettings.TotalJobLimit <- nTotalJob DeploymentSettings.ExeJobLimit <- nTotalJob DeploymentSettings.AppDomainJobLimit <- nTotalJob Logger.Log( LogLevel.Info, ( sprintf "Set # of Jobs allowed to execute in parallel to %d ..........." (DeploymentSettings.TotalJobLimit) )) let memLimit = parse.ParseInt64( "-mem", (DeploymentSettings.MaxMemoryLimitInMB) ) if memLimit <> (DeploymentSettings.MaxMemoryLimitInMB) then DeploymentSettings.MaxMemoryLimitInMB <- memLimit Logger.Log( LogLevel.Info, ( sprintf "Set Memory Limit to %d MB..........." (DeploymentSettings.MaxMemoryLimitInMB) )) let ip = parse.ParseString("-ip", "") let port = parse.ParseInt( "-port", (DeploymentSettings.ClientPort) ) DeploymentSettings.ClientIP <- ip DeploymentSettings.ClientPort <- port RemoteExecutionEnvironment.ContainerName <- "Daemon@" + port.ToString() Prajna.Core.Cluster.Connects.IpAddr <- ip let jobDirectory = Path.Combine(DeploymentSettings.LocalFolder, DeploymentSettings.JobFolder + DeploymentSettings.ClientPort.ToString() ) JobDependency.CleanJobDir(jobDirectory) let jobip = parse.ParseString("-jobip", "") DeploymentSettings.JobIP <- jobip let jobport = // Keep "-jobport" to not break existing scripts let j = parse.ParseString( "-jobports", String.Empty ) if j <> String.Empty then j else parse.ParseString( "-jobport", String.Empty ) if Utils.IsNotNull jobport && jobport.Length > 0 then let jobport2 = jobport.Split(("-,".ToCharArray()), StringSplitOptions.RemoveEmptyEntries ) if jobport2.Length >= 2 then DeploymentSettings.JobPortMin <- Int32.Parse( jobport2.[0] ) DeploymentSettings.JobPortMax <- Int32.Parse( jobport2.[1] ) else if jobport2.Length >= 1 then let numPorts = DeploymentSettings.JobPortMax - DeploymentSettings.JobPortMin DeploymentSettings.JobPortMin <- Int32.Parse( jobport2.[0] ) DeploymentSettings.JobPortMax <- DeploymentSettings.JobPortMin + numPorts () Logger.Log( LogLevel.Info, ( sprintf "Start PrajnaClient at port %d (%d-%d)...................... Mode %s, %d MB" DeploymentSettings.ClientPort DeploymentSettings.JobPortMin DeploymentSettings.JobPortMax DeploymentSettings.PlatformFlag (DeploymentSettings.MaximumWorkingSet>>>20))) Process.ReportSystemThreadPoolStat() let argsToLog = Array.copy orgargs for i in 0..argsToLog.Length-1 do if String.Compare(argsToLog.[i], "-pwd", StringComparison.InvariantCultureIgnoreCase) = 0 || String.Compare(argsToLog.[i], "-keypwd", StringComparison.InvariantCultureIgnoreCase) = 0 then argsToLog.[i + 1] <- "****" Logger.Log( LogLevel.Info, ( sprintf "Start Parameters %A" argsToLog )) if bAllowAD then Logger.Log( LogLevel.Info, ( sprintf "Allow start remote container in AppDomain" )) DeploymentSettings.AllowAppDomain <- true if bAllowRelay then Logger.Log( LogLevel.Info, ( sprintf "Allow daemon to realy command for jobs. " )) DeploymentSettings.bDaemonRelayForJobAllowed <- true // MakeFileAccessible( logfname ) : logfname may not be the name used for log anymore // Delete All log except the latest 5 log let allLogFiles = logdirInfo.GetFiles() let sortedLogFiles = allLogFiles |> Array.sortBy( fun fileinfo -> fileinfo.CreationTimeUtc.Ticks ) for i=0 to sortedLogFiles.Length-DeploymentSettings.LogFileRetained do try sortedLogFiles.[i].Delete() with // It's possible that a machine runs more than one clients, as a result, some log files may be still accessed by another client | :? IOException -> Logger.Log( LogLevel.MediumVerbose, (sprintf "Cannot delete log file %s" sortedLogFiles.[i].FullName )) let PrajnaMasterFile = parse.ParseString( "-master", "" ) let masterInfo = if Utils.IsNotNull PrajnaMasterFile && PrajnaMasterFile.Length>0 then Logger.Log( LogLevel.Info, (sprintf "Master information file ==== %s" PrajnaMasterFile )) ClientMasterConfig.Parse( PrajnaMasterFile ) else ClientMasterConfig.ToParse( parse ) let bAllParsed = parse.AllParsed Usage if not bAllParsed then failwith "Incorrect arguments" Logger.Log( LogLevel.Info, (sprintf "All command parsed ==== %A" bAllParsed ) ) // let dataDrive = StringTools.GetDrive( dir ) let client0 = if masterInfo.ReportingServers.Count > 0 then let client = HomeInClient( masterInfo.VersionInfo, DeploymentSettings.DataDrive, masterInfo.ReportingServers, masterInfo.MasterName, masterInfo.MasterPort ) //Async.StartAsTask(ClientController.ConnectToController(client, masterInfo.ControlPort)) |> ignore for pair in masterInfo.Executables do let exe, param = pair.Key, pair.Value Logger.Log( LogLevel.Info, (sprintf "To execute %s with %s" exe param )) // let homeInTimer = Timer( HomeInClient.HomeInClient, client, 0, 10000) // ListenerThread // let HomeInThreadStart = Threading.ParameterizedThreadStart( HomeInClient.HomeInClient ) // let HomeInThread = Threading.Thread( HomeInThreadStart ) // HomeInThread.IsBackground <- true // HomeInThread.Start( client ) let HomeInThread = ThreadTracking.StartThreadForFunction( fun _ -> "Home in thread") ( fun _ -> HomeInClient.HomeInClient client) client else null /// Create hooker for distributed function routing. Prajna.Service.DistributedFunctionBuiltIn.Init() let listener = Listener.StartListener() let monTimer = ThreadPoolTimer.TimerWait ( fun _ -> sprintf "Task Queue Monitor Timer" ) listener.TaskQueue.MonitorTasks DeploymentSettings.MonitorIntervalTaskQueueInMs DeploymentSettings.MonitorIntervalTaskQueueInMs // set authentication parameters for networking Logger.Log( LogLevel.Info, (sprintf "Authentication parameters: pwd=%s keyfile=%s keyfilepwd=%s" (if String.IsNullOrEmpty(pwd) then "empty" else "specified") keyfile (if String.IsNullOrEmpty(keyfilepwd) then "empty" else "specified") ) ) if not (keyfilepwd.Equals("", StringComparison.Ordinal)) then if (not (pwd.Equals("", StringComparison.Ordinal))) then listener.Connects.InitializeAuthentication(pwd, keyfile, keyfilepwd) else let keyinfo = NetworkConnections.ObtainKeyInfoFromFiles(keyfile) listener.Connects.InitializeAuthentication(keyinfo, keyfilepwd) elif (not (pwd.Equals("", StringComparison.Ordinal))) then listener.Connects.InitializeAuthentication(pwd) // let ListenerThreadStart = Threading.ParameterizedThreadStart( Listener.StartServer ) // let ListenerThread = Threading.Thread( ListenerThreadStart ) // ListenerThread.IsBackground <- true // ListenerThread.Start( listener ) let ListenerThread = ThreadTracking.StartThreadForFunction( fun _ -> sprintf "Main Listener thread for daemon, on port %d" DeploymentSettings.ClientPort ) (fun _ -> Listener.StartServer listener) if bLocal then // for local, the host should have created the semaphore, the client // tries to notify the host that it is ready to serve ClientLauncher.NotifyClientReady() while (not (bLocal && ClientLauncher.CheckShutdownEvent())) do Thread.Sleep(100) if not (Utils.IsNull client0) then client0.Shutdown <- true listener.InListeningState <- false // Shutdown main loop // homeInTimer.Dispose() // ListenerThread.Abort() (* // With startclient.ps1, we do not use auto update at this moment. *) // Should give a chance for attached Remote container to shutdown. (* let tStart = PerfDateTime.UtcNowTicks() let mutable bDoneWaiting = false while not bDoneWaiting do if listener.TaskQueue.IsEmptyExecutionTable() then bDoneWaiting <- true else let tCur = PerfDateTime.UtcNowTicks() let span = (tCur - tStart) / TimeSpan.TicksPerMillisecond if span < 5000L then Threading.Thread.Sleep(50) else bDoneWaiting <- true *) listener.TaskQueue.EvEmptyExecutionTable.WaitOne( 5000 ) |> ignore CleanUp.Current.CleanUpAll() // Code below is included in Cluster.Connects.Close() // ThreadPoolWait.TerminateAll() // ThreadTracking.CloseAllActiveThreads DeploymentSettings.ThreadJoinTimeOut Logger.LogF( LogLevel.MildVerbose, ( fun _ -> sprintf "daemon on port %d ended" DeploymentSettings.ClientPort )) if bLocal then // Notify the host that the shutdown has completed ClientLauncher.NotifyClientShutdownCompletion() /// Give a chance for all the launched task to be closed. Logger.LogF( LogLevel.MildVerbose, ( fun _ -> sprintf "ClientLauncher.Main (for daemon on port %d) returns" DeploymentSettings.ClientPort)) 0 // return an integer exit code // Instance member that wraps over Main member x.Start orgargs = ClientLauncher.Main orgargs // start the client inside an AppDomain static member StartAppDomain name port (orgargs : string[]) = let thread = ThreadTracking.StartThreadForFunction (fun _ -> sprintf "Daemon on port %d" port ) ( fun () -> try Logger.LogF( LogLevel.Info, ( fun _ -> sprintf "Start AppDomain for client with name '%s' and args '%s'" name (String.Join(" ", orgargs)))) let adName = name + "_" + VersionToString(PerfADateTime.UtcNow()) + Guid.NewGuid().ToString("D") let ads = AppDomainSetup() ads.ApplicationBase <- Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) let ad = AppDomain.CreateDomain(adName, new Security.Policy.Evidence(), ads) Logger.LogF( LogLevel.Info, ( fun _ -> sprintf "AppDomain %s created (%i)" adName port)) let fullTypeName = Operators.typeof< ClientLauncher >.FullName let curAsm = Assembly.GetExecutingAssembly() try let proxy = ad.CreateInstanceFromAndUnwrap( curAsm.Location, fullTypeName) let remoteObj = proxy :?> ClientLauncher Logger.LogF( LogLevel.Info, ( fun _ -> sprintf "RemoteObject for %s is created (%i)" fullTypeName port)) remoteObj.Start orgargs |> ignore Logger.LogF( LogLevel.MildVerbose, fun _ -> sprintf "ClientLauncher.Start has returned, current domain is '%s'" AppDomain.CurrentDomain.FriendlyName) finally try if DeploymentSettings.SleepMSBeforeUnloadAppDomain > 0 then Threading.Thread.Sleep( DeploymentSettings.SleepMSBeforeUnloadAppDomain ) // Currently, during unit test clean up phase, the container hosted by appdomain takes very long time to unload for unknow reasons. It causes // the appdomain for deamon (which starts the container appdomain) also cannot unload quickly. // As a temporary workaround before the root cause was figured out, the code below limits the time given to unload the appdomain. // Notes: // 1. When we reach this point, the execution for the daemon has already completed. Unload the now un-used appdomain is the only thing left. // 2. If the unload itself hit any exception, the Wait should rethrow it here and it would be caught by the "with" below. if Async.StartAsTask(async { AppDomain.Unload( ad ) }).Wait(DeploymentSettings.AppDomainUnloadWaitTime) then Logger.LogF( LogLevel.Info, ( fun _ -> sprintf "Successfully unload AppDomain for client with name '%s' and args '%s'" name (String.Join(" ", orgargs)))) else Logger.LogF( LogLevel.MildVerbose, ( fun _ -> sprintf "Time budget (%f ms) for unload AppDomain for client with name '%s' is used up, continue without waiting " DeploymentSettings.AppDomainUnloadWaitTime.TotalMilliseconds name ) ) with | e -> Logger.LogF( LogLevel.MildVerbose, ( fun _ -> sprintf "fail to unload AppDomain for client with name '%s' and args '%s'" name (String.Join(" ", orgargs)))) with | e -> Logger.Log( LogLevel.Error, ( sprintf "ClientLauncher.StartAppDomain exception: %A" e )) Logger.LogF( LogLevel.MediumVerbose, ( fun _ -> sprintf "ClientLauncher.StartAppDomain (for client with name '%s' and args '%s') returns" name (String.Join(" ", orgargs)))) ) ()
{ "pile_set_name": "Github" }
/* * #%L * BroadleafCommerce Common Libraries * %% * Copyright (C) 2009 - 2016 Broadleaf Commerce * %% * Licensed under the Broadleaf Fair Use License Agreement, Version 1.0 * (the "Fair Use License" located at http://license.broadleafcommerce.org/fair_use_license-1.0.txt) * unless the restrictions on use therein are violated and require payment to Broadleaf in which case * the Broadleaf End User License Agreement (EULA), Version 1.1 * (the "Commercial License" located at http://license.broadleafcommerce.org/commercial_license-1.1.txt) * shall apply. * * Alternatively, the Commercial License may be replaced with a mutually agreed upon license (the "Custom License") * between you and Broadleaf Commerce. You may not use this file except in compliance with the applicable license. * #L% */ package org.broadleafcommerce.common.email.service; import org.broadleafcommerce.common.email.dao.EmailReportingDao; import org.broadleafcommerce.common.email.domain.EmailTarget; import org.broadleafcommerce.common.email.service.exception.EmailException; import org.broadleafcommerce.common.email.service.info.EmailInfo; import org.broadleafcommerce.common.email.service.info.NullEmailInfo; import org.broadleafcommerce.common.email.service.info.ServerInfo; import org.broadleafcommerce.common.email.service.message.EmailPropertyType; import org.broadleafcommerce.common.email.service.message.EmailServiceProducer; import org.broadleafcommerce.common.email.service.message.MessageCreator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.Map; import javax.annotation.Resource; /** * @author jfischer */ @Service("blEmailService") public class EmailServiceImpl implements EmailService { @Resource(name = "blEmailTrackingManager") protected EmailTrackingManager emailTrackingManager; @Resource(name = "blServerInfo") protected ServerInfo serverInfo; @Autowired(required = false) protected EmailServiceProducer emailServiceProducer; @Resource(name = "blMessageCreator") protected MessageCreator messageCreator; @Resource(name = "blEmailReportingDao") protected EmailReportingDao emailReportingDao; @Override public boolean sendTemplateEmail(EmailTarget emailTarget, EmailInfo emailInfo, Map<String, Object> props) { if (props == null) { props = new HashMap<String, Object>(); } if (emailInfo == null) { emailInfo = new EmailInfo(); } props.put(EmailPropertyType.INFO.getType(), emailInfo); props.put(EmailPropertyType.USER.getType(), emailTarget); Long emailId = emailTrackingManager.createTrackedEmail(emailTarget.getEmailAddress(), emailInfo.getEmailType(), null); props.put("emailTrackingId", emailId); return sendBasicEmail(emailInfo, emailTarget, props); } @Override public boolean sendTemplateEmail(String emailAddress, EmailInfo emailInfo, Map<String, Object> props) { if (!(emailInfo instanceof NullEmailInfo)) { EmailTarget emailTarget = emailReportingDao.createTarget(); emailTarget.setEmailAddress(emailAddress); return sendTemplateEmail(emailTarget, emailInfo, props); } else { return true; } } @Override public boolean sendBasicEmail(EmailInfo emailInfo, EmailTarget emailTarget, Map<String, Object> props) { if (props == null) { props = new HashMap<String, Object>(); } if (emailInfo == null) { emailInfo = new EmailInfo(); } props.put(EmailPropertyType.INFO.getType(), emailInfo); props.put(EmailPropertyType.USER.getType(), emailTarget); if (Boolean.parseBoolean(emailInfo.getSendEmailReliableAsync())) { if (emailServiceProducer == null) { throw new EmailException("The property sendEmailReliableAsync on EmailInfo is true, but the EmailService does not have an instance of JMSEmailServiceProducer set."); } emailServiceProducer.send(props); } else { messageCreator.sendMessage(props); } return true; } /** * @return the emailTrackingManager */ public EmailTrackingManager getEmailTrackingManager() { return emailTrackingManager; } /** * @param emailTrackingManager the emailTrackingManager to set */ public void setEmailTrackingManager(EmailTrackingManager emailTrackingManager) { this.emailTrackingManager = emailTrackingManager; } /** * @return the serverInfo */ public ServerInfo getServerInfo() { return serverInfo; } /** * @param serverInfo the serverInfo to set */ public void setServerInfo(ServerInfo serverInfo) { this.serverInfo = serverInfo; } /** * @return the emailServiceProducer */ public EmailServiceProducer getEmailServiceProducer() { return emailServiceProducer; } /** * @param emailServiceProducer the emailServiceProducer to set */ public void setEmailServiceProducer(EmailServiceProducer emailServiceProducer) { this.emailServiceProducer = emailServiceProducer; } /** * @return the messageCreator */ public MessageCreator getMessageCreator() { return messageCreator; } /** * @param messageCreator the messageCreator to set */ public void setMessageCreator(MessageCreator messageCreator) { this.messageCreator = messageCreator; } }
{ "pile_set_name": "Github" }
# Copyright 2017 Insurance Australia Group Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import datetime import pytest import boto3 import verification_rules.common.evaluation as evaluation import verification_rules.common.logger as logger import verification_rules.common.credential as credential import verification_rules.common.rule_parameter as rule_parameter from botocore.stub import Stubber ################################################################################# # Classes ################################################################################# class Context(object): @property def aws_request_id(self): return "Req1" @property def memory_limit_in_mb(self): return 1234 @classmethod def get_remaining_time_in_millis(cls): return 1234 @property def invoked_function_arn(self): return "arn1234" @property def function_name(self): return "FunctionName" @property def function_version(self): return 1 class TestEvaluation(object): def test_delete_eval_results_valid(self): config = boto3.client("config") stubber = Stubber(config) stubber.add_response("delete_evaluation_results", {}) stubber.activate() result = evaluation.delete_evaluation_results(config, False, "RuleName") is None stubber.deactivate() assert result def test_delete_eval_results_error(self): config = boto3.client("config") stubber = Stubber(config) stubber.add_client_error("delete_evaluation_results") stubber.activate() result = evaluation.delete_evaluation_results(config, False, "RuleName") is None stubber.deactivate() assert result def test_put_log_evaluation(self): config = boto3.client("config") stubber = Stubber(config) stubber.add_response("put_evaluations", {}) stubber.activate() eval_elemnt = evaluation.EvaluationElement( "resource_id", "resource_type", "compliance_type", "annotation", datetime.datetime.now() ) result = evaluation.put_log_evaluation( config, eval_elemnt, "result_token", True, logger, {"resultToken": "resultToken"}, Context() ) is None stubber.deactivate() assert result class TestLogger(object): def test_log_event(self): eval_elemnt = evaluation.EvaluationElement( "resource_id", "resource_type", "compliance_type", "annotation", "ordering_timestamp" ) result = logger.log_event( {"event": "contents", "resultToken": "ResultToken"}, Context(), eval_elemnt, "Message" ) is None assert result class TestAssumedCredentials(object): @pytest.fixture(scope="function") def _resp_assume_role_valid(self): return { "AssumedRoleUser": { "AssumedRoleId": "AROAI4WM4ITKVYXUVZ7VQ:RoleId", "Arn": "arn:aws:sts::123456789012:assumed-role/TestRole/RoleId" }, "Credentials": { "SecretAccessKey": "secretAccessKey", "SessionToken": "sessionToken", "Expiration": "2017-06-02T03:22:31Z", "AccessKeyId": "accessKeyId12345" } } def test_assumed_creds_arn_blank(self): assert credential.get_assumed_creds(None, "") == {} def test_assumed_creds_arn_missing(self): assert credential.get_assumed_creds(None, None) == {} def test_assumed_creds_arn_valid(self, _resp_assume_role_valid): sts = boto3.client("sts") stubber = Stubber(sts) stubber.add_response("assume_role", _resp_assume_role_valid) stubber.activate() assumed_creds = credential.get_assumed_creds( sts, "arn:aws:iam::123456789012:role/aws-config-role" ) stubber.deactivate() assert assumed_creds.get("aws_access_key_id") == "accessKeyId12345" assert assumed_creds.get("aws_secret_access_key") == "secretAccessKey" assert assumed_creds.get("aws_session_token") == "sessionToken" class TestEvaluationElement(object): def test_instance(self): eval_element = evaluation.EvaluationElement( "resource_id", "resource_type", "compliance_type", "annotation", "ordering_timestamp" ) assert isinstance(eval_element, evaluation.EvaluationElement) def test_eval_element_properties(self): eval_element = evaluation.EvaluationElement( "resource_id", "resource_type", "compliance_type", "annotation", "ordering_timestamp" ) assert eval_element.resource_id == "resource_id" assert eval_element.resource_type == "resource_type" assert eval_element.compliance_type == "compliance_type" assert eval_element.annotation == "annotation" assert eval_element.ordering_timestamp == "ordering_timestamp" class TestRuleParameter(object): def test_instance_param(self): parameter = rule_parameter.RuleParameter({"ruleParameters": '{"testMode": true}'}) assert isinstance(parameter, rule_parameter.RuleParameter) def test_instance_no_param(self): parameter = rule_parameter.RuleParameter({}) assert isinstance(parameter, rule_parameter.RuleParameter) def test_get_param(self): parameter = rule_parameter.RuleParameter({"ruleParameters": '{"testMode": true}'}) assert parameter.get("testMode") def test_get_no_param(self): parameter = rule_parameter.RuleParameter({}) assert parameter.get("testMode") is None def test_get_default_param(self): parameter = rule_parameter.RuleParameter({"ruleParameters": '{"testMode": true}'}) assert parameter.get("missingParam", True) def test_get_default_no_param(self): parameter = rule_parameter.RuleParameter({}) assert parameter.get("missingParam", True)
{ "pile_set_name": "Github" }
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA */ /** * $Id: 7a3ee77599816fd10ffa9f85a07840bf253bacfc $ * * @brief Utillity functions used in the module. * @file mod.c * * @author Aaron Hurt ([email protected]) * @copyright 2013-2014 The FreeRADIUS Server Project. */ RCSID("$Id: 7a3ee77599816fd10ffa9f85a07840bf253bacfc $") #define LOG_PREFIX "rlm_couchbase - " #include <freeradius-devel/json/base.h> #include <freeradius-devel/server/base.h> #include <freeradius-devel/server/map.h> #include "mod.h" #include "couchbase.h" /** Delete a connection pool handle and free related resources * * Destroys the underlying Couchbase connection handle freeing any related * resources and closes the socket connection. * * @param chandle The connection handle to destroy. * @return 0. */ static int _mod_conn_free(rlm_couchbase_handle_t *chandle) { lcb_t cb_inst = chandle->handle; /* couchbase instance */ /* destroy/free couchbase instance */ lcb_destroy(cb_inst); /* return */ return 0; } /** Delete a object built by mod_build_api_opts() * * Release the underlying mod_build_api_opts() objects * * @param instance The module instance. * @return 0. */ int mod_free_api_opts(void *instance) { rlm_couchbase_t *inst = instance; /* our module instance */ couchbase_opts_t *opts = inst->api_opts; if (!opts) return 0; DEBUG("Releasing the couchbase api options"); for (; opts != NULL; opts = opts->next) { if (opts->key) talloc_free(opts->key); if (opts->val) talloc_free(opts->val); } talloc_free(opts); /* return */ return 0; } /** Build a couchbase_opts_t structure from the configuration "couchbase_api" list * * Parse the "couchbase_api" list from the module configuration file and store this * as a couchbase_opts_t object (key/value list). * * @param conf Configuration list. * @param instance The module instance. * @return * - 0 on success. * - -1 on failure. */ int mod_build_api_opts(CONF_SECTION *conf, void *instance) { rlm_couchbase_t *inst = instance; /* our module instance */ CONF_SECTION *cs; /* module config list */ CONF_ITEM *ci; /* config item */ CONF_PAIR *cp; /* config pair */ couchbase_opts_t *entry = NULL; /* couchbase api options */ /* find opts list */ cs = cf_section_find(conf, "opts", NULL); /* check list */ if (!cs) return 0; /* parse libcouchbase_opts list */ cf_log_debug(cs, "opts {"); for (ci = cf_item_next(cs, NULL); ci != NULL; ci = cf_item_next(cs, ci)) { /* * Ignore things we don't care about. */ if (!cf_item_is_pair(ci)) { continue; } /* get value pair from item */ cp = cf_item_to_pair(ci); /* create opts object */ if (!entry) { entry = talloc_zero(inst, couchbase_opts_t); inst->api_opts = entry; } else { entry->next = talloc_zero(inst->api_opts, couchbase_opts_t); entry = entry->next; } entry->next = NULL; entry->key = talloc_typed_strdup(entry, cf_pair_attr(cp)); entry->val = talloc_typed_strdup(entry, cf_pair_value(cp)); /* debugging */ cf_log_debug(cs, "\t%s = \"%s\"", entry->key, entry->val); } cf_log_debug(cs, "}"); /* return */ return 0; } /** Create a new connection pool handle * * Create a new connection to Couchbase within the pool and initialize * information associated with the connection instance. * * @param ctx The connection parent context. * @param instance The module instance. * @param timeout Maximum time to establish the connection. * @return * - New connection handle. * - NULL on error. */ void *mod_conn_create(TALLOC_CTX *ctx, void *instance, fr_time_delta_t timeout) { rlm_couchbase_t const *inst = talloc_get_type_abort_const(instance, rlm_couchbase_t); /* module instance pointer */ rlm_couchbase_handle_t *chandle = NULL; /* connection handle pointer */ cookie_t *cookie = NULL; /* couchbase cookie */ lcb_t cb_inst; /* couchbase connection instance */ lcb_error_t cb_error; /* couchbase error status */ couchbase_opts_t const *opts = inst->api_opts; /* couchbase extra API settings */ /* create instance */ cb_error = couchbase_init_connection(&cb_inst, inst->server, inst->bucket, inst->username, inst->password, fr_time_delta_to_sec(timeout), opts); /* check couchbase instance */ if (cb_error != LCB_SUCCESS) { ERROR("failed to initiate couchbase connection: %s (0x%x)", lcb_strerror(NULL, cb_error), cb_error); /* destroy/free couchbase instance */ lcb_destroy(cb_inst); /* fail */ return NULL; } /* allocate memory for couchbase connection instance abstraction */ chandle = talloc_zero(ctx, rlm_couchbase_handle_t); talloc_set_destructor(chandle, _mod_conn_free); /* allocate cookie off handle */ cookie = talloc_zero(chandle, cookie_t); /* init tokener error and json object */ cookie->jerr = json_tokener_success; cookie->jobj = NULL; /* populate handle */ chandle->cookie = cookie; chandle->handle = cb_inst; /* return handle struct */ return chandle; } /** Check the health of a connection handle * * Attempt to determing the state of the Couchbase connection by requesting * a cluster statistics report. Mark the connection as failed if the request * returns anything other than success. * * @param instance The module instance (currently unused). * @param handle The connection handle. * @return * - 0 on success (alive). * - -1 on failure (unavailable). */ int mod_conn_alive(UNUSED void *instance, void *handle) { rlm_couchbase_handle_t *chandle = handle; /* connection handle pointer */ lcb_t cb_inst = chandle->handle; /* couchbase instance */ lcb_error_t cb_error = LCB_SUCCESS; /* couchbase error status */ /* attempt to get server stats */ if ((cb_error = couchbase_server_stats(cb_inst, NULL)) != LCB_SUCCESS) { /* log error */ ERROR("failed to get couchbase server stats: %s (0x%x)", lcb_strerror(NULL, cb_error), cb_error); /* error out */ return -1; } return 0; } /** Build a JSON object map from the configuration "map" list * * Parse the "map" list from the module configuration file and store this * as a JSON object (key/value list) in the module instance. This map will be * used to lookup and map attributes for all incoming accounting requests. * * @param conf Configuration list. * @param instance The module instance. * @return * - 0 on success. * - -1 on failure. */ int mod_build_attribute_element_map(CONF_SECTION *conf, void *instance) { rlm_couchbase_t *inst = instance; /* our module instance */ CONF_SECTION *cs; /* module config list */ CONF_ITEM *ci; /* config item */ CONF_PAIR *cp; /* conig pair */ const char *attribute, *element; /* attribute and element names */ /* find update list */ cs = cf_section_find(conf, "update", NULL); /* backwards compatibility */ if (!cs) { cs = cf_section_find(conf, "map", NULL); WARN("found deprecated 'map' list - please change to 'update'"); } /* check list */ if (!cs) { ERROR("failed to find 'update' list in config"); /* fail */ return -1; } /* create attribute map object */ inst->map = json_object_new_object(); /* parse update list */ for (ci = cf_item_next(cs, NULL); ci != NULL; ci = cf_item_next(cs, ci)) { /* validate item */ if (!cf_item_is_pair(ci)) { ERROR("failed to parse invalid item in 'update' list"); /* free map */ if (inst->map) { json_object_put(inst->map); } /* fail */ return -1; } /* get value pair from item */ cp = cf_item_to_pair(ci); /* get pair name (attribute name) */ attribute = cf_pair_attr(cp); /* get pair value (element name) */ element = cf_pair_value(cp); /* add pair name and value */ json_object_object_add(inst->map, attribute, json_object_new_string(element)); /* debugging */ DEBUG3("added attribute '%s' to element '%s' mapping", attribute, element); } /* debugging */ DEBUG3("built attribute to element mapping %s", json_object_to_json_string(inst->map)); /* return */ return 0; } /** Map attributes to JSON element names * * Attempt to map the passed attribute name to the configured JSON element * name using the JSON object map mod_build_attribute_element_map(). * * @param name The character name of the requested attribute. * @param map The JSON object map to use for the lookup. * @param buf The buffer where the given element will be stored if found. * @return * - 0 on success. * - -1 on failure. */ int mod_attribute_to_element(const char *name, json_object *map, void *buf) { json_object *j_value; /* json object values */ /* clear buffer */ memset((char *) buf, 0, MAX_KEY_SIZE); /* attempt to map attribute */ if (json_object_object_get_ex(map, name, &j_value)) { /* copy and check size */ if (strlcpy(buf, json_object_get_string(j_value), MAX_KEY_SIZE) >= MAX_KEY_SIZE) { /* oops ... this value is bigger than our buffer ... error out */ ERROR("json map value larger than MAX_KEY_SIZE - %d", MAX_KEY_SIZE); /* return fail */ return -1; } /* looks good */ return 0; } /* debugging */ DEBUG("skipping attribute with no map entry - %s", name); /* default return */ return -1; } /** Build value pairs from the passed JSON object and add to the request * * Parse the passed JSON object and create value pairs that will be injected into * the given request for authorization. * * Example JSON document structure: * @code{.json} * { * "docType": "raduser", * "userName": "test", * "control": { * "SHA-Password": { * "value": "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3", * "op": ":=" * } * }, * "reply": { * "Reply-Message": { * "value": "Hidey Ho!", * "op": "=" * } * } * } * @endcode * * @param[in] ctx to allocate maps in. * @param[in] out Cursor to append maps to. * @param[in] request The request to which the generated pairs should be added. * @param[in] json The JSON object representation of the user document. * @param[in] list The pair list PAIR_LIST_CONTROL or PAIR_LIST_REPLY. * @return * - 1 if no section found. * - 0 on success. * - <0 on error. */ int mod_json_object_to_map(TALLOC_CTX *ctx, fr_cursor_t *out, REQUEST *request, json_object *json, pair_list_t list) { json_object *list_obj; char const *list_name = fr_table_str_by_value(pair_list_table, list, "<INVALID>"); /* * Check for a section matching the specified list */ if (!json_object_object_get_ex(json, list_name, &list_obj)) { RDEBUG2("Couldn't find \"%s\" key in json object - Not adding value pairs for this attribute list", list_name); return 1; } /* * Check the key representing the list is a JSON object */ if (!fr_json_object_is_type(list_obj, json_type_object)) { RERROR("Invalid json type for \"%s\" key - Attribute lists must be json objects", list_name); return -1; } fr_cursor_tail(out); /* Wind to the end */ /* * Loop through the keys in this object. * * Where attr_name is the key, and attr_value_obj is * the object containing the attributes value and * operator. */ json_object_object_foreach(list_obj, attr_name, attr_value_obj) { json_object *value_obj, *op_obj; fr_dict_attr_t const *da; fr_token_t op; if (!fr_json_object_is_type(attr_value_obj, json_type_object)) { REDEBUG("Invalid json type for \"%s\" key - Attributes must be json objects", attr_name); error: fr_cursor_free_list(out); /* Free any maps we added */ return -1; } RDEBUG3("Parsing %s - \"%s\" : { %s }", list_name, attr_name, json_object_to_json_string(attr_value_obj)); /* * Check we have a value key */ if (!json_object_object_get_ex(attr_value_obj, "value", &value_obj)) { REDEBUG("Missing \"value\" key in: %s - \"%s\" : { %s }", list_name, attr_name, json_object_to_json_string(attr_value_obj)); goto error; } /* * Parse the operator and check its valid */ if (json_object_object_get_ex(attr_value_obj, "op", &op_obj)) { char const *op_str; op_str = json_object_get_string(op_obj); if (!op_str) { bad_op: REDEBUG("Invalid \"op\" key in: %s - \"%s\" : { %s }", list_name, attr_name, json_object_to_json_string(attr_value_obj)); goto error; } op = fr_table_value_by_str(fr_tokens_table, op_str, T_INVALID); if (!fr_assignment_op[op] && !fr_equality_op[op]) goto bad_op; } else { op = T_OP_SET; /* The default */ } /* * Lookup the string attr_name in the * request dictionary. */ da = fr_dict_attr_by_name(request->dict, attr_name); if (!da) { RPERROR("Invalid attribute \"%s\"", attr_name); goto error; } /* * Create a map representing the operation */ { fr_value_box_t tmp = { .type = FR_TYPE_INVALID }; vp_map_t *map; if (fr_json_object_to_value_box(ctx, &tmp, value_obj, da, true) < 0) { bad_value: RPERROR("Failed parsing value for \"%s\"", attr_name); goto error; } if (fr_value_box_cast_in_place(ctx, &tmp, da->type, da) < 0) { fr_value_box_clear(&tmp); goto bad_value; } if (map_afrom_value_box(ctx, &map, attr_name, T_BARE_WORD, &(tmpl_rules_t){ .dict_def = request->dict, .list_def = list, }, op, &tmp, true) < 0) { fr_value_box_clear(&tmp); goto bad_value; } fr_cursor_insert(out, map); } } return 0; } /** Convert value pairs to json objects * * Take the passed value pair and convert it to a json-c JSON object. * This code is heavily based on the fr_json_from_pair() function * from src/lib/print.c. * * @param request The request object. * @param vp The value pair to convert. * @return A JSON object. */ json_object *mod_value_pair_to_json_object(REQUEST *request, VALUE_PAIR *vp) { char value[255]; /* radius attribute value */ /* add this attribute/value pair to our json output */ { unsigned int i; switch (vp->vp_type) { case FR_TYPE_UINT32: i = vp->vp_uint32; goto print_int; case FR_TYPE_UINT16: i = vp->vp_uint16; goto print_int; case FR_TYPE_UINT8: i = vp->vp_uint8; print_int: /* skip if we have flags */ if (vp->da->flags.has_value) break; #ifdef HAVE_JSON_OBJECT_NEW_INT64 /* debug */ RDEBUG3("creating new int64 for unsigned 32 bit int/byte/short '%s'", vp->da->name); /* return as 64 bit int - JSON spec does not support unsigned ints */ return json_object_new_int64(i); #else /* debug */ RDEBUG3("creating new int for unsigned 32 bit int/byte/short '%s'", vp->da->name); /* return as 64 bit int - JSON spec does not support unsigned ints */ return json_object_new_int(i); #endif case FR_TYPE_INT32: #ifdef HAVE_JSON_OBJECT_NEW_INT64 /* debug */ RDEBUG3("creating new int64 for signed 32 bit integer '%s'", vp->da->name); /* return as 64 bit int - json-c represents all ints as 64 bits internally */ return json_object_new_int64(vp->vp_int32); #else RDEBUG3("creating new int for signed 32 bit integer '%s'", vp->da->name); /* return as signed int */ return json_object_new_int(vp->vp_int32); #endif case FR_TYPE_UINT64: #ifdef HAVE_JSON_OBJECT_NEW_INT64 /* debug */ RDEBUG3("creating new int64 for 64 bit integer '%s'", vp->da->name); /* return as 64 bit int - because it is a 64 bit int */ return json_object_new_int64(vp->vp_uint64); #else /* warning */ RWARN("skipping 64 bit integer attribute '%s' - please upgrade json-c to 0.10+", vp->da->name); break; #endif default: /* silence warnings - do nothing */ break; } } /* keep going if not set above */ switch (vp->vp_type) { case FR_TYPE_STRING: /* debug */ RDEBUG3("assigning string '%s' as string", vp->da->name); /* return string value */ return json_object_new_string(vp->vp_strvalue); default: /* debug */ RDEBUG3("assigning unhandled '%s' as string", vp->da->name); /* get standard value */ fr_pair_print_value_quoted(&FR_SBUFF_OUT(value, sizeof(value)), vp, T_BARE_WORD); /* return string value from above */ return json_object_new_string(value); } } /** Ensure accounting documents always contain a valid timestamp * * Inspect the given JSON object representation of an accounting document * fetched from Couchbase and ensuse it contains a valid (non NULL) timestamp value. * * @param json JSON object representation of an accounting document. * @param vps The value pairs associated with the current accounting request. * @return * - 0 on success. * - -1 on failure. */ int mod_ensure_start_timestamp(json_object *json, VALUE_PAIR *vps) { json_object *j_value; /* json object value */ struct tm tm; /* struct to hold event time */ time_t ts = 0; /* values to hold time in seconds */ VALUE_PAIR *vp; /* values to hold value pairs */ char value[255]; /* store radius attribute values and our timestamp */ /* get our current start timestamp from our json body */ if (json_object_object_get_ex(json, "startTimestamp", &j_value) == 0) { /* debugging ... this shouldn't ever happen */ DEBUG("failed to find 'startTimestamp' in current json body"); /* return */ return -1; } /* check for null value */ if (json_object_get_string(j_value) != NULL) { /* already set - nothing left to do */ return 0; } /* get current event timestamp */ if ((vp = fr_pair_find_by_da(vps, attr_event_timestamp)) != NULL) { /* get seconds value from attribute */ ts = fr_time_to_sec(vp->vp_date); } else { /* debugging */ DEBUG("failed to find event timestamp in current request"); /* return */ return -1; } /* clear value */ memset(value, 0, sizeof(value)); /* get elapsed session time */ if ((vp = fr_pair_find_by_da(vps, attr_acct_session_time)) != NULL) { /* calculate diff */ ts = (ts - vp->vp_uint32); /* calculate start time */ size_t length = strftime(value, sizeof(value), "%b %e %Y %H:%M:%S %Z", localtime_r(&ts, &tm)); /* check length */ if (length > 0) { /* debugging */ DEBUG("calculated start timestamp: %s", value); /* store new value in json body */ json_object_object_add(json, "startTimestamp", json_object_new_string(value)); } else { /* debugging */ DEBUG("failed to format calculated timestamp"); /* return */ return -1; } } /* default return */ return 0; } /** Handle client value processing for client_map_section() * * @param out Character output * @param cp Configuration pair * @param data The client data * @return * - 0 on success. * - -1 on failure. */ static int _get_client_value(char **out, CONF_PAIR const *cp, void *data) { json_object *j_value; if (!json_object_object_get_ex((json_object *)data, cf_pair_value(cp), &j_value)) { *out = NULL; return 0; } if (!j_value) return -1; *out = talloc_strdup(NULL, json_object_get_string(j_value)); if (!*out) return -1; return 0; } /** Load client entries from Couchbase client documents on startup * * This function executes the view defined in the module configuration and loops * through all returned rows. The view is called with "stale=false" to ensure the * most accurate data available when the view is called. This will force an index * rebuild on this design document in Couchbase. However, since this function is only * run once at server startup this should not be a concern. * * @param inst The module instance. * @param tmpl Default values for new clients. * @param map The client attribute configuration list. * @return * - 0 on success. * - -1 on failure. */ int mod_load_client_documents(rlm_couchbase_t *inst, CONF_SECTION *tmpl, CONF_SECTION *map) { rlm_couchbase_handle_t *handle = NULL; /* connection pool handle */ char vpath[256], vid[MAX_KEY_SIZE], vkey[MAX_KEY_SIZE]; /* view path and fields */ char error[512]; /* view error return */ int idx = 0; /* row array index counter */ int retval = 0; /* return value */ lcb_error_t cb_error = LCB_SUCCESS; /* couchbase error holder */ json_object *json, *j_value; /* json object holders */ json_object *jrows = NULL; /* json object to hold view rows */ CONF_SECTION *client; /* freeradius config list */ RADCLIENT *c; /* freeradius client */ /* get handle */ handle = fr_pool_connection_get(inst->pool, NULL); /* check handle */ if (!handle) return -1; /* set couchbase instance */ lcb_t cb_inst = handle->handle; /* set cookie */ cookie_t *cookie = handle->cookie; /* build view path */ snprintf(vpath, sizeof(vpath), "%s?stale=false", inst->client_view); /* query view for document */ cb_error = couchbase_query_view(cb_inst, cookie, vpath, NULL); /* check error and object */ if (cb_error != LCB_SUCCESS || cookie->jerr != json_tokener_success || !cookie->jobj) { /* log error */ ERROR("failed to execute view request or parse return"); /* set return */ retval = -1; /* return */ goto free_and_return; } /* debugging */ DEBUG3("cookie->jobj == %s", json_object_to_json_string(cookie->jobj)); /* check for error in json object */ if (json_object_object_get_ex(cookie->jobj, "error", &json)) { /* build initial error buffer */ strlcpy(error, json_object_get_string(json), sizeof(error)); /* get error reason */ if (json_object_object_get_ex(cookie->jobj, "reason", &json)) { /* append divider */ strlcat(error, " - ", sizeof(error)); /* append reason */ strlcat(error, json_object_get_string(json), sizeof(error)); } /* log error */ ERROR("view request failed with error: %s", error); /* set return */ retval = -1; /* return */ goto free_and_return; } /* check for document id in return */ if (!json_object_object_get_ex(cookie->jobj, "rows", &json)) { /* log error */ ERROR("failed to fetch rows from view payload"); /* set return */ retval = -1; /* return */ goto free_and_return; } /* get and hold rows */ jrows = json_object_get(json); /* free cookie object */ if (cookie->jobj) { json_object_put(cookie->jobj); cookie->jobj = NULL; } /* debugging */ DEBUG3("jrows == %s", json_object_to_json_string(jrows)); /* check for valid row value */ if (!fr_json_object_is_type(jrows, json_type_array) || json_object_array_length(jrows) < 1) { /* log error */ ERROR("no valid rows returned from view: %s", vpath); /* set return */ retval = -1; /* return */ goto free_and_return; } /* loop across all row elements */ for (idx = 0; (size_t)idx < (size_t)json_object_array_length(jrows); idx++) { /* fetch current index */ json = json_object_array_get_idx(jrows, idx); /* get view id */ if (json_object_object_get_ex(json, "id", &j_value)) { /* clear view id */ memset(vid, 0, sizeof(vid)); /* copy and check length */ if (strlcpy(vid, json_object_get_string(j_value), sizeof(vid)) >= sizeof(vid)) { ERROR("id from row longer than MAX_KEY_SIZE (%d)", MAX_KEY_SIZE); continue; } } else { WARN("failed to fetch id from row - skipping"); continue; } /* get view key */ if (json_object_object_get_ex(json, "key", &j_value)) { /* clear view key */ memset(vkey, 0, sizeof(vkey)); /* copy and check length */ if (strlcpy(vkey, json_object_get_string(j_value), sizeof(vkey)) >= sizeof(vkey)) { ERROR("key from row longer than MAX_KEY_SIZE (%d)", MAX_KEY_SIZE); continue; } } else { WARN("failed to fetch key from row - skipping"); continue; } /* fetch document */ cb_error = couchbase_get_key(cb_inst, cookie, vid); /* check error and object */ if (cb_error != LCB_SUCCESS || cookie->jerr != json_tokener_success || !cookie->jobj) { /* log error */ ERROR("failed to execute get request or parse return"); /* set return */ retval = -1; /* return */ goto free_and_return; } /* debugging */ DEBUG3("cookie->jobj == %s", json_object_to_json_string(cookie->jobj)); /* allocate conf list */ client = tmpl ? cf_section_dup(NULL, NULL, tmpl, "client", vkey, true) : cf_section_alloc(NULL, NULL, "client", vkey); if (client_map_section(client, map, _get_client_value, cookie->jobj) < 0) { /* free config setion */ talloc_free(client); /* set return */ retval = -1; /* return */ goto free_and_return; } /* * @todo These should be parented from something. */ c = client_afrom_cs(NULL, client, false); if (!c) { ERROR("failed to allocate client"); /* free config setion */ talloc_free(client); /* set return */ retval = -1; /* return */ goto free_and_return; } /* * Client parents the CONF_SECTION which defined it. */ talloc_steal(c, client); /* attempt to add client */ if (!client_add(NULL, c)) { ERROR("failed to add client '%s' from '%s', possible duplicate?", vkey, vid); /* free client */ client_free(c); /* set return */ retval = -1; /* return */ goto free_and_return; } /* debugging */ DEBUG("client '%s' added", c->longname); /* free json object */ if (cookie->jobj) { json_object_put(cookie->jobj); cookie->jobj = NULL; } } free_and_return: /* free rows */ if (jrows) { json_object_put(jrows); } /* free json object */ if (cookie->jobj) { json_object_put(cookie->jobj); cookie->jobj = NULL; } /* release handle */ if (handle) fr_pool_connection_release(inst->pool, NULL, handle); /* return */ return retval; }
{ "pile_set_name": "Github" }
/* * Copyright (C) 2006-2018 Christopho, Solarus - http://www.solarus-games.org * * Solarus 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. * * Solarus 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/>. */ #include "solarus/audio/Music.h" #include "solarus/audio/Sound.h" #include "solarus/core/Debug.h" #include "solarus/core/Equipment.h" #include "solarus/core/EquipmentItem.h" #include "solarus/core/Game.h" #include "solarus/core/MainLoop.h" #include "solarus/core/Map.h" #include "solarus/core/ResourceProvider.h" #include "solarus/core/Timer.h" #include "solarus/core/Treasure.h" #include "solarus/entities/Block.h" #include "solarus/entities/Bomb.h" #include "solarus/entities/Chest.h" #include "solarus/entities/Crystal.h" #include "solarus/entities/CrystalBlock.h" #include "solarus/entities/CustomEntity.h" #include "solarus/entities/Destination.h" #include "solarus/entities/Destructible.h" #include "solarus/entities/Door.h" #include "solarus/entities/DynamicTile.h" #include "solarus/entities/Enemy.h" #include "solarus/entities/Entities.h" #include "solarus/entities/EntityTypeInfo.h" #include "solarus/entities/Explosion.h" #include "solarus/entities/Fire.h" #include "solarus/entities/GroundInfo.h" #include "solarus/entities/Hero.h" #include "solarus/entities/Jumper.h" #include "solarus/entities/Npc.h" #include "solarus/entities/Pickable.h" #include "solarus/entities/Sensor.h" #include "solarus/entities/Separator.h" #include "solarus/entities/ShopTreasure.h" #include "solarus/entities/Stairs.h" #include "solarus/entities/Stream.h" #include "solarus/entities/Switch.h" #include "solarus/entities/Teletransporter.h" #include "solarus/entities/Tile.h" #include "solarus/entities/TilePattern.h" #include "solarus/entities/Tileset.h" #include "solarus/entities/Wall.h" #include "solarus/lua/LuaContext.h" #include "solarus/lua/LuaTools.h" #include "solarus/movements/Movement.h" #include <lua.hpp> #include <sstream> namespace Solarus { namespace { /** * \brief Lua equivalent of the deprecated map:move_camera() function. */ const char* move_camera_code = "local map, x, y, speed, callback, delay_before, delay_after = ...\n" "local camera = map:get_camera()\n" "local game = map:get_game()\n" "local hero = map:get_hero()\n" "delay_before = delay_before or 1000\n" "delay_after = delay_after or 1000\n" "local back_x, back_y = camera:get_position_to_track(hero)\n" "game:set_suspended(true)\n" "camera:start_manual()\n" "local movement = sol.movement.create(\"target\")\n" "movement:set_target(camera:get_position_to_track(x, y))\n" "movement:set_ignore_obstacles(true)\n" "movement:set_speed(speed)\n" "movement:start(camera, function()\n" " local timer_1 = sol.timer.start(map, delay_before, function()\n" " callback()\n" " local timer_2 = sol.timer.start(map, delay_after, function()\n" " local movement = sol.movement.create(\"target\")\n" " movement:set_target(back_x, back_y)\n" " movement:set_ignore_obstacles(true)\n" " movement:set_speed(speed)\n" " movement:start(camera, function()\n" " game:set_suspended(false)\n" " camera:start_tracking(hero)\n" " if map.on_camera_back ~= nil then\n" " map:on_camera_back()\n" " end\n" " end)\n" " end)\n" " timer_2:set_suspended_with_map(false)\n" " end)\n" " timer_1:set_suspended_with_map(false)\n" "end)\n"; } // Anonymous namespace. /** * Name of the Lua table representing the map module. */ const std::string LuaContext::map_module_name = "sol.map"; /** * \brief Initializes the map features provided to Lua. */ void LuaContext::register_map_module() { const std::vector<luaL_Reg> methods = { { "get_id", map_api_get_id }, { "get_game", map_api_get_game }, { "get_world", map_api_get_world }, { "set_world", map_api_set_world }, { "get_min_layer", map_api_get_min_layer }, { "get_max_layer", map_api_get_max_layer }, { "get_size", map_api_get_size }, { "get_location", map_api_get_location }, { "get_floor", map_api_get_floor }, { "set_floor", map_api_set_floor }, { "get_tileset", map_api_get_tileset }, { "set_tileset", map_api_set_tileset }, { "get_music", map_api_get_music }, { "get_camera", map_api_get_camera }, { "get_camera_position", map_api_get_camera_position }, { "move_camera", map_api_move_camera }, { "get_ground", map_api_get_ground }, { "draw_visual", map_api_draw_visual }, { "draw_sprite", map_api_draw_sprite }, { "get_crystal_state", map_api_get_crystal_state }, { "set_crystal_state", map_api_set_crystal_state }, { "change_crystal_state", map_api_change_crystal_state }, { "open_doors", map_api_open_doors }, { "close_doors", map_api_close_doors }, { "set_doors_open", map_api_set_doors_open }, { "get_entity", map_api_get_entity }, { "has_entity", map_api_has_entity }, { "get_entities", map_api_get_entities }, { "get_entities_count", map_api_get_entities_count }, { "has_entities", map_api_has_entities }, { "get_entities_by_type", map_api_get_entities_by_type }, { "get_entities_in_rectangle", map_api_get_entities_in_rectangle }, { "get_entities_in_region", map_api_get_entities_in_region }, { "get_hero", map_api_get_hero }, { "set_entities_enabled", map_api_set_entities_enabled }, { "remove_entities", map_api_remove_entities } }; const std::vector<luaL_Reg> metamethods = { { "__gc", userdata_meta_gc }, { "__newindex", userdata_meta_newindex_as_table }, { "__index", userdata_meta_index_as_table } }; register_type(map_module_name, {}, methods, metamethods); // Add map:create_* functions as closures because we pass the entity type as upvalue. luaL_getmetatable(l, map_module_name.c_str()); for (const auto& kvp : EnumInfoTraits<EntityType>::names) { EntityType type = kvp.first; const std::string& type_name = kvp.second; if (!EntityTypeInfo::can_be_created_from_lua_api(type)) { continue; } std::string function_name = "create_" + type_name; push_string(l, type_name); lua_pushcclosure(l, map_api_create_entity, 1); lua_setfield(l, -2, function_name.c_str()); } // Add a Lua implementation of the deprecated map:move_camera() function. int result = luaL_loadstring(l, move_camera_code); if (result != 0) { Debug::error(std::string("Failed to initialize map:move_camera(): ") + lua_tostring(l, -1)); lua_pop(l, 1); } else { Debug::check_assertion(lua_isfunction(l, -1), "map:move_camera() is not a function"); lua_setfield(l, LUA_REGISTRYINDEX, "map.move_camera"); } } /** * \brief Returns whether a value is a userdata of type map. * \param l A Lua context. * \param index An index in the stack. * \return true if the value at this index is a map. */ bool LuaContext::is_map(lua_State* l, int index) { return is_userdata(l, index, map_module_name); } /** * \brief Checks that the userdata at the specified index of the stack is a * map that is currently loaded and returns it. * \param l A Lua context. * \param index An index in the stack. * \return The map. */ std::shared_ptr<Map> LuaContext::check_map(lua_State* l, int index) { return std::static_pointer_cast<Map>(check_userdata( l, index, map_module_name )); } /** * \brief Pushes a map userdata onto the stack. * \param l A Lua context. * \param game A game. */ void LuaContext::push_map(lua_State* l, Map& map) { push_userdata(l, map); } namespace { /** * \brief Checks and returns the layer of an entity to be created. * * The layer is assumed to be specified in a field "layer". * Throws a LuaException if the layer is invalid for the map. * * \param l A Lua state. * \param index Index of the argument in the Lua stack. * \param entity_data Description of the entity to create. * \param map The map where to create the entity. * \return The layer. */ int entity_creation_check_layer( lua_State* l, int index, const EntityData& entity_data, const Map& map) { const int layer = entity_data.get_layer(); if (!map.is_valid_layer(layer)) { std::ostringstream oss; oss << "Invalid layer: " << layer; LuaTools::arg_error(l, index, oss.str()); } return layer; } /** * \brief Checks and returns the size of an entity to be created. * * The size is assumed to be specified in fields "width" and "height". * Throws a LuaException if the size is invalid. * * \param l A Lua state. * \param index Index of the argument in the Lua stack. * \param entity_data Description of the entity to create. * \return The size. */ Size entity_creation_check_size( lua_State* l, int index, const EntityData& entity_data) { const Size size = { entity_data.get_integer("width"), entity_data.get_integer("height") }; if (size.width < 0 || size.width % 8 != 0) { std::ostringstream oss; oss << "Invalid width " << size.width << ": should be a positive multiple of 8"; LuaTools::arg_error(l, index, oss.str()); } if (size.height < 0 || size.height % 8 != 0) { std::ostringstream oss; oss << "Invalid height " << size.height << ": should be a positive multiple of 8"; LuaTools::arg_error(l, index, oss.str()); } return size; } /** * \brief Checks and returns a mandatory savegame variable field for an * entity to be created. * * Throws a LuaException if the savegame variable name is invalid or empty. * * \param l A Lua state. * \param index Index of the argument in the Lua stack. * \param entity_data Description of the entity to create. * \param field_name Name of the savegame variable field to check. * \return The savegame variable name. */ std::string entity_creation_check_savegame_variable_mandatory( lua_State* l, int index, const EntityData& entity_data, const std::string& field_name ) { const std::string& savegame_variable = entity_data.get_string(field_name); if (!LuaTools::is_valid_lua_identifier(savegame_variable)) { LuaTools::arg_error(l, index, "Bad field '" + field_name + "' (invalid savegame variable identifier: '" + savegame_variable + "')" ); } return savegame_variable; } /** * \brief Checks and returns an optional savegame variable field for an * entity to be created. * * Throws a LuaException if the savegame variable name is invalid. * * \param l A Lua state. * \param index Index of the argument in the Lua stack. * \param entity_data Description of the entity to create. * \param field_name Name of the savegame variable field to check. * \return The savegame variable name. * An empty string means no savegame variable. */ std::string entity_creation_check_savegame_variable_optional( lua_State* l, int index, const EntityData& entity_data, const std::string& field_name ) { const std::string& savegame_variable = entity_data.get_string(field_name); if (savegame_variable.empty()) { return savegame_variable; } return entity_creation_check_savegame_variable_mandatory(l, index, entity_data, field_name); } /** * \brief Checks an enum field for an entity to be created. * * Throws a LuaException if the value is not a string or if the string is not * a valid name for the enum. * This is a useful function for mapping strings to C or C++ enums. * * \param l A Lua state. * \param index Index of the argument in the Lua stack. * \param entity_data Description of the entity to * \param field_name Name of the field to check. * \param names A mapping of enum values to strings to search in. * \return The enumerated value corresponding to this string. */ template<typename E> E entity_creation_check_enum( lua_State* l, int index, const EntityData& entity_data, const std::string& field_name, const std::map<E, std::string>& names ) { const std::string& name = entity_data.get_string(field_name); for (const auto& kvp: names) { if (kvp.second == name) { return kvp.first; } } // The value was not found. Build an error message with possible values. std::string allowed_names; for (const auto& kvp: names) { allowed_names += "\"" + kvp.second + "\", "; } allowed_names = allowed_names.substr(0, allowed_names.size() - 2); LuaTools::arg_error(l, index, std::string("Invalid name '") + name + "'. Allowed names are: " + allowed_names ); return E(); // Make sure the compiler is happy. } template<typename E> E entity_creation_check_enum( lua_State* l, int index, const EntityData& entity_data, const std::string& field_name ) { return entity_creation_check_enum<E>(l, index, entity_data, field_name, EnumInfoTraits<E>::names); } } /** * \brief Creates a tile on the map. * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::l_create_tile(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); EntityData& data = *(static_cast<EntityData*>(lua_touserdata(l, 2))); const int layer = entity_creation_check_layer(l, 1, data, map); const int x = data.get_xy().x; const int y = data.get_xy().y; const Size size = entity_creation_check_size(l, 1, data); const std::string& tile_pattern_id = data.get_string("pattern"); std::string tileset_id = data.get_string("tileset"); if (tileset_id.empty()) { tileset_id = map.get_tileset_id(); } ResourceProvider& resource_provider = map.get_game().get_resource_provider(); const Tileset& tileset = resource_provider.get_tileset(tileset_id); const TilePattern& pattern = tileset.get_tile_pattern(tile_pattern_id); const Size& pattern_size = pattern.get_size(); Entities& entities = map.get_entities(); // If the tile is big, divide it in several smaller tiles so that // most of them can still be optimized away. // Otherwise, tiles expanded in big rectangles like a lake or a dungeon // floor would be entirely redrawn at each frame when just one small // animated tile overlaps them. TileInfo tile_info; tile_info.layer = layer; tile_info.box = { Point(), pattern_size }; tile_info.pattern_id = tile_pattern_id; tile_info.pattern = &pattern; tile_info.tileset = &tileset; for (int current_y = y; current_y < y + size.height; current_y += pattern.get_height()) { for (int current_x = x; current_x < x + size.width; current_x += pattern.get_width()) { tile_info.box.set_xy(current_x, current_y); // The tile will actually be created only if it cannot be optimized away. entities.add_tile_info( tile_info ); } } return 0; }); } /** * \brief Creates a destination on the map. * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::l_create_destination(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); EntityData& data = *(static_cast<EntityData*>(lua_touserdata(l, 2))); std::shared_ptr<Destination> entity = std::make_shared<Destination>( data.get_name(), entity_creation_check_layer(l, 1, data, map), data.get_xy(), data.get_integer("direction"), data.get_string("sprite"), data.get_boolean("default") ); StartingLocationMode starting_location_mode = entity_creation_check_enum<StartingLocationMode>(l, 1, data, "starting_location_mode"); entity->set_starting_location_mode(starting_location_mode); entity->set_user_properties(data.get_user_properties()); map.get_entities().add_entity(entity); if (map.is_started()) { push_entity(l, *entity); return 1; } return 0; }); } /** * \brief Creates a teletransporter on the map. * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::l_create_teletransporter(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); EntityData& data = *(static_cast<EntityData*>(lua_touserdata(l, 2))); EntityPtr entity = std::make_shared<Teletransporter>( data.get_name(), entity_creation_check_layer(l, 1, data, map), data.get_xy(), entity_creation_check_size(l, 1, data), data.get_string("sprite"), data.get_string("sound"), entity_creation_check_enum<Transition::Style>(l, 1, data, "transition"), data.get_string("destination_map"), data.get_string("destination") ); entity->set_user_properties(data.get_user_properties()); map.get_entities().add_entity(entity); if (map.is_started()) { push_entity(l, *entity); return 1; } return 0; }); } /** * \brief Creates a pickable treasure on the map. * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::l_create_pickable(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); EntityData& data = *(static_cast<EntityData*>(lua_touserdata(l, 2))); Game& game = map.get_game(); bool force_persistent = false; FallingHeight falling_height = FALLING_MEDIUM; if (!map.is_loaded()) { // Different behavior when the pickable is already placed on the map. falling_height = FALLING_NONE; force_persistent = true; } const std::shared_ptr<Pickable>& entity = Pickable::create( game, data.get_name(), entity_creation_check_layer(l, 1, data, map), data.get_xy(), Treasure( game, data.get_string("treasure_name"), data.get_integer("treasure_variant"), entity_creation_check_savegame_variable_optional(l, 1, data, "treasure_savegame_variable") ), falling_height, force_persistent ); if (entity == nullptr) { lua_pushnil(l); return 1; } entity->set_user_properties(data.get_user_properties()); map.get_entities().add_entity(entity); if (map.is_started()) { push_entity(l, *entity); return 1; } return 0; }); } /** * \brief Creates a destructible object on the map. * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::l_create_destructible(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); EntityData& data = *(static_cast<EntityData*>(lua_touserdata(l, 2))); std::shared_ptr<Destructible> destructible = std::make_shared<Destructible>( data.get_name(), entity_creation_check_layer(l, 1, data, map), data.get_xy(), data.get_string("sprite"), Treasure( map.get_game(), data.get_string("treasure_name"), data.get_integer("treasure_variant"), entity_creation_check_savegame_variable_optional(l, 1, data, "treasure_savegame_variable") ), entity_creation_check_enum<Ground>(l, 1, data, "ground") ); destructible->set_destruction_sound(data.get_string("destruction_sound")); destructible->set_weight(data.get_integer("weight")); destructible->set_can_be_cut(data.get_boolean("can_be_cut")); destructible->set_can_explode(data.get_boolean("can_explode")); destructible->set_can_regenerate(data.get_boolean("can_regenerate")); destructible->set_damage_on_enemies(data.get_integer("damage_on_enemies")); destructible->set_user_properties(data.get_user_properties()); map.get_entities().add_entity(destructible); if (map.is_started()) { push_entity(l, *destructible); return 1; } return 0; }); } /** * \brief Creates a chest on the map. * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::l_create_chest(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); EntityData& data = *(static_cast<EntityData*>(lua_touserdata(l, 2))); Chest::OpeningMethod opening_method = entity_creation_check_enum<Chest::OpeningMethod>( l, 1, data, "opening_method", Chest::opening_method_names ); // Check the value of opening_condition depending on the opening method. Game& game = map.get_game(); const std::string& opening_condition = data.get_string("opening_condition"); if (opening_method == Chest::OpeningMethod::BY_INTERACTION_IF_SAVEGAME_VARIABLE) { entity_creation_check_savegame_variable_mandatory(l, 1, data, "opening_condition"); } else if (opening_method == Chest::OpeningMethod::BY_INTERACTION_IF_ITEM) { if (!game.get_equipment().item_exists(opening_condition)) { LuaTools::arg_error(l, 1, "Bad field 'opening_condition' (no such equipment item: '" + opening_condition + "')" ); } EquipmentItem& item = game.get_equipment().get_item(opening_condition); if (!item.is_saved()) { LuaTools::arg_error(l, 1, "Bad field 'opening_condition' (equipment item '" + opening_condition + "' is not saved)" ); } } std::shared_ptr<Chest> chest = std::make_shared<Chest>( data.get_name(), entity_creation_check_layer(l, 1, data, map), data.get_xy(), data.get_string("sprite"), Treasure( game, data.get_string("treasure_name"), data.get_integer("treasure_variant"), entity_creation_check_savegame_variable_optional(l, 1, data, "treasure_savegame_variable") ) ); chest->set_opening_method(opening_method); chest->set_opening_condition(opening_condition); chest->set_opening_condition_consumed(data.get_boolean("opening_condition_consumed")); chest->set_cannot_open_dialog_id(data.get_string("cannot_open_dialog")); chest->set_user_properties(data.get_user_properties()); map.get_entities().add_entity(chest); if (map.is_started()) { push_entity(l, *chest); return 1; } return 0; }); } /** * \brief Creates a jumper on the map. * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::l_create_jumper(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); EntityData& data = *(static_cast<EntityData*>(lua_touserdata(l, 2))); EntityPtr entity = std::make_shared<Jumper>( data.get_name(), entity_creation_check_layer(l, 1, data, map), data.get_xy(), entity_creation_check_size(l, 1, data), data.get_integer("direction"), data.get_integer("jump_length") ); entity->set_user_properties(data.get_user_properties()); map.get_entities().add_entity(entity); if (map.is_started()) { push_entity(l, *entity); return 1; } return 0; }); } /** * \brief Creates an enemy on the map. * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::l_create_enemy(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); EntityData& data = *(static_cast<EntityData*>(lua_touserdata(l, 2))); Game& game = map.get_game(); EntityPtr entity = Enemy::create( game, data.get_string("breed"), entity_creation_check_savegame_variable_optional(l, 1, data, "savegame_variable"), data.get_name(), entity_creation_check_layer(l, 1, data, map), data.get_xy(), data.get_integer("direction"), Treasure( game, data.get_string("treasure_name"), data.get_integer("treasure_variant"), entity_creation_check_savegame_variable_optional(l, 1, data, "treasure_savegame_variable") ) ); if (entity == nullptr) { lua_pushnil(l); return 1; } entity->set_user_properties(data.get_user_properties()); map.get_entities().add_entity(entity); if (map.is_started()) { push_entity(l, *entity); return 1; } return 0; }); } /** * \brief Creates an NPC on the map. * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::l_create_npc(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); EntityData& data = *(static_cast<EntityData*>(lua_touserdata(l, 2))); Game& game = map.get_game(); EntityPtr entity = std::make_shared<Npc>( game, data.get_name(), entity_creation_check_layer(l, 1, data, map), data.get_xy(), Npc::Subtype(data.get_integer("subtype")), data.get_string("sprite"), data.get_integer("direction"), data.get_string("behavior") ); entity->set_user_properties(data.get_user_properties()); map.get_entities().add_entity(entity); if (map.is_started()) { push_entity(l, *entity); return 1; } return 0; }); } /** * \brief Creates a block on the map. * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::l_create_block(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); EntityData& data = *(static_cast<EntityData*>(lua_touserdata(l, 2))); int maximum_moves = data.get_integer("maximum_moves"); if (maximum_moves < 0 || maximum_moves > 2) { std::ostringstream oss; oss << "Invalid maximum_moves: " << maximum_moves; LuaTools::arg_error(l, 1, oss.str()); } std::shared_ptr<Block> entity = std::make_shared<Block>( data.get_name(), entity_creation_check_layer(l, 1, data, map), data.get_xy(), data.get_integer("direction"), data.get_string("sprite"), data.get_boolean("pushable"), data.get_boolean("pullable"), maximum_moves ); entity->set_user_properties(data.get_user_properties()); map.get_entities().add_entity(entity); if (map.is_started()) { push_entity(l, *entity); return 1; } return 0; }); } /** * \brief Creates a dynamic tile on the map. * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::l_create_dynamic_tile(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); EntityData& data = *(static_cast<EntityData*>(lua_touserdata(l, 2))); std::string tileset_id = data.get_string("tileset"); if (tileset_id.empty()) { tileset_id = map.get_tileset_id(); } ResourceProvider& resource_provider = map.get_game().get_resource_provider(); const Tileset& tileset = resource_provider.get_tileset(tileset_id); EntityPtr entity = std::make_shared<DynamicTile>( data.get_name(), entity_creation_check_layer(l, 1, data, map), data.get_xy(), entity_creation_check_size(l, 1, data), tileset, data.get_string("pattern"), data.get_boolean("enabled_at_start") ); entity->set_user_properties(data.get_user_properties()); map.get_entities().add_entity(entity); if (map.is_started()) { push_entity(l, *entity); return 1; } return 0; }); } /** * \brief Creates a switch on the map. * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::l_create_switch(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); EntityData& data = *(static_cast<EntityData*>(lua_touserdata(l, 2))); EntityPtr entity = std::make_shared<Switch>( data.get_name(), entity_creation_check_layer(l, 1, data, map), data.get_xy(), entity_creation_check_enum<Switch::Subtype>(l, 1, data, "subtype", Switch::subtype_names), data.get_string("sprite"), data.get_string("sound"), data.get_boolean("needs_block"), data.get_boolean("inactivate_when_leaving") ); entity->set_user_properties(data.get_user_properties()); map.get_entities().add_entity(entity); if (map.is_started()) { push_entity(l, *entity); return 1; } return 0; }); } /** * \brief Creates a wall on the map. * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::l_create_wall(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); EntityData& data = *(static_cast<EntityData*>(lua_touserdata(l, 2))); EntityPtr entity = std::make_shared<Wall>( data.get_name(), entity_creation_check_layer(l, 1, data, map), data.get_xy(), entity_creation_check_size(l, 1, data), data.get_boolean("stops_hero"), data.get_boolean("stops_enemies"), data.get_boolean("stops_npcs"), data.get_boolean("stops_blocks"), data.get_boolean("stops_projectiles") ); entity->set_user_properties(data.get_user_properties()); map.get_entities().add_entity(entity); if (map.is_started()) { push_entity(l, *entity); return 1; } return 0; }); } /** * \brief Creates a sensor on the map. * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::l_create_sensor(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); EntityData& data = *(static_cast<EntityData*>(lua_touserdata(l, 2))); EntityPtr entity = std::make_shared<Sensor>( data.get_name(), entity_creation_check_layer(l, 1, data, map), data.get_xy(), entity_creation_check_size(l, 1, data) ); entity->set_user_properties(data.get_user_properties()); map.get_entities().add_entity(entity); if (map.is_started()) { push_entity(l, *entity); return 1; } return 0; }); } /** * \brief Creates a crystal on the map. * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::l_create_crystal(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); EntityData& data = *(static_cast<EntityData*>(lua_touserdata(l, 2))); EntityPtr entity = std::make_shared<Crystal>( data.get_name(), entity_creation_check_layer(l, 1, data, map), data.get_xy() ); entity->set_user_properties(data.get_user_properties()); map.get_entities().add_entity(entity); if (map.is_started()) { push_entity(l, *entity); return 1; } return 0; }); } /** * \brief Creates a crystal block on the map. * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::l_create_crystal_block(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); EntityData& data = *(static_cast<EntityData*>(lua_touserdata(l, 2))); Game& game = map.get_game(); EntityPtr entity = std::make_shared<CrystalBlock>( game, data.get_name(), entity_creation_check_layer(l, 1, data, map), data.get_xy(), entity_creation_check_size(l, 1, data), CrystalBlock::Subtype(data.get_integer("subtype")) ); entity->set_user_properties(data.get_user_properties()); map.get_entities().add_entity(entity); if (map.is_started()) { push_entity(l, *entity); return 1; } return 0; }); } /** * \brief Creates a shop treasure on the map. * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::l_create_shop_treasure(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); EntityData& data = *(static_cast<EntityData*>(lua_touserdata(l, 2))); Game& game = map.get_game(); EntityPtr entity = ShopTreasure::create( game, data.get_name(), entity_creation_check_layer(l, 1, data, map), data.get_xy(), Treasure( game, data.get_string("treasure_name"), data.get_integer("treasure_variant"), entity_creation_check_savegame_variable_optional(l, 1, data, "treasure_savegame_variable") ), data.get_integer("price"), data.get_string("font"), data.get_string("dialog") ); if (entity == nullptr) { lua_pushnil(l); return 1; } entity->set_user_properties(data.get_user_properties()); map.get_entities().add_entity(entity); if (map.is_started()) { push_entity(l, *entity); return 1; } return 0; }); } /** * \brief Creates a stream on the map. * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::l_create_stream(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); EntityData& data = *(static_cast<EntityData*>(lua_touserdata(l, 2))); std::shared_ptr<Stream> stream = std::make_shared<Stream>( data.get_name(), entity_creation_check_layer(l, 1, data, map), data.get_xy(), data.get_integer("direction"), data.get_string("sprite") ); stream->set_speed(data.get_integer("speed")); stream->set_allow_movement(data.get_boolean("allow_movement")); stream->set_allow_attack(data.get_boolean("allow_attack")); stream->set_allow_item(data.get_boolean("allow_item")); stream->set_user_properties(data.get_user_properties()); map.get_entities().add_entity(stream); if (map.is_started()) { push_stream(l, *stream); return 1; } return 0; }); } /** * \brief Creates a door on the map. * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::l_create_door(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); EntityData& data = *(static_cast<EntityData*>(lua_touserdata(l, 2))); Door::OpeningMethod opening_method = entity_creation_check_enum<Door::OpeningMethod>( l, 1, data, "opening_method", Door::opening_method_names ); // Check the value of opening_condition depending on the opening method. Game& game = map.get_game(); const std::string& opening_condition = data.get_string("opening_condition"); if (opening_method == Door::OpeningMethod::BY_INTERACTION_IF_SAVEGAME_VARIABLE) { entity_creation_check_savegame_variable_mandatory(l, 1, data, "opening_condition"); } else if (opening_method == Door::OpeningMethod::BY_INTERACTION_IF_ITEM) { if (!game.get_equipment().item_exists(opening_condition)) { LuaTools::arg_error(l, 1, "Bad field 'opening_condition' (no such equipment item: '" + opening_condition + "')" ); } EquipmentItem& item = game.get_equipment().get_item(opening_condition); if (!item.is_saved()) { LuaTools::arg_error(l, 1, "Bad field 'opening_condition' (equipment item '" + opening_condition + "' is not saved)" ); } } std::shared_ptr<Door> door = std::make_shared<Door>( game, data.get_name(), entity_creation_check_layer(l, 1, data, map), data.get_xy(), data.get_integer("direction"), data.get_string("sprite"), entity_creation_check_savegame_variable_optional(l, 1, data, "savegame_variable") ); door->set_opening_method(opening_method); door->set_opening_condition(opening_condition); door->set_opening_condition_consumed(data.get_boolean("opening_condition_consumed")); door->set_cannot_open_dialog_id(data.get_string("cannot_open_dialog")); door->set_user_properties(data.get_user_properties()); map.get_entities().add_entity(door); if (map.is_started()) { push_entity(l, *door); return 1; } return 0; }); } /** * \brief Creates stairs on the map. * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::l_create_stairs(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); EntityData& data = *(static_cast<EntityData*>(lua_touserdata(l, 2))); EntityPtr entity = std::make_shared<Stairs>( data.get_name(), entity_creation_check_layer(l, 1, data, map), data.get_xy(), data.get_integer("direction"), Stairs::Subtype(data.get_integer("subtype")) ); entity->set_user_properties(data.get_user_properties()); map.get_entities().add_entity(entity); if (map.is_started()) { push_entity(l, *entity); return 1; } return 0; }); } /** * \brief Creates a separator on the map. * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::l_create_separator(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); EntityData& data = *(static_cast<EntityData*>(lua_touserdata(l, 2))); EntityPtr entity = std::make_shared<Separator>( data.get_name(), entity_creation_check_layer(l, 1, data, map), data.get_xy(), entity_creation_check_size(l, 1, data) ); entity->set_user_properties(data.get_user_properties()); map.get_entities().add_entity(entity); if (map.is_started()) { push_entity(l, *entity); return 1; } return 0; }); } /** * \brief Creates a custom entity on the map. * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::l_create_custom_entity(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); EntityData& data = *(static_cast<EntityData*>(lua_touserdata(l, 2))); Game& game = map.get_game(); EntityPtr entity = std::make_shared<CustomEntity>( game, data.get_name(), data.get_integer("direction"), entity_creation_check_layer(l, 1, data, map), data.get_xy(), entity_creation_check_size(l, 1, data), data.get_string("sprite"), data.get_string("model") ); entity->set_user_properties(data.get_user_properties()); map.get_entities().add_entity(entity); if (map.is_started()) { push_entity(l, *entity); return 1; } return 0; }); } /** * \brief Creates a bomb on the map. * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::l_create_bomb(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); EntityData& data = *(static_cast<EntityData*>(lua_touserdata(l, 2))); EntityPtr entity = std::make_shared<Bomb>( data.get_name(), entity_creation_check_layer(l, 1, data, map), data.get_xy() ); entity->set_user_properties(data.get_user_properties()); map.get_entities().add_entity(entity); if (map.is_started()) { push_entity(l, *entity); return 1; } return 0; }); } /** * \brief Creates an explosion on the map. * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::l_create_explosion(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); EntityData& data = *(static_cast<EntityData*>(lua_touserdata(l, 2))); const bool with_damage = true; EntityPtr entity = std::make_shared<Explosion>( data.get_name(), entity_creation_check_layer(l, 1, data, map), data.get_xy(), with_damage ); entity->set_user_properties(data.get_user_properties()); map.get_entities().add_entity(entity); if (map.is_started()) { push_entity(l, *entity); return 1; } return 0; }); } /** * \brief Creates a fire entity on the map. * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::l_create_fire(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); EntityData& data = *(static_cast<EntityData*>(lua_touserdata(l, 2))); EntityPtr entity = std::make_shared<Fire>( data.get_name(), entity_creation_check_layer(l, 1, data, map), data.get_xy() ); entity->set_user_properties(data.get_user_properties()); map.get_entities().add_entity(entity); if (map.is_started()) { push_entity(l, *entity); return 1; } return 0; }); } const std::map<EntityType, lua_CFunction> LuaContext::entity_creation_functions = { { EntityType::TILE, LuaContext::l_create_tile }, { EntityType::DESTINATION, LuaContext::l_create_destination }, { EntityType::TELETRANSPORTER, LuaContext::l_create_teletransporter }, { EntityType::PICKABLE, LuaContext::l_create_pickable }, { EntityType::DESTRUCTIBLE, LuaContext::l_create_destructible }, { EntityType::CHEST, LuaContext::l_create_chest }, { EntityType::JUMPER, LuaContext::l_create_jumper }, { EntityType::ENEMY, LuaContext::l_create_enemy }, { EntityType::NPC, LuaContext::l_create_npc }, { EntityType::BLOCK, LuaContext::l_create_block }, { EntityType::DYNAMIC_TILE, LuaContext::l_create_dynamic_tile }, { EntityType::SWITCH, LuaContext::l_create_switch }, { EntityType::WALL, LuaContext::l_create_wall }, { EntityType::SENSOR, LuaContext::l_create_sensor }, { EntityType::CRYSTAL, LuaContext::l_create_crystal }, { EntityType::CRYSTAL_BLOCK, LuaContext::l_create_crystal_block }, { EntityType::SHOP_TREASURE, LuaContext::l_create_shop_treasure }, { EntityType::STREAM, LuaContext::l_create_stream }, { EntityType::DOOR, LuaContext::l_create_door }, { EntityType::STAIRS, LuaContext::l_create_stairs }, { EntityType::SEPARATOR, LuaContext::l_create_separator }, { EntityType::CUSTOM, LuaContext::l_create_custom_entity }, { EntityType::EXPLOSION, LuaContext::l_create_explosion }, { EntityType::BOMB, LuaContext::l_create_bomb }, { EntityType::FIRE, LuaContext::l_create_fire }, }; /** * \brief Creates on the current map an entity from the specified data. * * Pushes onto the Lua stack the created entity. * In case of error, pushes nothing and returns \c false. * * \param map The map where to create an entity. * \param entity_data Description of the entity to create. * \return \c true if the entity was successfully created. */ bool LuaContext::create_map_entity_from_data(Map& map, const EntityData& entity_data) { const std::string& type_name = enum_to_name(entity_data.get_type()); std::string function_name = "create_" + type_name; const auto& it = entity_creation_functions.find(entity_data.get_type()); Debug::check_assertion(it != entity_creation_functions.end(), "Missing entity creation function for type '" + type_name + "'" ); lua_CFunction function = it->second; lua_pushcfunction(l, function); push_map(l, map); lua_pushlightuserdata(l, const_cast<EntityData*>(&entity_data)); return call_function(2, 1, function_name.c_str()); } /** * \brief __index function of the environment of the map's code. * * This special __index function allows the map's Lua code to get a map * entity like a global value. * If an entity exists with the specified name, this entity is returned. * Otherwise, we fall back to the usual behavior of global values: * a global value with this name (or \c nil) is returned. * * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::l_get_map_entity_or_global(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { lua_pushvalue(l, lua_upvalueindex(1)); // Because check_map does not like pseudo-indexes. Map& map = *check_map(l, -1); const std::string& name = LuaTools::check_string(l, 2); EntityPtr entity = nullptr; if (map.is_started()) { entity = map.get_entities().find_entity(name); } if (entity != nullptr && !entity->is_being_removed()) { push_entity(l, *entity); } else { lua_getglobal(l, name.c_str()); } return 1; }); } /** * \brief Closure of an iterator over a list of entities. * * This closure expects 3 upvalues in this order: * - The array of entities. * - The size of the array (for performance). * - The current index in the array. * * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::l_entity_iterator_next(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { // Get upvalues. const int table_index = lua_upvalueindex(1); const int size = lua_tointeger(l, lua_upvalueindex(2)); int index = lua_tointeger(l, lua_upvalueindex(3)); if (index > size) { // Finished. return 0; } // Get the next value. lua_rawgeti(l, table_index, index); // Increment index. ++index; lua_pushinteger(l, index); lua_replace(l, lua_upvalueindex(3)); return 1; }); } /** * \brief Generates a Lua error if a map is not in an existing game. * \param l A Lua context. * \param map The map to check. */ void LuaContext::check_map_has_game(lua_State* l, const Map& map) { if (!map.is_game_running()) { // Return nil if the game is already destroyed. LuaTools::error(l, "The game of this map is no longer running"); } } /** * \brief Implementation of map:get_game(). * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::map_api_get_game(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); push_game(l, *map.get_savegame()); return 1; }); } /** * \brief Implementation of map:get_id(). * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::map_api_get_id(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { const Map& map = *check_map(l, 1); push_string(l, map.get_id()); return 1; }); } /** * \brief Implementation of map:get_world(). * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::map_api_get_world(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { const Map& map = *check_map(l, 1); const std::string& world = map.get_world(); if (world.empty()) { lua_pushnil(l); } else { push_string(l, world); } return 1; }); } /** * \brief Implementation of map:set_world(). * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::map_api_set_world(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); std::string world; if (lua_type(l, 2) != LUA_TSTRING && lua_type(l, 2) != LUA_TNIL) { LuaTools::type_error(l, 2, "string or nil"); } if (!lua_isnil(l, 2)) { world = LuaTools::check_string(l, 2); } map.set_world(world); return 0; }); } /** * \brief Implementation of map:get_min_layer(). * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::map_api_get_min_layer(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { const Map& map = *check_map(l, 1); lua_pushinteger(l, map.get_min_layer()); return 1; }); } /** * \brief Implementation of map:get_max_layer(). * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::map_api_get_max_layer(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { const Map& map = *check_map(l, 1); lua_pushinteger(l, map.get_max_layer()); return 1; }); } /** * \brief Implementation of map:get_floor(). * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::map_api_get_floor(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { const Map& map = *check_map(l, 1); if (!map.has_floor()) { lua_pushnil(l); } else { lua_pushinteger(l, map.get_floor()); } return 1; }); } /** * \brief Implementation of map:set_floor(). * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::map_api_set_floor(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); int floor = MapData::NO_FLOOR; if (lua_type(l, 2) != LUA_TNUMBER && lua_type(l, 2) != LUA_TNIL) { LuaTools::type_error(l, 2, "number or nil"); } if (!lua_isnil(l, 2)) { floor = LuaTools::check_int(l, 2); } map.set_floor(floor); return 0; }); } /** * \brief Implementation of map:get_size(). * \param l the Lua context that is calling this function * \return number of values to return to Lua */ int LuaContext::map_api_get_size(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { const Map& map = *check_map(l, 1); lua_pushinteger(l, map.get_width()); lua_pushinteger(l, map.get_height()); return 2; }); } /** * \brief Implementation of map:get_location(). * \param l the Lua context that is calling this function * \return number of values to return to Lua */ int LuaContext::map_api_get_location(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { const Map& map = *check_map(l, 1); lua_pushinteger(l, map.get_location().get_x()); lua_pushinteger(l, map.get_location().get_y()); return 2; }); } /** * \brief Implementation of map:get_tileset(). * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::map_api_get_tileset(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { const Map& map = *check_map(l, 1); push_string(l, map.get_tileset_id()); return 1; }); } /** * \brief Implementation of map:get_music(). * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::map_api_get_music(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { const Map& map = *check_map(l, 1); const std::string& music_id = map.get_music_id(); if (music_id == Music::none) { // Special id to stop any music. lua_pushnil(l); } else if (music_id == Music::unchanged) { // Special id to keep the music unchanged. push_string(l, "same"); } else { push_string(l, music_id); } return 1; }); } /** * \brief Implementation of map:set_tileset(). * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::map_api_set_tileset(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); const std::string& tileset_id = LuaTools::check_string(l, 2); map.set_tileset(tileset_id); return 0; }); } /** * \brief Implementation of map:get_camera(). * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::map_api_get_camera(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); const CameraPtr& camera = map.get_camera(); if (camera == nullptr) { lua_pushnil(l); return 1; } push_camera(l, *camera); return 1; }); } /** * \brief Implementation of map:get_camera_position(). * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::map_api_get_camera_position(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { get_lua_context(l).warning_deprecated( { 1, 5 }, "map:get_camera_position()", "Use map:get_camera():get_bounding_box() instead."); const Map& map = *check_map(l, 1); const CameraPtr& camera = map.get_camera(); if (camera == nullptr) { lua_pushnil(l); return 1; } const Rectangle& camera_position = camera->get_bounding_box(); lua_pushinteger(l, camera_position.get_x()); lua_pushinteger(l, camera_position.get_y()); lua_pushinteger(l, camera_position.get_width()); lua_pushinteger(l, camera_position.get_height()); return 4; }); } /** * \brief Implementation of map:move_camera(). * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::map_api_move_camera(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { LuaContext& lua_context = get_lua_context(l); lua_context.warning_deprecated( { 1, 5 }, "map:move_camera()", "Make a target movement on map:get_camera() instead."); check_map(l, 1); LuaTools::check_int(l, 2); LuaTools::check_int(l, 3); LuaTools::check_int(l, 4); LuaTools::check_type(l, 5, LUA_TFUNCTION); if (lua_gettop(l) >= 6) { LuaTools::check_int(l, 6); } if (lua_gettop(l) >= 7) { LuaTools::check_int(l, 7); } lua_settop(l, 7); // Make sure that we always have 7 arguments. lua_getfield(l, LUA_REGISTRYINDEX, "map.move_camera"); if (!lua_isnil(l, -1)) { Debug::check_assertion(lua_isfunction(l, -1), "map:move_camera() is not a function"); lua_insert(l, 1); lua_context.call_function(7, 0, "move_camera"); } return 0; }); } /** * \brief Implementation of map:get_ground(). * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::map_api_get_ground(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); int x = LuaTools::check_int(l, 2); int y = LuaTools::check_int(l, 3); int layer = LuaTools::check_layer(l, 4, map); Ground ground = map.get_ground(layer, x, y, nullptr); push_string(l, enum_to_name(ground)); return 1; }); } /** * \brief Implementation of map:draw_visual(). * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::map_api_draw_visual(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); Drawable& drawable = *check_drawable(l, 2); int x = LuaTools::check_int(l, 3); int y = LuaTools::check_int(l, 4); map.draw_visual(drawable, x, y); return 0; }); } /** * \brief Implementation of map:draw_sprite(). * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::map_api_draw_sprite(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { get_lua_context(l).warning_deprecated( { 1, 5 }, "map:draw_sprite()", "Use map:draw_visual() instead."); Map& map = *check_map(l, 1); Sprite& sprite = *check_sprite(l, 2); int x = LuaTools::check_int(l, 3); int y = LuaTools::check_int(l, 4); map.draw_visual(sprite, x, y); return 0; }); } /** * \brief Implementation of map:get_crystal_state(). * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::map_api_get_crystal_state(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); lua_pushboolean(l, map.get_game().get_crystal_state()); return 1; }); } /** * \brief Implementation of map:set_crystal_state(). * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::map_api_set_crystal_state(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); bool state = LuaTools::check_boolean(l, 2); Game& game = map.get_game(); if (game.get_crystal_state() != state) { game.change_crystal_state(); } return 0; }); } /** * \brief Implementation of map:change_crystal_state(). * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::map_api_change_crystal_state(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); map.get_game().change_crystal_state(); return 0; }); } /** * \brief Implementation of map:open_doors(). * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::map_api_open_doors(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); const std::string& prefix = LuaTools::check_string(l, 2); bool done = false; Entities& entities = map.get_entities(); const std::vector<EntityPtr>& doors = entities.get_entities_with_prefix(EntityType::DOOR, prefix); for (const EntityPtr& entity: doors) { Door& door = *std::static_pointer_cast<Door>(entity); if (!door.is_open() || door.is_closing()) { door.open(); done = true; } } // make sure the sound is played only once even if the script calls // this function repeatedly while the door is still changing if (done) { Sound::play("door_open"); } return 0; }); } /** * \brief Implementation of map:close_doors(). * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::map_api_close_doors(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); const std::string& prefix = LuaTools::check_string(l, 2); bool done = false; Entities& entities = map.get_entities(); const std::vector<EntityPtr>& doors = entities.get_entities_with_prefix(EntityType::DOOR, prefix); for (const EntityPtr& entity: doors) { Door& door = *std::static_pointer_cast<Door>(entity); if (door.is_open() || door.is_opening()) { door.close(); done = true; } } // make sure the sound is played only once even if the script calls // this function repeatedly while the door is still changing if (done) { Sound::play("door_closed"); } return 0; }); } /** * \brief Implementation of map:set_doors_open(). * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::map_api_set_doors_open(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); const std::string& prefix = LuaTools::check_string(l, 2); bool open = LuaTools::opt_boolean(l, 3, true); Entities& entities = map.get_entities(); const std::vector<EntityPtr>& doors = entities.get_entities_with_prefix(EntityType::DOOR, prefix); for (const EntityPtr& entity: doors) { Door& door = *std::static_pointer_cast<Door>(entity); door.set_open(open); } return 0; }); } /** * \brief Implementation of map:get_entity(). * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::map_api_get_entity(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); const std::string& name = LuaTools::check_string(l, 2); const EntityPtr& entity = map.get_entities().find_entity(name); if (entity != nullptr && !entity->is_being_removed()) { push_entity(l, *entity); } else { lua_pushnil(l); } return 1; }); } /** * \brief Implementation of map:has_entity(). * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::map_api_has_entity(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); const std::string& name = LuaTools::check_string(l, 2); const EntityPtr& entity = map.get_entities().find_entity(name); lua_pushboolean(l, entity != nullptr); return 1; }); } /** * \brief Implementation of map:get_entities(). * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::map_api_get_entities(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); const std::string& prefix = LuaTools::opt_string(l, 2, ""); const EntityVector& entities = map.get_entities().get_entities_with_prefix_sorted(prefix); push_entity_iterator(l, entities); return 1; }); } /** * \brief Implementation of map:get_entities_count(). * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::map_api_get_entities_count(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); const std::string& prefix = LuaTools::check_string(l, 2); const EntityVector& entities = map.get_entities().get_entities_with_prefix(prefix); lua_pushinteger(l, entities.size()); return 1; }); } /** * \brief Implementation of map:has_entities(). * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::map_api_has_entities(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { const Map& map = *check_map(l, 1); const std::string& prefix = LuaTools::check_string(l, 2); lua_pushboolean(l, map.get_entities().has_entity_with_prefix(prefix)); return 1; }); } /** * \brief Implementation of map:get_entities_by_type(). * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::map_api_get_entities_by_type(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); EntityType type = LuaTools::check_enum<EntityType>(l, 2); const EntityVector& entities = map.get_entities().get_entities_by_type_sorted(type); push_entity_iterator(l, entities); return 1; }); } /** * \brief Implementation of map:get_entities_in_rectangle(). * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::map_api_get_entities_in_rectangle(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); const int x = LuaTools::check_int(l, 2); const int y = LuaTools::check_int(l, 3); const int width = LuaTools::check_int(l, 4); const int height = LuaTools::check_int(l, 5); EntityVector entities; map.get_entities().get_entities_in_rectangle_sorted( Rectangle(x, y, width, height), entities ); push_entity_iterator(l, entities); return 1; }); } /** * \brief Implementation of map:get_entities_in_region(). * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::map_api_get_entities_in_region(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); Point xy; EntityPtr entity; if (lua_isnumber(l, 2)) { int x = LuaTools::check_int(l, 2); int y = LuaTools::check_int(l, 3); xy = Point(x, y); } else if (is_entity(l, 2)) { entity = check_entity(l, 2); xy = entity->get_xy(); } else { LuaTools::type_error(l, 2, "entity or number"); } EntityVector entities; map.get_entities().get_entities_in_region_sorted( xy, entities ); if (entity != nullptr) { // Entity variant: remove the entity itself. const auto& it = std::find(entities.begin(), entities.end(), entity); if (it != entities.end()) { entities.erase(it); } } push_entity_iterator(l, entities); return 1; }); } /** * \brief Implementation of map:get_hero(). * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::map_api_get_hero(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); check_map_has_game(l, map); // Return the hero even if he is no longer on this map. push_hero(l, *map.get_game().get_hero()); return 1; }); } /** * \brief Implementation of map:set_entities_enabled(). * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::map_api_set_entities_enabled(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); const std::string& prefix = LuaTools::check_string(l, 2); bool enabled = LuaTools::opt_boolean(l, 3, true); std::vector<EntityPtr> entities = map.get_entities().get_entities_with_prefix(prefix); for (const EntityPtr& entity: entities) { entity->set_enabled(enabled); } return 0; }); } /** * \brief Implementation of map:remove_entities(). * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::map_api_remove_entities(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { Map& map = *check_map(l, 1); const std::string& prefix = LuaTools::check_string(l, 2); map.get_entities().remove_entities_with_prefix(prefix); return 0; }); } /** * \brief Implementation of all entity creation functions: map_api_create_*. * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::map_api_create_entity(lua_State* l) { return LuaTools::exception_boundary_handle(l, [&] { EntityType type = LuaTools::check_enum<EntityType>( l, lua_upvalueindex(1) ); Map& map = *check_map(l, 1); const EntityData& data = EntityData::check_entity_data(l, 2, type); get_lua_context(l).create_map_entity_from_data(map, data); return 1; }); } /** * \brief Calls the on_started() method of a Lua map. * * Does nothing if the method is not defined. * * \param map A map. * \param destination The destination point used (nullptr if it's a special one). */ void LuaContext::map_on_started(Map& map, Destination* destination) { if (!userdata_has_field(map, "on_started")) { return; } push_map(l, map); on_started(destination); lua_pop(l, 1); } /** * \brief Calls the on_finished() method of a Lua map if it is defined. * * Also stops timers and menus associated to the map. * * \param map A map. */ void LuaContext::map_on_finished(Map& map) { push_map(l, map); if (userdata_has_field(map, "on_finished")) { on_finished(); } remove_timers(-1); // Stop timers and menus associated to this map. remove_menus(-1); lua_pop(l, 1); } /** * \brief Calls the on_update() method of a Lua map. * * Also calls the method on its menus. * * \param map A map. */ void LuaContext::map_on_update(Map& map) { push_map(l, map); // This particular method is tried so often that we want to save optimize // the std::string construction. static const std::string method_name = "on_update"; if (userdata_has_field(map, method_name)) { on_update(); } menus_on_update(-1); lua_pop(l, 1); } /** * \brief Calls the on_draw() method of a Lua map if it is defined. * * Also calls the method on its menus. * * \param map A map. * \param dst_surface The destination surface. */ void LuaContext::map_on_draw(Map& map, const SurfacePtr& dst_surface) { push_map(l, map); if (userdata_has_field(map, "on_draw")) { on_draw(dst_surface); } menus_on_draw(-1, dst_surface); lua_pop(l, 1); } /** * \brief Notifies a Lua map that an input event has just occurred. * * The appropriate callback in the map is triggered if it exists. * Also notifies the menus of the game if the game itself does not handle the * event. * * \param event The input event to handle. * \param map A map. * \return \c true if the event was handled and should stop being propagated. */ bool LuaContext::map_on_input(Map& map, const InputEvent& event) { push_map(l, map); bool handled = on_input(event); if (!handled) { handled = menus_on_input(-1, event); } lua_pop(l, 1); return handled; } /** * \brief Calls the on_command_pressed() method of a Lua map. * * Also notifies the menus of the game if the game itself does not handle the * event. * * \param map A map. * \param command The command pressed. * \return \c true if the event was handled and should stop being propagated. */ bool LuaContext::map_on_command_pressed(Map& map, GameCommand command) { bool handled = false; push_map(l, map); if (userdata_has_field(map, "on_command_pressed")) { handled = on_command_pressed(command); } if (!handled) { handled = menus_on_command_pressed(-1, command); } lua_pop(l, 1); return handled; } /** * \brief Calls the on_command_released() method of a Lua map. * * Also notifies the menus of the game if the game itself does not handle the * event. * * \param map A map. * \param command The command released. * \return \c true if the event was handled and should stop being propagated. */ bool LuaContext::map_on_command_released(Map& map, GameCommand command) { bool handled = false; push_map(l, map); if (userdata_has_field(map, "on_command_released")) { handled = on_command_released(command); } if (!handled) { handled = menus_on_command_released(-1, command); } lua_pop(l, 1); return handled; } /** * \brief Calls the on_suspended() method of a Lua map. * * Does nothing if the method is not defined. * * \param map A map. * \param suspended true if the map is suspended. */ void LuaContext::map_on_suspended(Map& map, bool suspended) { if (!userdata_has_field(map, "on_suspended")) { return; } push_map(l, map); on_suspended(suspended); lua_pop(l, 1); } /** * \brief Calls the on_opening_transition_finished() method of a Lua map. * * Does nothing if the method is not defined. * * \param map A map. * \param destination The destination point used (nullptr if it is a special one). */ void LuaContext::map_on_opening_transition_finished(Map& map, Destination* destination) { if (!userdata_has_field(map, "on_opening_transition_finished")) { //return; } push_map(l, map); on_opening_transition_finished(destination); lua_pop(l, 1); } /** * \brief Calls the on_obtaining_treasure() method of a Lua map. * * Does nothing if the method is not defined. * * \param map A map. * \param treasure A treasure the hero is about to obtain on that map. */ void LuaContext::map_on_obtaining_treasure(Map& map, const Treasure& treasure) { if (!userdata_has_field(map, "on_obtaining_treasure")) { return; } push_map(l, map); on_obtaining_treasure(treasure); lua_pop(l, 1); } /** * \brief Calls the on_obtained_treasure() method of a Lua map. * * Does nothing if the method is not defined. * * \param map A map. * \param treasure The treasure just obtained. */ void LuaContext::map_on_obtained_treasure(Map& map, const Treasure& treasure) { if (!userdata_has_field(map, "on_obtained_treasure")) { return; } push_map(l, map); on_obtained_treasure(treasure); lua_pop(l, 1); } }
{ "pile_set_name": "Github" }
<h3><a href="http://reference.wolfram.com/search/?q=DiracGammaMatrix">DiracGammaMatrix</a></h3><p><b>Attributes:</b>Protected, ReadProtected</p><p><b>Symbol has no options.</b></p>
{ "pile_set_name": "Github" }
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Windows system calls. package windows import ( errorspkg "errors" "sync" "syscall" "time" "unicode/utf16" "unsafe" ) type Handle uintptr const ( InvalidHandle = ^Handle(0) // Flags for DefineDosDevice. DDD_EXACT_MATCH_ON_REMOVE = 0x00000004 DDD_NO_BROADCAST_SYSTEM = 0x00000008 DDD_RAW_TARGET_PATH = 0x00000001 DDD_REMOVE_DEFINITION = 0x00000002 // Return values for GetDriveType. DRIVE_UNKNOWN = 0 DRIVE_NO_ROOT_DIR = 1 DRIVE_REMOVABLE = 2 DRIVE_FIXED = 3 DRIVE_REMOTE = 4 DRIVE_CDROM = 5 DRIVE_RAMDISK = 6 // File system flags from GetVolumeInformation and GetVolumeInformationByHandle. FILE_CASE_SENSITIVE_SEARCH = 0x00000001 FILE_CASE_PRESERVED_NAMES = 0x00000002 FILE_FILE_COMPRESSION = 0x00000010 FILE_DAX_VOLUME = 0x20000000 FILE_NAMED_STREAMS = 0x00040000 FILE_PERSISTENT_ACLS = 0x00000008 FILE_READ_ONLY_VOLUME = 0x00080000 FILE_SEQUENTIAL_WRITE_ONCE = 0x00100000 FILE_SUPPORTS_ENCRYPTION = 0x00020000 FILE_SUPPORTS_EXTENDED_ATTRIBUTES = 0x00800000 FILE_SUPPORTS_HARD_LINKS = 0x00400000 FILE_SUPPORTS_OBJECT_IDS = 0x00010000 FILE_SUPPORTS_OPEN_BY_FILE_ID = 0x01000000 FILE_SUPPORTS_REPARSE_POINTS = 0x00000080 FILE_SUPPORTS_SPARSE_FILES = 0x00000040 FILE_SUPPORTS_TRANSACTIONS = 0x00200000 FILE_SUPPORTS_USN_JOURNAL = 0x02000000 FILE_UNICODE_ON_DISK = 0x00000004 FILE_VOLUME_IS_COMPRESSED = 0x00008000 FILE_VOLUME_QUOTAS = 0x00000020 // Flags for LockFileEx. LOCKFILE_FAIL_IMMEDIATELY = 0x00000001 LOCKFILE_EXCLUSIVE_LOCK = 0x00000002 // Return values of SleepEx and other APC functions STATUS_USER_APC = 0x000000C0 WAIT_IO_COMPLETION = STATUS_USER_APC ) // StringToUTF16 is deprecated. Use UTF16FromString instead. // If s contains a NUL byte this function panics instead of // returning an error. func StringToUTF16(s string) []uint16 { a, err := UTF16FromString(s) if err != nil { panic("windows: string with NUL passed to StringToUTF16") } return a } // UTF16FromString returns the UTF-16 encoding of the UTF-8 string // s, with a terminating NUL added. If s contains a NUL byte at any // location, it returns (nil, syscall.EINVAL). func UTF16FromString(s string) ([]uint16, error) { for i := 0; i < len(s); i++ { if s[i] == 0 { return nil, syscall.EINVAL } } return utf16.Encode([]rune(s + "\x00")), nil } // UTF16ToString returns the UTF-8 encoding of the UTF-16 sequence s, // with a terminating NUL removed. func UTF16ToString(s []uint16) string { for i, v := range s { if v == 0 { s = s[0:i] break } } return string(utf16.Decode(s)) } // StringToUTF16Ptr is deprecated. Use UTF16PtrFromString instead. // If s contains a NUL byte this function panics instead of // returning an error. func StringToUTF16Ptr(s string) *uint16 { return &StringToUTF16(s)[0] } // UTF16PtrFromString returns pointer to the UTF-16 encoding of // the UTF-8 string s, with a terminating NUL added. If s // contains a NUL byte at any location, it returns (nil, syscall.EINVAL). func UTF16PtrFromString(s string) (*uint16, error) { a, err := UTF16FromString(s) if err != nil { return nil, err } return &a[0], nil } func Getpagesize() int { return 4096 } // NewCallback converts a Go function to a function pointer conforming to the stdcall calling convention. // This is useful when interoperating with Windows code requiring callbacks. // The argument is expected to be a function with with one uintptr-sized result. The function must not have arguments with size larger than the size of uintptr. func NewCallback(fn interface{}) uintptr { return syscall.NewCallback(fn) } // NewCallbackCDecl converts a Go function to a function pointer conforming to the cdecl calling convention. // This is useful when interoperating with Windows code requiring callbacks. // The argument is expected to be a function with with one uintptr-sized result. The function must not have arguments with size larger than the size of uintptr. func NewCallbackCDecl(fn interface{}) uintptr { return syscall.NewCallbackCDecl(fn) } // windows api calls //sys GetLastError() (lasterr error) //sys LoadLibrary(libname string) (handle Handle, err error) = LoadLibraryW //sys LoadLibraryEx(libname string, zero Handle, flags uintptr) (handle Handle, err error) = LoadLibraryExW //sys FreeLibrary(handle Handle) (err error) //sys GetProcAddress(module Handle, procname string) (proc uintptr, err error) //sys GetModuleFileName(module Handle, filename *uint16, size uint32) (n uint32, err error) = kernel32.GetModuleFileNameW //sys GetModuleHandleEx(flags uint32, moduleName *uint16, module *Handle) (err error) = kernel32.GetModuleHandleExW //sys GetVersion() (ver uint32, err error) //sys FormatMessage(flags uint32, msgsrc uintptr, msgid uint32, langid uint32, buf []uint16, args *byte) (n uint32, err error) = FormatMessageW //sys ExitProcess(exitcode uint32) //sys IsWow64Process(handle Handle, isWow64 *bool) (err error) = IsWow64Process //sys CreateFile(name *uint16, access uint32, mode uint32, sa *SecurityAttributes, createmode uint32, attrs uint32, templatefile Handle) (handle Handle, err error) [failretval==InvalidHandle] = CreateFileW //sys ReadFile(handle Handle, buf []byte, done *uint32, overlapped *Overlapped) (err error) //sys WriteFile(handle Handle, buf []byte, done *uint32, overlapped *Overlapped) (err error) //sys GetOverlappedResult(handle Handle, overlapped *Overlapped, done *uint32, wait bool) (err error) //sys SetFilePointer(handle Handle, lowoffset int32, highoffsetptr *int32, whence uint32) (newlowoffset uint32, err error) [failretval==0xffffffff] //sys CloseHandle(handle Handle) (err error) //sys GetStdHandle(stdhandle uint32) (handle Handle, err error) [failretval==InvalidHandle] //sys SetStdHandle(stdhandle uint32, handle Handle) (err error) //sys findFirstFile1(name *uint16, data *win32finddata1) (handle Handle, err error) [failretval==InvalidHandle] = FindFirstFileW //sys findNextFile1(handle Handle, data *win32finddata1) (err error) = FindNextFileW //sys FindClose(handle Handle) (err error) //sys GetFileInformationByHandle(handle Handle, data *ByHandleFileInformation) (err error) //sys GetFileInformationByHandleEx(handle Handle, class uint32, outBuffer *byte, outBufferLen uint32) (err error) //sys GetCurrentDirectory(buflen uint32, buf *uint16) (n uint32, err error) = GetCurrentDirectoryW //sys SetCurrentDirectory(path *uint16) (err error) = SetCurrentDirectoryW //sys CreateDirectory(path *uint16, sa *SecurityAttributes) (err error) = CreateDirectoryW //sys RemoveDirectory(path *uint16) (err error) = RemoveDirectoryW //sys DeleteFile(path *uint16) (err error) = DeleteFileW //sys MoveFile(from *uint16, to *uint16) (err error) = MoveFileW //sys MoveFileEx(from *uint16, to *uint16, flags uint32) (err error) = MoveFileExW //sys LockFileEx(file Handle, flags uint32, reserved uint32, bytesLow uint32, bytesHigh uint32, overlapped *Overlapped) (err error) //sys UnlockFileEx(file Handle, reserved uint32, bytesLow uint32, bytesHigh uint32, overlapped *Overlapped) (err error) //sys GetComputerName(buf *uint16, n *uint32) (err error) = GetComputerNameW //sys GetComputerNameEx(nametype uint32, buf *uint16, n *uint32) (err error) = GetComputerNameExW //sys SetEndOfFile(handle Handle) (err error) //sys GetSystemTimeAsFileTime(time *Filetime) //sys GetSystemTimePreciseAsFileTime(time *Filetime) //sys GetTimeZoneInformation(tzi *Timezoneinformation) (rc uint32, err error) [failretval==0xffffffff] //sys CreateIoCompletionPort(filehandle Handle, cphandle Handle, key uint32, threadcnt uint32) (handle Handle, err error) //sys GetQueuedCompletionStatus(cphandle Handle, qty *uint32, key *uint32, overlapped **Overlapped, timeout uint32) (err error) //sys PostQueuedCompletionStatus(cphandle Handle, qty uint32, key uint32, overlapped *Overlapped) (err error) //sys CancelIo(s Handle) (err error) //sys CancelIoEx(s Handle, o *Overlapped) (err error) //sys CreateProcess(appName *uint16, commandLine *uint16, procSecurity *SecurityAttributes, threadSecurity *SecurityAttributes, inheritHandles bool, creationFlags uint32, env *uint16, currentDir *uint16, startupInfo *StartupInfo, outProcInfo *ProcessInformation) (err error) = CreateProcessW //sys OpenProcess(desiredAccess uint32, inheritHandle bool, processId uint32) (handle Handle, err error) //sys ShellExecute(hwnd Handle, verb *uint16, file *uint16, args *uint16, cwd *uint16, showCmd int32) (err error) [failretval<=32] = shell32.ShellExecuteW //sys shGetKnownFolderPath(id *KNOWNFOLDERID, flags uint32, token Token, path **uint16) (ret error) = shell32.SHGetKnownFolderPath //sys TerminateProcess(handle Handle, exitcode uint32) (err error) //sys GetExitCodeProcess(handle Handle, exitcode *uint32) (err error) //sys GetStartupInfo(startupInfo *StartupInfo) (err error) = GetStartupInfoW //sys GetProcessTimes(handle Handle, creationTime *Filetime, exitTime *Filetime, kernelTime *Filetime, userTime *Filetime) (err error) //sys DuplicateHandle(hSourceProcessHandle Handle, hSourceHandle Handle, hTargetProcessHandle Handle, lpTargetHandle *Handle, dwDesiredAccess uint32, bInheritHandle bool, dwOptions uint32) (err error) //sys WaitForSingleObject(handle Handle, waitMilliseconds uint32) (event uint32, err error) [failretval==0xffffffff] //sys waitForMultipleObjects(count uint32, handles uintptr, waitAll bool, waitMilliseconds uint32) (event uint32, err error) [failretval==0xffffffff] = WaitForMultipleObjects //sys GetTempPath(buflen uint32, buf *uint16) (n uint32, err error) = GetTempPathW //sys CreatePipe(readhandle *Handle, writehandle *Handle, sa *SecurityAttributes, size uint32) (err error) //sys GetFileType(filehandle Handle) (n uint32, err error) //sys CryptAcquireContext(provhandle *Handle, container *uint16, provider *uint16, provtype uint32, flags uint32) (err error) = advapi32.CryptAcquireContextW //sys CryptReleaseContext(provhandle Handle, flags uint32) (err error) = advapi32.CryptReleaseContext //sys CryptGenRandom(provhandle Handle, buflen uint32, buf *byte) (err error) = advapi32.CryptGenRandom //sys GetEnvironmentStrings() (envs *uint16, err error) [failretval==nil] = kernel32.GetEnvironmentStringsW //sys FreeEnvironmentStrings(envs *uint16) (err error) = kernel32.FreeEnvironmentStringsW //sys GetEnvironmentVariable(name *uint16, buffer *uint16, size uint32) (n uint32, err error) = kernel32.GetEnvironmentVariableW //sys SetEnvironmentVariable(name *uint16, value *uint16) (err error) = kernel32.SetEnvironmentVariableW //sys CreateEnvironmentBlock(block **uint16, token Token, inheritExisting bool) (err error) = userenv.CreateEnvironmentBlock //sys DestroyEnvironmentBlock(block *uint16) (err error) = userenv.DestroyEnvironmentBlock //sys getTickCount64() (ms uint64) = kernel32.GetTickCount64 //sys SetFileTime(handle Handle, ctime *Filetime, atime *Filetime, wtime *Filetime) (err error) //sys GetFileAttributes(name *uint16) (attrs uint32, err error) [failretval==INVALID_FILE_ATTRIBUTES] = kernel32.GetFileAttributesW //sys SetFileAttributes(name *uint16, attrs uint32) (err error) = kernel32.SetFileAttributesW //sys GetFileAttributesEx(name *uint16, level uint32, info *byte) (err error) = kernel32.GetFileAttributesExW //sys GetCommandLine() (cmd *uint16) = kernel32.GetCommandLineW //sys CommandLineToArgv(cmd *uint16, argc *int32) (argv *[8192]*[8192]uint16, err error) [failretval==nil] = shell32.CommandLineToArgvW //sys LocalFree(hmem Handle) (handle Handle, err error) [failretval!=0] //sys SetHandleInformation(handle Handle, mask uint32, flags uint32) (err error) //sys FlushFileBuffers(handle Handle) (err error) //sys GetFullPathName(path *uint16, buflen uint32, buf *uint16, fname **uint16) (n uint32, err error) = kernel32.GetFullPathNameW //sys GetLongPathName(path *uint16, buf *uint16, buflen uint32) (n uint32, err error) = kernel32.GetLongPathNameW //sys GetShortPathName(longpath *uint16, shortpath *uint16, buflen uint32) (n uint32, err error) = kernel32.GetShortPathNameW //sys CreateFileMapping(fhandle Handle, sa *SecurityAttributes, prot uint32, maxSizeHigh uint32, maxSizeLow uint32, name *uint16) (handle Handle, err error) = kernel32.CreateFileMappingW //sys MapViewOfFile(handle Handle, access uint32, offsetHigh uint32, offsetLow uint32, length uintptr) (addr uintptr, err error) //sys UnmapViewOfFile(addr uintptr) (err error) //sys FlushViewOfFile(addr uintptr, length uintptr) (err error) //sys VirtualLock(addr uintptr, length uintptr) (err error) //sys VirtualUnlock(addr uintptr, length uintptr) (err error) //sys VirtualAlloc(address uintptr, size uintptr, alloctype uint32, protect uint32) (value uintptr, err error) = kernel32.VirtualAlloc //sys VirtualFree(address uintptr, size uintptr, freetype uint32) (err error) = kernel32.VirtualFree //sys VirtualProtect(address uintptr, size uintptr, newprotect uint32, oldprotect *uint32) (err error) = kernel32.VirtualProtect //sys TransmitFile(s Handle, handle Handle, bytesToWrite uint32, bytsPerSend uint32, overlapped *Overlapped, transmitFileBuf *TransmitFileBuffers, flags uint32) (err error) = mswsock.TransmitFile //sys ReadDirectoryChanges(handle Handle, buf *byte, buflen uint32, watchSubTree bool, mask uint32, retlen *uint32, overlapped *Overlapped, completionRoutine uintptr) (err error) = kernel32.ReadDirectoryChangesW //sys CertOpenSystemStore(hprov Handle, name *uint16) (store Handle, err error) = crypt32.CertOpenSystemStoreW //sys CertOpenStore(storeProvider uintptr, msgAndCertEncodingType uint32, cryptProv uintptr, flags uint32, para uintptr) (handle Handle, err error) [failretval==InvalidHandle] = crypt32.CertOpenStore //sys CertEnumCertificatesInStore(store Handle, prevContext *CertContext) (context *CertContext, err error) [failretval==nil] = crypt32.CertEnumCertificatesInStore //sys CertAddCertificateContextToStore(store Handle, certContext *CertContext, addDisposition uint32, storeContext **CertContext) (err error) = crypt32.CertAddCertificateContextToStore //sys CertCloseStore(store Handle, flags uint32) (err error) = crypt32.CertCloseStore //sys CertGetCertificateChain(engine Handle, leaf *CertContext, time *Filetime, additionalStore Handle, para *CertChainPara, flags uint32, reserved uintptr, chainCtx **CertChainContext) (err error) = crypt32.CertGetCertificateChain //sys CertFreeCertificateChain(ctx *CertChainContext) = crypt32.CertFreeCertificateChain //sys CertCreateCertificateContext(certEncodingType uint32, certEncoded *byte, encodedLen uint32) (context *CertContext, err error) [failretval==nil] = crypt32.CertCreateCertificateContext //sys CertFreeCertificateContext(ctx *CertContext) (err error) = crypt32.CertFreeCertificateContext //sys CertVerifyCertificateChainPolicy(policyOID uintptr, chain *CertChainContext, para *CertChainPolicyPara, status *CertChainPolicyStatus) (err error) = crypt32.CertVerifyCertificateChainPolicy //sys RegOpenKeyEx(key Handle, subkey *uint16, options uint32, desiredAccess uint32, result *Handle) (regerrno error) = advapi32.RegOpenKeyExW //sys RegCloseKey(key Handle) (regerrno error) = advapi32.RegCloseKey //sys RegQueryInfoKey(key Handle, class *uint16, classLen *uint32, reserved *uint32, subkeysLen *uint32, maxSubkeyLen *uint32, maxClassLen *uint32, valuesLen *uint32, maxValueNameLen *uint32, maxValueLen *uint32, saLen *uint32, lastWriteTime *Filetime) (regerrno error) = advapi32.RegQueryInfoKeyW //sys RegEnumKeyEx(key Handle, index uint32, name *uint16, nameLen *uint32, reserved *uint32, class *uint16, classLen *uint32, lastWriteTime *Filetime) (regerrno error) = advapi32.RegEnumKeyExW //sys RegQueryValueEx(key Handle, name *uint16, reserved *uint32, valtype *uint32, buf *byte, buflen *uint32) (regerrno error) = advapi32.RegQueryValueExW //sys GetCurrentProcessId() (pid uint32) = kernel32.GetCurrentProcessId //sys GetConsoleMode(console Handle, mode *uint32) (err error) = kernel32.GetConsoleMode //sys SetConsoleMode(console Handle, mode uint32) (err error) = kernel32.SetConsoleMode //sys GetConsoleScreenBufferInfo(console Handle, info *ConsoleScreenBufferInfo) (err error) = kernel32.GetConsoleScreenBufferInfo //sys WriteConsole(console Handle, buf *uint16, towrite uint32, written *uint32, reserved *byte) (err error) = kernel32.WriteConsoleW //sys ReadConsole(console Handle, buf *uint16, toread uint32, read *uint32, inputControl *byte) (err error) = kernel32.ReadConsoleW //sys CreateToolhelp32Snapshot(flags uint32, processId uint32) (handle Handle, err error) [failretval==InvalidHandle] = kernel32.CreateToolhelp32Snapshot //sys Process32First(snapshot Handle, procEntry *ProcessEntry32) (err error) = kernel32.Process32FirstW //sys Process32Next(snapshot Handle, procEntry *ProcessEntry32) (err error) = kernel32.Process32NextW //sys Thread32First(snapshot Handle, threadEntry *ThreadEntry32) (err error) //sys Thread32Next(snapshot Handle, threadEntry *ThreadEntry32) (err error) //sys DeviceIoControl(handle Handle, ioControlCode uint32, inBuffer *byte, inBufferSize uint32, outBuffer *byte, outBufferSize uint32, bytesReturned *uint32, overlapped *Overlapped) (err error) // This function returns 1 byte BOOLEAN rather than the 4 byte BOOL. //sys CreateSymbolicLink(symlinkfilename *uint16, targetfilename *uint16, flags uint32) (err error) [failretval&0xff==0] = CreateSymbolicLinkW //sys CreateHardLink(filename *uint16, existingfilename *uint16, reserved uintptr) (err error) [failretval&0xff==0] = CreateHardLinkW //sys GetCurrentThreadId() (id uint32) //sys CreateEvent(eventAttrs *SecurityAttributes, manualReset uint32, initialState uint32, name *uint16) (handle Handle, err error) = kernel32.CreateEventW //sys CreateEventEx(eventAttrs *SecurityAttributes, name *uint16, flags uint32, desiredAccess uint32) (handle Handle, err error) = kernel32.CreateEventExW //sys OpenEvent(desiredAccess uint32, inheritHandle bool, name *uint16) (handle Handle, err error) = kernel32.OpenEventW //sys SetEvent(event Handle) (err error) = kernel32.SetEvent //sys ResetEvent(event Handle) (err error) = kernel32.ResetEvent //sys PulseEvent(event Handle) (err error) = kernel32.PulseEvent //sys CreateMutex(mutexAttrs *SecurityAttributes, initialOwner bool, name *uint16) (handle Handle, err error) = kernel32.CreateMutexW //sys CreateMutexEx(mutexAttrs *SecurityAttributes, name *uint16, flags uint32, desiredAccess uint32) (handle Handle, err error) = kernel32.CreateMutexExW //sys OpenMutex(desiredAccess uint32, inheritHandle bool, name *uint16) (handle Handle, err error) = kernel32.OpenMutexW //sys ReleaseMutex(mutex Handle) (err error) = kernel32.ReleaseMutex //sys SleepEx(milliseconds uint32, alertable bool) (ret uint32) = kernel32.SleepEx //sys CreateJobObject(jobAttr *SecurityAttributes, name *uint16) (handle Handle, err error) = kernel32.CreateJobObjectW //sys AssignProcessToJobObject(job Handle, process Handle) (err error) = kernel32.AssignProcessToJobObject //sys TerminateJobObject(job Handle, exitCode uint32) (err error) = kernel32.TerminateJobObject //sys SetErrorMode(mode uint32) (ret uint32) = kernel32.SetErrorMode //sys ResumeThread(thread Handle) (ret uint32, err error) [failretval==0xffffffff] = kernel32.ResumeThread //sys SetPriorityClass(process Handle, priorityClass uint32) (err error) = kernel32.SetPriorityClass //sys GetPriorityClass(process Handle) (ret uint32, err error) = kernel32.GetPriorityClass //sys SetInformationJobObject(job Handle, JobObjectInformationClass uint32, JobObjectInformation uintptr, JobObjectInformationLength uint32) (ret int, err error) //sys GenerateConsoleCtrlEvent(ctrlEvent uint32, processGroupID uint32) (err error) //sys GetProcessId(process Handle) (id uint32, err error) //sys OpenThread(desiredAccess uint32, inheritHandle bool, threadId uint32) (handle Handle, err error) //sys SetProcessPriorityBoost(process Handle, disable bool) (err error) = kernel32.SetProcessPriorityBoost // Volume Management Functions //sys DefineDosDevice(flags uint32, deviceName *uint16, targetPath *uint16) (err error) = DefineDosDeviceW //sys DeleteVolumeMountPoint(volumeMountPoint *uint16) (err error) = DeleteVolumeMountPointW //sys FindFirstVolume(volumeName *uint16, bufferLength uint32) (handle Handle, err error) [failretval==InvalidHandle] = FindFirstVolumeW //sys FindFirstVolumeMountPoint(rootPathName *uint16, volumeMountPoint *uint16, bufferLength uint32) (handle Handle, err error) [failretval==InvalidHandle] = FindFirstVolumeMountPointW //sys FindNextVolume(findVolume Handle, volumeName *uint16, bufferLength uint32) (err error) = FindNextVolumeW //sys FindNextVolumeMountPoint(findVolumeMountPoint Handle, volumeMountPoint *uint16, bufferLength uint32) (err error) = FindNextVolumeMountPointW //sys FindVolumeClose(findVolume Handle) (err error) //sys FindVolumeMountPointClose(findVolumeMountPoint Handle) (err error) //sys GetDiskFreeSpaceEx(directoryName *uint16, freeBytesAvailableToCaller *uint64, totalNumberOfBytes *uint64, totalNumberOfFreeBytes *uint64) (err error) = GetDiskFreeSpaceExW //sys GetDriveType(rootPathName *uint16) (driveType uint32) = GetDriveTypeW //sys GetLogicalDrives() (drivesBitMask uint32, err error) [failretval==0] //sys GetLogicalDriveStrings(bufferLength uint32, buffer *uint16) (n uint32, err error) [failretval==0] = GetLogicalDriveStringsW //sys GetVolumeInformation(rootPathName *uint16, volumeNameBuffer *uint16, volumeNameSize uint32, volumeNameSerialNumber *uint32, maximumComponentLength *uint32, fileSystemFlags *uint32, fileSystemNameBuffer *uint16, fileSystemNameSize uint32) (err error) = GetVolumeInformationW //sys GetVolumeInformationByHandle(file Handle, volumeNameBuffer *uint16, volumeNameSize uint32, volumeNameSerialNumber *uint32, maximumComponentLength *uint32, fileSystemFlags *uint32, fileSystemNameBuffer *uint16, fileSystemNameSize uint32) (err error) = GetVolumeInformationByHandleW //sys GetVolumeNameForVolumeMountPoint(volumeMountPoint *uint16, volumeName *uint16, bufferlength uint32) (err error) = GetVolumeNameForVolumeMountPointW //sys GetVolumePathName(fileName *uint16, volumePathName *uint16, bufferLength uint32) (err error) = GetVolumePathNameW //sys GetVolumePathNamesForVolumeName(volumeName *uint16, volumePathNames *uint16, bufferLength uint32, returnLength *uint32) (err error) = GetVolumePathNamesForVolumeNameW //sys QueryDosDevice(deviceName *uint16, targetPath *uint16, max uint32) (n uint32, err error) [failretval==0] = QueryDosDeviceW //sys SetVolumeLabel(rootPathName *uint16, volumeName *uint16) (err error) = SetVolumeLabelW //sys SetVolumeMountPoint(volumeMountPoint *uint16, volumeName *uint16) (err error) = SetVolumeMountPointW //sys MessageBox(hwnd Handle, text *uint16, caption *uint16, boxtype uint32) (ret int32, err error) [failretval==0] = user32.MessageBoxW //sys ExitWindowsEx(flags uint32, reason uint32) (err error) = user32.ExitWindowsEx //sys InitiateSystemShutdownEx(machineName *uint16, message *uint16, timeout uint32, forceAppsClosed bool, rebootAfterShutdown bool, reason uint32) (err error) = advapi32.InitiateSystemShutdownExW //sys SetProcessShutdownParameters(level uint32, flags uint32) (err error) = kernel32.SetProcessShutdownParameters //sys GetProcessShutdownParameters(level *uint32, flags *uint32) (err error) = kernel32.GetProcessShutdownParameters //sys clsidFromString(lpsz *uint16, pclsid *GUID) (ret error) = ole32.CLSIDFromString //sys stringFromGUID2(rguid *GUID, lpsz *uint16, cchMax int32) (chars int32) = ole32.StringFromGUID2 //sys coCreateGuid(pguid *GUID) (ret error) = ole32.CoCreateGuid //sys CoTaskMemFree(address unsafe.Pointer) = ole32.CoTaskMemFree //sys rtlGetVersion(info *OsVersionInfoEx) (ret error) = ntdll.RtlGetVersion //sys rtlGetNtVersionNumbers(majorVersion *uint32, minorVersion *uint32, buildNumber *uint32) = ntdll.RtlGetNtVersionNumbers //sys getProcessPreferredUILanguages(flags uint32, numLanguages *uint32, buf *uint16, bufSize *uint32) (err error) = kernel32.GetProcessPreferredUILanguages //sys getThreadPreferredUILanguages(flags uint32, numLanguages *uint32, buf *uint16, bufSize *uint32) (err error) = kernel32.GetThreadPreferredUILanguages //sys getUserPreferredUILanguages(flags uint32, numLanguages *uint32, buf *uint16, bufSize *uint32) (err error) = kernel32.GetUserPreferredUILanguages //sys getSystemPreferredUILanguages(flags uint32, numLanguages *uint32, buf *uint16, bufSize *uint32) (err error) = kernel32.GetSystemPreferredUILanguages // Process Status API (PSAPI) //sys EnumProcesses(processIds []uint32, bytesReturned *uint32) (err error) = psapi.EnumProcesses // syscall interface implementation for other packages // GetCurrentProcess returns the handle for the current process. // It is a pseudo handle that does not need to be closed. // The returned error is always nil. // // Deprecated: use CurrentProcess for the same Handle without the nil // error. func GetCurrentProcess() (Handle, error) { return CurrentProcess(), nil } // CurrentProcess returns the handle for the current process. // It is a pseudo handle that does not need to be closed. func CurrentProcess() Handle { return Handle(^uintptr(1 - 1)) } // GetCurrentThread returns the handle for the current thread. // It is a pseudo handle that does not need to be closed. // The returned error is always nil. // // Deprecated: use CurrentThread for the same Handle without the nil // error. func GetCurrentThread() (Handle, error) { return CurrentThread(), nil } // CurrentThread returns the handle for the current thread. // It is a pseudo handle that does not need to be closed. func CurrentThread() Handle { return Handle(^uintptr(2 - 1)) } // GetProcAddressByOrdinal retrieves the address of the exported // function from module by ordinal. func GetProcAddressByOrdinal(module Handle, ordinal uintptr) (proc uintptr, err error) { r0, _, e1 := syscall.Syscall(procGetProcAddress.Addr(), 2, uintptr(module), ordinal, 0) proc = uintptr(r0) if proc == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func Exit(code int) { ExitProcess(uint32(code)) } func makeInheritSa() *SecurityAttributes { var sa SecurityAttributes sa.Length = uint32(unsafe.Sizeof(sa)) sa.InheritHandle = 1 return &sa } func Open(path string, mode int, perm uint32) (fd Handle, err error) { if len(path) == 0 { return InvalidHandle, ERROR_FILE_NOT_FOUND } pathp, err := UTF16PtrFromString(path) if err != nil { return InvalidHandle, err } var access uint32 switch mode & (O_RDONLY | O_WRONLY | O_RDWR) { case O_RDONLY: access = GENERIC_READ case O_WRONLY: access = GENERIC_WRITE case O_RDWR: access = GENERIC_READ | GENERIC_WRITE } if mode&O_CREAT != 0 { access |= GENERIC_WRITE } if mode&O_APPEND != 0 { access &^= GENERIC_WRITE access |= FILE_APPEND_DATA } sharemode := uint32(FILE_SHARE_READ | FILE_SHARE_WRITE) var sa *SecurityAttributes if mode&O_CLOEXEC == 0 { sa = makeInheritSa() } var createmode uint32 switch { case mode&(O_CREAT|O_EXCL) == (O_CREAT | O_EXCL): createmode = CREATE_NEW case mode&(O_CREAT|O_TRUNC) == (O_CREAT | O_TRUNC): createmode = CREATE_ALWAYS case mode&O_CREAT == O_CREAT: createmode = OPEN_ALWAYS case mode&O_TRUNC == O_TRUNC: createmode = TRUNCATE_EXISTING default: createmode = OPEN_EXISTING } var attrs uint32 = FILE_ATTRIBUTE_NORMAL if perm&S_IWRITE == 0 { attrs = FILE_ATTRIBUTE_READONLY } h, e := CreateFile(pathp, access, sharemode, sa, createmode, attrs, 0) return h, e } func Read(fd Handle, p []byte) (n int, err error) { var done uint32 e := ReadFile(fd, p, &done, nil) if e != nil { if e == ERROR_BROKEN_PIPE { // NOTE(brainman): work around ERROR_BROKEN_PIPE is returned on reading EOF from stdin return 0, nil } return 0, e } if raceenabled { if done > 0 { raceWriteRange(unsafe.Pointer(&p[0]), int(done)) } raceAcquire(unsafe.Pointer(&ioSync)) } return int(done), nil } func Write(fd Handle, p []byte) (n int, err error) { if raceenabled { raceReleaseMerge(unsafe.Pointer(&ioSync)) } var done uint32 e := WriteFile(fd, p, &done, nil) if e != nil { return 0, e } if raceenabled && done > 0 { raceReadRange(unsafe.Pointer(&p[0]), int(done)) } return int(done), nil } var ioSync int64 func Seek(fd Handle, offset int64, whence int) (newoffset int64, err error) { var w uint32 switch whence { case 0: w = FILE_BEGIN case 1: w = FILE_CURRENT case 2: w = FILE_END } hi := int32(offset >> 32) lo := int32(offset) // use GetFileType to check pipe, pipe can't do seek ft, _ := GetFileType(fd) if ft == FILE_TYPE_PIPE { return 0, syscall.EPIPE } rlo, e := SetFilePointer(fd, lo, &hi, w) if e != nil { return 0, e } return int64(hi)<<32 + int64(rlo), nil } func Close(fd Handle) (err error) { return CloseHandle(fd) } var ( Stdin = getStdHandle(STD_INPUT_HANDLE) Stdout = getStdHandle(STD_OUTPUT_HANDLE) Stderr = getStdHandle(STD_ERROR_HANDLE) ) func getStdHandle(stdhandle uint32) (fd Handle) { r, _ := GetStdHandle(stdhandle) CloseOnExec(r) return r } const ImplementsGetwd = true func Getwd() (wd string, err error) { b := make([]uint16, 300) n, e := GetCurrentDirectory(uint32(len(b)), &b[0]) if e != nil { return "", e } return string(utf16.Decode(b[0:n])), nil } func Chdir(path string) (err error) { pathp, err := UTF16PtrFromString(path) if err != nil { return err } return SetCurrentDirectory(pathp) } func Mkdir(path string, mode uint32) (err error) { pathp, err := UTF16PtrFromString(path) if err != nil { return err } return CreateDirectory(pathp, nil) } func Rmdir(path string) (err error) { pathp, err := UTF16PtrFromString(path) if err != nil { return err } return RemoveDirectory(pathp) } func Unlink(path string) (err error) { pathp, err := UTF16PtrFromString(path) if err != nil { return err } return DeleteFile(pathp) } func Rename(oldpath, newpath string) (err error) { from, err := UTF16PtrFromString(oldpath) if err != nil { return err } to, err := UTF16PtrFromString(newpath) if err != nil { return err } return MoveFileEx(from, to, MOVEFILE_REPLACE_EXISTING) } func ComputerName() (name string, err error) { var n uint32 = MAX_COMPUTERNAME_LENGTH + 1 b := make([]uint16, n) e := GetComputerName(&b[0], &n) if e != nil { return "", e } return string(utf16.Decode(b[0:n])), nil } func DurationSinceBoot() time.Duration { return time.Duration(getTickCount64()) * time.Millisecond } func Ftruncate(fd Handle, length int64) (err error) { curoffset, e := Seek(fd, 0, 1) if e != nil { return e } defer Seek(fd, curoffset, 0) _, e = Seek(fd, length, 0) if e != nil { return e } e = SetEndOfFile(fd) if e != nil { return e } return nil } func Gettimeofday(tv *Timeval) (err error) { var ft Filetime GetSystemTimeAsFileTime(&ft) *tv = NsecToTimeval(ft.Nanoseconds()) return nil } func Pipe(p []Handle) (err error) { if len(p) != 2 { return syscall.EINVAL } var r, w Handle e := CreatePipe(&r, &w, makeInheritSa(), 0) if e != nil { return e } p[0] = r p[1] = w return nil } func Utimes(path string, tv []Timeval) (err error) { if len(tv) != 2 { return syscall.EINVAL } pathp, e := UTF16PtrFromString(path) if e != nil { return e } h, e := CreateFile(pathp, FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, nil, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0) if e != nil { return e } defer Close(h) a := NsecToFiletime(tv[0].Nanoseconds()) w := NsecToFiletime(tv[1].Nanoseconds()) return SetFileTime(h, nil, &a, &w) } func UtimesNano(path string, ts []Timespec) (err error) { if len(ts) != 2 { return syscall.EINVAL } pathp, e := UTF16PtrFromString(path) if e != nil { return e } h, e := CreateFile(pathp, FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, nil, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0) if e != nil { return e } defer Close(h) a := NsecToFiletime(TimespecToNsec(ts[0])) w := NsecToFiletime(TimespecToNsec(ts[1])) return SetFileTime(h, nil, &a, &w) } func Fsync(fd Handle) (err error) { return FlushFileBuffers(fd) } func Chmod(path string, mode uint32) (err error) { p, e := UTF16PtrFromString(path) if e != nil { return e } attrs, e := GetFileAttributes(p) if e != nil { return e } if mode&S_IWRITE != 0 { attrs &^= FILE_ATTRIBUTE_READONLY } else { attrs |= FILE_ATTRIBUTE_READONLY } return SetFileAttributes(p, attrs) } func LoadGetSystemTimePreciseAsFileTime() error { return procGetSystemTimePreciseAsFileTime.Find() } func LoadCancelIoEx() error { return procCancelIoEx.Find() } func LoadSetFileCompletionNotificationModes() error { return procSetFileCompletionNotificationModes.Find() } func WaitForMultipleObjects(handles []Handle, waitAll bool, waitMilliseconds uint32) (event uint32, err error) { // Every other win32 array API takes arguments as "pointer, count", except for this function. So we // can't declare it as a usual [] type, because mksyscall will use the opposite order. We therefore // trivially stub this ourselves. var handlePtr *Handle if len(handles) > 0 { handlePtr = &handles[0] } return waitForMultipleObjects(uint32(len(handles)), uintptr(unsafe.Pointer(handlePtr)), waitAll, waitMilliseconds) } // net api calls const socket_error = uintptr(^uint32(0)) //sys WSAStartup(verreq uint32, data *WSAData) (sockerr error) = ws2_32.WSAStartup //sys WSACleanup() (err error) [failretval==socket_error] = ws2_32.WSACleanup //sys WSAIoctl(s Handle, iocc uint32, inbuf *byte, cbif uint32, outbuf *byte, cbob uint32, cbbr *uint32, overlapped *Overlapped, completionRoutine uintptr) (err error) [failretval==socket_error] = ws2_32.WSAIoctl //sys socket(af int32, typ int32, protocol int32) (handle Handle, err error) [failretval==InvalidHandle] = ws2_32.socket //sys sendto(s Handle, buf []byte, flags int32, to unsafe.Pointer, tolen int32) (err error) [failretval==socket_error] = ws2_32.sendto //sys recvfrom(s Handle, buf []byte, flags int32, from *RawSockaddrAny, fromlen *int32) (n int32, err error) [failretval==-1] = ws2_32.recvfrom //sys Setsockopt(s Handle, level int32, optname int32, optval *byte, optlen int32) (err error) [failretval==socket_error] = ws2_32.setsockopt //sys Getsockopt(s Handle, level int32, optname int32, optval *byte, optlen *int32) (err error) [failretval==socket_error] = ws2_32.getsockopt //sys bind(s Handle, name unsafe.Pointer, namelen int32) (err error) [failretval==socket_error] = ws2_32.bind //sys connect(s Handle, name unsafe.Pointer, namelen int32) (err error) [failretval==socket_error] = ws2_32.connect //sys getsockname(s Handle, rsa *RawSockaddrAny, addrlen *int32) (err error) [failretval==socket_error] = ws2_32.getsockname //sys getpeername(s Handle, rsa *RawSockaddrAny, addrlen *int32) (err error) [failretval==socket_error] = ws2_32.getpeername //sys listen(s Handle, backlog int32) (err error) [failretval==socket_error] = ws2_32.listen //sys shutdown(s Handle, how int32) (err error) [failretval==socket_error] = ws2_32.shutdown //sys Closesocket(s Handle) (err error) [failretval==socket_error] = ws2_32.closesocket //sys AcceptEx(ls Handle, as Handle, buf *byte, rxdatalen uint32, laddrlen uint32, raddrlen uint32, recvd *uint32, overlapped *Overlapped) (err error) = mswsock.AcceptEx //sys GetAcceptExSockaddrs(buf *byte, rxdatalen uint32, laddrlen uint32, raddrlen uint32, lrsa **RawSockaddrAny, lrsalen *int32, rrsa **RawSockaddrAny, rrsalen *int32) = mswsock.GetAcceptExSockaddrs //sys WSARecv(s Handle, bufs *WSABuf, bufcnt uint32, recvd *uint32, flags *uint32, overlapped *Overlapped, croutine *byte) (err error) [failretval==socket_error] = ws2_32.WSARecv //sys WSASend(s Handle, bufs *WSABuf, bufcnt uint32, sent *uint32, flags uint32, overlapped *Overlapped, croutine *byte) (err error) [failretval==socket_error] = ws2_32.WSASend //sys WSARecvFrom(s Handle, bufs *WSABuf, bufcnt uint32, recvd *uint32, flags *uint32, from *RawSockaddrAny, fromlen *int32, overlapped *Overlapped, croutine *byte) (err error) [failretval==socket_error] = ws2_32.WSARecvFrom //sys WSASendTo(s Handle, bufs *WSABuf, bufcnt uint32, sent *uint32, flags uint32, to *RawSockaddrAny, tolen int32, overlapped *Overlapped, croutine *byte) (err error) [failretval==socket_error] = ws2_32.WSASendTo //sys GetHostByName(name string) (h *Hostent, err error) [failretval==nil] = ws2_32.gethostbyname //sys GetServByName(name string, proto string) (s *Servent, err error) [failretval==nil] = ws2_32.getservbyname //sys Ntohs(netshort uint16) (u uint16) = ws2_32.ntohs //sys GetProtoByName(name string) (p *Protoent, err error) [failretval==nil] = ws2_32.getprotobyname //sys DnsQuery(name string, qtype uint16, options uint32, extra *byte, qrs **DNSRecord, pr *byte) (status error) = dnsapi.DnsQuery_W //sys DnsRecordListFree(rl *DNSRecord, freetype uint32) = dnsapi.DnsRecordListFree //sys DnsNameCompare(name1 *uint16, name2 *uint16) (same bool) = dnsapi.DnsNameCompare_W //sys GetAddrInfoW(nodename *uint16, servicename *uint16, hints *AddrinfoW, result **AddrinfoW) (sockerr error) = ws2_32.GetAddrInfoW //sys FreeAddrInfoW(addrinfo *AddrinfoW) = ws2_32.FreeAddrInfoW //sys GetIfEntry(pIfRow *MibIfRow) (errcode error) = iphlpapi.GetIfEntry //sys GetAdaptersInfo(ai *IpAdapterInfo, ol *uint32) (errcode error) = iphlpapi.GetAdaptersInfo //sys SetFileCompletionNotificationModes(handle Handle, flags uint8) (err error) = kernel32.SetFileCompletionNotificationModes //sys WSAEnumProtocols(protocols *int32, protocolBuffer *WSAProtocolInfo, bufferLength *uint32) (n int32, err error) [failretval==-1] = ws2_32.WSAEnumProtocolsW //sys GetAdaptersAddresses(family uint32, flags uint32, reserved uintptr, adapterAddresses *IpAdapterAddresses, sizePointer *uint32) (errcode error) = iphlpapi.GetAdaptersAddresses //sys GetACP() (acp uint32) = kernel32.GetACP //sys MultiByteToWideChar(codePage uint32, dwFlags uint32, str *byte, nstr int32, wchar *uint16, nwchar int32) (nwrite int32, err error) = kernel32.MultiByteToWideChar // For testing: clients can set this flag to force // creation of IPv6 sockets to return EAFNOSUPPORT. var SocketDisableIPv6 bool type RawSockaddrInet4 struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ Zero [8]uint8 } type RawSockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type RawSockaddr struct { Family uint16 Data [14]int8 } type RawSockaddrAny struct { Addr RawSockaddr Pad [100]int8 } type Sockaddr interface { sockaddr() (ptr unsafe.Pointer, len int32, err error) // lowercase; only we can define Sockaddrs } type SockaddrInet4 struct { Port int Addr [4]byte raw RawSockaddrInet4 } func (sa *SockaddrInet4) sockaddr() (unsafe.Pointer, int32, error) { if sa.Port < 0 || sa.Port > 0xFFFF { return nil, 0, syscall.EINVAL } sa.raw.Family = AF_INET p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port)) p[0] = byte(sa.Port >> 8) p[1] = byte(sa.Port) for i := 0; i < len(sa.Addr); i++ { sa.raw.Addr[i] = sa.Addr[i] } return unsafe.Pointer(&sa.raw), int32(unsafe.Sizeof(sa.raw)), nil } type SockaddrInet6 struct { Port int ZoneId uint32 Addr [16]byte raw RawSockaddrInet6 } func (sa *SockaddrInet6) sockaddr() (unsafe.Pointer, int32, error) { if sa.Port < 0 || sa.Port > 0xFFFF { return nil, 0, syscall.EINVAL } sa.raw.Family = AF_INET6 p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port)) p[0] = byte(sa.Port >> 8) p[1] = byte(sa.Port) sa.raw.Scope_id = sa.ZoneId for i := 0; i < len(sa.Addr); i++ { sa.raw.Addr[i] = sa.Addr[i] } return unsafe.Pointer(&sa.raw), int32(unsafe.Sizeof(sa.raw)), nil } type RawSockaddrUnix struct { Family uint16 Path [UNIX_PATH_MAX]int8 } type SockaddrUnix struct { Name string raw RawSockaddrUnix } func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, int32, error) { name := sa.Name n := len(name) if n > len(sa.raw.Path) { return nil, 0, syscall.EINVAL } if n == len(sa.raw.Path) && name[0] != '@' { return nil, 0, syscall.EINVAL } sa.raw.Family = AF_UNIX for i := 0; i < n; i++ { sa.raw.Path[i] = int8(name[i]) } // length is family (uint16), name, NUL. sl := int32(2) if n > 0 { sl += int32(n) + 1 } if sa.raw.Path[0] == '@' { sa.raw.Path[0] = 0 // Don't count trailing NUL for abstract address. sl-- } return unsafe.Pointer(&sa.raw), sl, nil } func (rsa *RawSockaddrAny) Sockaddr() (Sockaddr, error) { switch rsa.Addr.Family { case AF_UNIX: pp := (*RawSockaddrUnix)(unsafe.Pointer(rsa)) sa := new(SockaddrUnix) if pp.Path[0] == 0 { // "Abstract" Unix domain socket. // Rewrite leading NUL as @ for textual display. // (This is the standard convention.) // Not friendly to overwrite in place, // but the callers below don't care. pp.Path[0] = '@' } // Assume path ends at NUL. // This is not technically the Linux semantics for // abstract Unix domain sockets--they are supposed // to be uninterpreted fixed-size binary blobs--but // everyone uses this convention. n := 0 for n < len(pp.Path) && pp.Path[n] != 0 { n++ } bytes := (*[len(pp.Path)]byte)(unsafe.Pointer(&pp.Path[0]))[0:n] sa.Name = string(bytes) return sa, nil case AF_INET: pp := (*RawSockaddrInet4)(unsafe.Pointer(rsa)) sa := new(SockaddrInet4) p := (*[2]byte)(unsafe.Pointer(&pp.Port)) sa.Port = int(p[0])<<8 + int(p[1]) for i := 0; i < len(sa.Addr); i++ { sa.Addr[i] = pp.Addr[i] } return sa, nil case AF_INET6: pp := (*RawSockaddrInet6)(unsafe.Pointer(rsa)) sa := new(SockaddrInet6) p := (*[2]byte)(unsafe.Pointer(&pp.Port)) sa.Port = int(p[0])<<8 + int(p[1]) sa.ZoneId = pp.Scope_id for i := 0; i < len(sa.Addr); i++ { sa.Addr[i] = pp.Addr[i] } return sa, nil } return nil, syscall.EAFNOSUPPORT } func Socket(domain, typ, proto int) (fd Handle, err error) { if domain == AF_INET6 && SocketDisableIPv6 { return InvalidHandle, syscall.EAFNOSUPPORT } return socket(int32(domain), int32(typ), int32(proto)) } func SetsockoptInt(fd Handle, level, opt int, value int) (err error) { v := int32(value) return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(&v)), int32(unsafe.Sizeof(v))) } func Bind(fd Handle, sa Sockaddr) (err error) { ptr, n, err := sa.sockaddr() if err != nil { return err } return bind(fd, ptr, n) } func Connect(fd Handle, sa Sockaddr) (err error) { ptr, n, err := sa.sockaddr() if err != nil { return err } return connect(fd, ptr, n) } func Getsockname(fd Handle) (sa Sockaddr, err error) { var rsa RawSockaddrAny l := int32(unsafe.Sizeof(rsa)) if err = getsockname(fd, &rsa, &l); err != nil { return } return rsa.Sockaddr() } func Getpeername(fd Handle) (sa Sockaddr, err error) { var rsa RawSockaddrAny l := int32(unsafe.Sizeof(rsa)) if err = getpeername(fd, &rsa, &l); err != nil { return } return rsa.Sockaddr() } func Listen(s Handle, n int) (err error) { return listen(s, int32(n)) } func Shutdown(fd Handle, how int) (err error) { return shutdown(fd, int32(how)) } func WSASendto(s Handle, bufs *WSABuf, bufcnt uint32, sent *uint32, flags uint32, to Sockaddr, overlapped *Overlapped, croutine *byte) (err error) { rsa, l, err := to.sockaddr() if err != nil { return err } return WSASendTo(s, bufs, bufcnt, sent, flags, (*RawSockaddrAny)(unsafe.Pointer(rsa)), l, overlapped, croutine) } func LoadGetAddrInfo() error { return procGetAddrInfoW.Find() } var connectExFunc struct { once sync.Once addr uintptr err error } func LoadConnectEx() error { connectExFunc.once.Do(func() { var s Handle s, connectExFunc.err = Socket(AF_INET, SOCK_STREAM, IPPROTO_TCP) if connectExFunc.err != nil { return } defer CloseHandle(s) var n uint32 connectExFunc.err = WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, (*byte)(unsafe.Pointer(&WSAID_CONNECTEX)), uint32(unsafe.Sizeof(WSAID_CONNECTEX)), (*byte)(unsafe.Pointer(&connectExFunc.addr)), uint32(unsafe.Sizeof(connectExFunc.addr)), &n, nil, 0) }) return connectExFunc.err } func connectEx(s Handle, name unsafe.Pointer, namelen int32, sendBuf *byte, sendDataLen uint32, bytesSent *uint32, overlapped *Overlapped) (err error) { r1, _, e1 := syscall.Syscall9(connectExFunc.addr, 7, uintptr(s), uintptr(name), uintptr(namelen), uintptr(unsafe.Pointer(sendBuf)), uintptr(sendDataLen), uintptr(unsafe.Pointer(bytesSent)), uintptr(unsafe.Pointer(overlapped)), 0, 0) if r1 == 0 { if e1 != 0 { err = error(e1) } else { err = syscall.EINVAL } } return } func ConnectEx(fd Handle, sa Sockaddr, sendBuf *byte, sendDataLen uint32, bytesSent *uint32, overlapped *Overlapped) error { err := LoadConnectEx() if err != nil { return errorspkg.New("failed to find ConnectEx: " + err.Error()) } ptr, n, err := sa.sockaddr() if err != nil { return err } return connectEx(fd, ptr, n, sendBuf, sendDataLen, bytesSent, overlapped) } var sendRecvMsgFunc struct { once sync.Once sendAddr uintptr recvAddr uintptr err error } func loadWSASendRecvMsg() error { sendRecvMsgFunc.once.Do(func() { var s Handle s, sendRecvMsgFunc.err = Socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP) if sendRecvMsgFunc.err != nil { return } defer CloseHandle(s) var n uint32 sendRecvMsgFunc.err = WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, (*byte)(unsafe.Pointer(&WSAID_WSARECVMSG)), uint32(unsafe.Sizeof(WSAID_WSARECVMSG)), (*byte)(unsafe.Pointer(&sendRecvMsgFunc.recvAddr)), uint32(unsafe.Sizeof(sendRecvMsgFunc.recvAddr)), &n, nil, 0) if sendRecvMsgFunc.err != nil { return } sendRecvMsgFunc.err = WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, (*byte)(unsafe.Pointer(&WSAID_WSASENDMSG)), uint32(unsafe.Sizeof(WSAID_WSASENDMSG)), (*byte)(unsafe.Pointer(&sendRecvMsgFunc.sendAddr)), uint32(unsafe.Sizeof(sendRecvMsgFunc.sendAddr)), &n, nil, 0) }) return sendRecvMsgFunc.err } func WSASendMsg(fd Handle, msg *WSAMsg, flags uint32, bytesSent *uint32, overlapped *Overlapped, croutine *byte) error { err := loadWSASendRecvMsg() if err != nil { return err } r1, _, e1 := syscall.Syscall6(sendRecvMsgFunc.sendAddr, 6, uintptr(fd), uintptr(unsafe.Pointer(msg)), uintptr(flags), uintptr(unsafe.Pointer(bytesSent)), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(croutine))) if r1 == socket_error { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return err } func WSARecvMsg(fd Handle, msg *WSAMsg, bytesReceived *uint32, overlapped *Overlapped, croutine *byte) error { err := loadWSASendRecvMsg() if err != nil { return err } r1, _, e1 := syscall.Syscall6(sendRecvMsgFunc.recvAddr, 5, uintptr(fd), uintptr(unsafe.Pointer(msg)), uintptr(unsafe.Pointer(bytesReceived)), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(croutine)), 0) if r1 == socket_error { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return err } // Invented structures to support what package os expects. type Rusage struct { CreationTime Filetime ExitTime Filetime KernelTime Filetime UserTime Filetime } type WaitStatus struct { ExitCode uint32 } func (w WaitStatus) Exited() bool { return true } func (w WaitStatus) ExitStatus() int { return int(w.ExitCode) } func (w WaitStatus) Signal() Signal { return -1 } func (w WaitStatus) CoreDump() bool { return false } func (w WaitStatus) Stopped() bool { return false } func (w WaitStatus) Continued() bool { return false } func (w WaitStatus) StopSignal() Signal { return -1 } func (w WaitStatus) Signaled() bool { return false } func (w WaitStatus) TrapCause() int { return -1 } // Timespec is an invented structure on Windows, but here for // consistency with the corresponding package for other operating systems. type Timespec struct { Sec int64 Nsec int64 } func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } func NsecToTimespec(nsec int64) (ts Timespec) { ts.Sec = nsec / 1e9 ts.Nsec = nsec % 1e9 return } // TODO(brainman): fix all needed for net func Accept(fd Handle) (nfd Handle, sa Sockaddr, err error) { return 0, nil, syscall.EWINDOWS } func Recvfrom(fd Handle, p []byte, flags int) (n int, from Sockaddr, err error) { var rsa RawSockaddrAny l := int32(unsafe.Sizeof(rsa)) n32, err := recvfrom(fd, p, int32(flags), &rsa, &l) n = int(n32) if err != nil { return } from, err = rsa.Sockaddr() return } func Sendto(fd Handle, p []byte, flags int, to Sockaddr) (err error) { ptr, l, err := to.sockaddr() if err != nil { return err } return sendto(fd, p, int32(flags), ptr, l) } func SetsockoptTimeval(fd Handle, level, opt int, tv *Timeval) (err error) { return syscall.EWINDOWS } // The Linger struct is wrong but we only noticed after Go 1. // sysLinger is the real system call structure. // BUG(brainman): The definition of Linger is not appropriate for direct use // with Setsockopt and Getsockopt. // Use SetsockoptLinger instead. type Linger struct { Onoff int32 Linger int32 } type sysLinger struct { Onoff uint16 Linger uint16 } type IPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type IPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } func GetsockoptInt(fd Handle, level, opt int) (int, error) { return -1, syscall.EWINDOWS } func SetsockoptLinger(fd Handle, level, opt int, l *Linger) (err error) { sys := sysLinger{Onoff: uint16(l.Onoff), Linger: uint16(l.Linger)} return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(&sys)), int32(unsafe.Sizeof(sys))) } func SetsockoptInet4Addr(fd Handle, level, opt int, value [4]byte) (err error) { return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(&value[0])), 4) } func SetsockoptIPMreq(fd Handle, level, opt int, mreq *IPMreq) (err error) { return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(mreq)), int32(unsafe.Sizeof(*mreq))) } func SetsockoptIPv6Mreq(fd Handle, level, opt int, mreq *IPv6Mreq) (err error) { return syscall.EWINDOWS } func Getpid() (pid int) { return int(GetCurrentProcessId()) } func FindFirstFile(name *uint16, data *Win32finddata) (handle Handle, err error) { // NOTE(rsc): The Win32finddata struct is wrong for the system call: // the two paths are each one uint16 short. Use the correct struct, // a win32finddata1, and then copy the results out. // There is no loss of expressivity here, because the final // uint16, if it is used, is supposed to be a NUL, and Go doesn't need that. // For Go 1.1, we might avoid the allocation of win32finddata1 here // by adding a final Bug [2]uint16 field to the struct and then // adjusting the fields in the result directly. var data1 win32finddata1 handle, err = findFirstFile1(name, &data1) if err == nil { copyFindData(data, &data1) } return } func FindNextFile(handle Handle, data *Win32finddata) (err error) { var data1 win32finddata1 err = findNextFile1(handle, &data1) if err == nil { copyFindData(data, &data1) } return } func getProcessEntry(pid int) (*ProcessEntry32, error) { snapshot, err := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) if err != nil { return nil, err } defer CloseHandle(snapshot) var procEntry ProcessEntry32 procEntry.Size = uint32(unsafe.Sizeof(procEntry)) if err = Process32First(snapshot, &procEntry); err != nil { return nil, err } for { if procEntry.ProcessID == uint32(pid) { return &procEntry, nil } err = Process32Next(snapshot, &procEntry) if err != nil { return nil, err } } } func Getppid() (ppid int) { pe, err := getProcessEntry(Getpid()) if err != nil { return -1 } return int(pe.ParentProcessID) } // TODO(brainman): fix all needed for os func Fchdir(fd Handle) (err error) { return syscall.EWINDOWS } func Link(oldpath, newpath string) (err error) { return syscall.EWINDOWS } func Symlink(path, link string) (err error) { return syscall.EWINDOWS } func Fchmod(fd Handle, mode uint32) (err error) { return syscall.EWINDOWS } func Chown(path string, uid int, gid int) (err error) { return syscall.EWINDOWS } func Lchown(path string, uid int, gid int) (err error) { return syscall.EWINDOWS } func Fchown(fd Handle, uid int, gid int) (err error) { return syscall.EWINDOWS } func Getuid() (uid int) { return -1 } func Geteuid() (euid int) { return -1 } func Getgid() (gid int) { return -1 } func Getegid() (egid int) { return -1 } func Getgroups() (gids []int, err error) { return nil, syscall.EWINDOWS } type Signal int func (s Signal) Signal() {} func (s Signal) String() string { if 0 <= s && int(s) < len(signals) { str := signals[s] if str != "" { return str } } return "signal " + itoa(int(s)) } func LoadCreateSymbolicLink() error { return procCreateSymbolicLinkW.Find() } // Readlink returns the destination of the named symbolic link. func Readlink(path string, buf []byte) (n int, err error) { fd, err := CreateFile(StringToUTF16Ptr(path), GENERIC_READ, 0, nil, OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_BACKUP_SEMANTICS, 0) if err != nil { return -1, err } defer CloseHandle(fd) rdbbuf := make([]byte, MAXIMUM_REPARSE_DATA_BUFFER_SIZE) var bytesReturned uint32 err = DeviceIoControl(fd, FSCTL_GET_REPARSE_POINT, nil, 0, &rdbbuf[0], uint32(len(rdbbuf)), &bytesReturned, nil) if err != nil { return -1, err } rdb := (*reparseDataBuffer)(unsafe.Pointer(&rdbbuf[0])) var s string switch rdb.ReparseTag { case IO_REPARSE_TAG_SYMLINK: data := (*symbolicLinkReparseBuffer)(unsafe.Pointer(&rdb.reparseBuffer)) p := (*[0xffff]uint16)(unsafe.Pointer(&data.PathBuffer[0])) s = UTF16ToString(p[data.PrintNameOffset/2 : (data.PrintNameLength-data.PrintNameOffset)/2]) case IO_REPARSE_TAG_MOUNT_POINT: data := (*mountPointReparseBuffer)(unsafe.Pointer(&rdb.reparseBuffer)) p := (*[0xffff]uint16)(unsafe.Pointer(&data.PathBuffer[0])) s = UTF16ToString(p[data.PrintNameOffset/2 : (data.PrintNameLength-data.PrintNameOffset)/2]) default: // the path is not a symlink or junction but another type of reparse // point return -1, syscall.ENOENT } n = copy(buf, []byte(s)) return n, nil } // GUIDFromString parses a string in the form of // "{XXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}" into a GUID. func GUIDFromString(str string) (GUID, error) { guid := GUID{} str16, err := syscall.UTF16PtrFromString(str) if err != nil { return guid, err } err = clsidFromString(str16, &guid) if err != nil { return guid, err } return guid, nil } // GenerateGUID creates a new random GUID. func GenerateGUID() (GUID, error) { guid := GUID{} err := coCreateGuid(&guid) if err != nil { return guid, err } return guid, nil } // String returns the canonical string form of the GUID, // in the form of "{XXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}". func (guid GUID) String() string { var str [100]uint16 chars := stringFromGUID2(&guid, &str[0], int32(len(str))) if chars <= 1 { return "" } return string(utf16.Decode(str[:chars-1])) } // KnownFolderPath returns a well-known folder path for the current user, specified by one of // the FOLDERID_ constants, and chosen and optionally created based on a KF_ flag. func KnownFolderPath(folderID *KNOWNFOLDERID, flags uint32) (string, error) { return Token(0).KnownFolderPath(folderID, flags) } // KnownFolderPath returns a well-known folder path for the user token, specified by one of // the FOLDERID_ constants, and chosen and optionally created based on a KF_ flag. func (t Token) KnownFolderPath(folderID *KNOWNFOLDERID, flags uint32) (string, error) { var p *uint16 err := shGetKnownFolderPath(folderID, flags, t, &p) if err != nil { return "", err } defer CoTaskMemFree(unsafe.Pointer(p)) return UTF16ToString((*[(1 << 30) - 1]uint16)(unsafe.Pointer(p))[:]), nil } // RtlGetVersion returns the version of the underlying operating system, ignoring // manifest semantics but is affected by the application compatibility layer. func RtlGetVersion() *OsVersionInfoEx { info := &OsVersionInfoEx{} info.osVersionInfoSize = uint32(unsafe.Sizeof(*info)) // According to documentation, this function always succeeds. // The function doesn't even check the validity of the // osVersionInfoSize member. Disassembling ntdll.dll indicates // that the documentation is indeed correct about that. _ = rtlGetVersion(info) return info } // RtlGetNtVersionNumbers returns the version of the underlying operating system, // ignoring manifest semantics and the application compatibility layer. func RtlGetNtVersionNumbers() (majorVersion, minorVersion, buildNumber uint32) { rtlGetNtVersionNumbers(&majorVersion, &minorVersion, &buildNumber) buildNumber &= 0xffff return } // GetProcessPreferredUILanguages retrieves the process preferred UI languages. func GetProcessPreferredUILanguages(flags uint32) ([]string, error) { return getUILanguages(flags, getProcessPreferredUILanguages) } // GetThreadPreferredUILanguages retrieves the thread preferred UI languages for the current thread. func GetThreadPreferredUILanguages(flags uint32) ([]string, error) { return getUILanguages(flags, getThreadPreferredUILanguages) } // GetUserPreferredUILanguages retrieves information about the user preferred UI languages. func GetUserPreferredUILanguages(flags uint32) ([]string, error) { return getUILanguages(flags, getUserPreferredUILanguages) } // GetSystemPreferredUILanguages retrieves the system preferred UI languages. func GetSystemPreferredUILanguages(flags uint32) ([]string, error) { return getUILanguages(flags, getSystemPreferredUILanguages) } func getUILanguages(flags uint32, f func(flags uint32, numLanguages *uint32, buf *uint16, bufSize *uint32) error) ([]string, error) { size := uint32(128) for { var numLanguages uint32 buf := make([]uint16, size) err := f(flags, &numLanguages, &buf[0], &size) if err == ERROR_INSUFFICIENT_BUFFER { continue } if err != nil { return nil, err } buf = buf[:size] if numLanguages == 0 || len(buf) == 0 { // GetProcessPreferredUILanguages may return numLanguages==0 with "\0\0" return []string{}, nil } if buf[len(buf)-1] == 0 { buf = buf[:len(buf)-1] // remove terminating null } languages := make([]string, 0, numLanguages) from := 0 for i, c := range buf { if c == 0 { languages = append(languages, string(utf16.Decode(buf[from:i]))) from = i + 1 } } return languages, nil } }
{ "pile_set_name": "Github" }
SET(PROJECT_NAME vikit_ros) PROJECT(${PROJECT_NAME}) CMAKE_MINIMUM_REQUIRED (VERSION 2.8.3) SET(CMAKE_BUILD_TYPE Release) # Release, RelWithDebInfo SET(CMAKE_VERBOSE_MAKEFILE OFF) # Set build flags SET(CMAKE_CXX_FLAGS "-Wall -D_LINUX -D_REENTRANT -march=native -Wno-unused-variable -Wno-unused-but-set-variable -Wno-unknown-pragmas") SET(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS} -O0 -g") IF(CMAKE_COMPILER_IS_GNUCC) SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x") ELSE() SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") ENDIF() # Add catkin and required ROS packages FIND_PACKAGE(catkin REQUIRED COMPONENTS roscpp vikit_common visualization_msgs tf cmake_modules) # Add plain cmake packages FIND_PACKAGE(OpenCV REQUIRED) FIND_PACKAGE(Eigen REQUIRED) FIND_PACKAGE(Sophus REQUIRED) # Include dirs INCLUDE_DIRECTORIES( include ${Eigen_INCLUDE_DIRS} ${OpenCV_INCLUDE_DIRS} ${Sophus_INCLUDE_DIRS} ${catkin_INCLUDE_DIRS} ) # Describe catkin Project catkin_package( DEPENDS Eigen OpenCV Sophus vikit_common CATKIN_DEPENDS roscpp visualization_msgs tf INCLUDE_DIRS include LIBRARIES ${PROJECT_NAME} ) # Set Sourcefiles LIST(APPEND SOURCEFILES src/output_helper.cpp ) # Create vikit library ADD_LIBRARY(${PROJECT_NAME} SHARED ${SOURCEFILES}) TARGET_LINK_LIBRARIES( ${PROJECT_NAME} ${OpenCV_LIBS} ${Sophus_LIBRARIES} ${catkin_LIBRARIES})
{ "pile_set_name": "Github" }
<?php namespace Everyman\Neo4j\Cache; class MemcachedTest extends \PHPUnit_Framework_TestCase { protected $memcached = null; protected $cache = null; public function setUp() { $memcachedVersion = phpversion('memcached'); if (!$memcachedVersion) { $this->markTestSkipped('Memcached extension not enabled/installed'); } else if (version_compare($memcachedVersion, '2.2.0', '>=')) { $this->markTestSkipped('Memcached tests can only be run with memcached extension 2.1.0 or lower'); } $this->memcached = $this->getMock('\Memcached'); $this->cache = new Memcached($this->memcached); } public function testSet_PassesThroughToMemcached() { $this->memcached->expects($this->once()) ->method('set') ->with('somekey', 'somevalue', 12345) ->will($this->returnValue(true)); $this->assertTrue($this->cache->set('somekey', 'somevalue', 12345)); } public function testGet_PassesThroughToMemcached() { $this->memcached->expects($this->once()) ->method('get') ->with('somekey') ->will($this->returnValue('somevalue')); $this->assertEquals('somevalue', $this->cache->get('somekey')); } public function testDelete_PassesThroughToMemcached() { $this->memcached->expects($this->once()) ->method('delete') ->with('somekey') ->will($this->returnValue(true)); $this->assertTrue($this->cache->delete('somekey')); } }
{ "pile_set_name": "Github" }
/** * @file tpl_os_multicore_kernel.h * * @section descr File description * * Trampoline multicore kernel services header. * * @section copyright Copyright * * Trampoline RTOS * * Trampoline is copyright (c) CNRS, University of Nantes, Ecole Centrale de Nantes * Trampoline is protected by the French intellectual property law. * * This software is distributed under the GNU Public Licence V2. * Check the LICENSE file in the root directory of Trampoline * * @section infos File informations * * $Date$ * $Rev$ * $Author$ * $URL$ * */ #ifndef TPL_OS_MULTICORE_KERNEL_H #define TPL_OS_MULTICORE_KERNEL_H #include "tpl_os_multicore.h" #include "tpl_os_types.h" #if NUMBER_OF_CORES > 1 #define OS_START_SEC_VAR_8BITS #include "tpl_memmap.h" /** * The status of cores. The table is indexed by the core identifier * that ranges from 0 to NUMBER_OF_CORES - 1 */ extern VAR(CoreStatusType, OS_APPL_DATA) tpl_core_status[NUMBER_OF_CORES]; #define OS_STOP_SEC_VAR_8BITS #include "tpl_memmap.h" #define OS_START_SEC_VAR_16BITS #include "tpl_memmap.h" /** * tpl_start_count */ extern VAR(uint16, OS_APPL_DATA) tpl_start_count_0; extern VAR(uint16, OS_APPL_DATA) tpl_start_count_1; /** * tpl_number_of_activated_cores */ extern VAR(uint16, OS_APPL_DATA) tpl_number_of_activated_cores; #define OS_STOP_SEC_VAR_16BITS #include "tpl_memmap.h" #define OS_START_SEC_CODE #include "tpl_memmap.h" /** * tpl_get_core_id_service returns the identifier of the core. * * @retval The unique ID of the core running the caller. * * see paragraph 8.4.23 page 147 of * AUTOSAR Specification of Operating System V5.0.0 R4.0 Rev 3 */ FUNC(CoreIdType, OS_CODE) tpl_get_core_id_service(void); /** * tpl_start_core_service starts a processing core. * * @param core_id the core to start * @param status status returned by StartCore. * E_OK: No Error (standard & extended). * E_OS_ID: <core_id> is invalid (extended). * E_OS_ACCESS: The function was called after starting * the OS (extended). * E_OS_STATE: The core is already started (extended). * * see paragraph 8.4.24 page 147 of * AUTOSAR Specification of Operating System V5.0.0 R4.0 Rev 3 */ FUNC(void, OS_CODE) tpl_start_core_service( CONST(CoreIdType, AUTOMATIC) core_id, CONSTP2VAR(StatusType, AUTOMATIC, OS_APPL_DATA) status); /** * tpl_start_non_autosar_core_service starts a non AUTOSAR processing core. * * @param core_id the core to start * @param status status returned by StartCore. * E_OK: No Error (standard & extended). * E_OS_ID: <core_id> is invalid (extended). * E_OS_STATE: The core is already started (extended). * * see paragraph 8.4.25 page 148 of * AUTOSAR Specification of Operating System V5.0.0 R4.0 Rev 3 */ FUNC(void, OS_CODE) tpl_start_non_autosar_core_service( CONST(CoreIdType, AUTOMATIC) core_id, CONSTP2VAR(StatusType, AUTOMATIC, OS_APPL_DATA) status); /** * tpl_shutdown_all_cores_service shutdown all the running cores. * * @param error The shutdown error code. * * see paragraph 8.4.29 page 153 of * AUTOSAR Specification of Operating System V5.0.0 R4.0 Rev 3 */ FUNC(void, OS_CODE) tpl_shutdown_all_cores_service( CONST(StatusType, AUTOMATIC) error); /** * tpl_get_number_of_activated_cores_service returns the number * of activated cores. * * @retval The number of cores activated by the StartCore service. */ FUNC(uint32, OS_CODE) tpl_get_number_of_activated_cores_service(void); /** * tpl_get_core_status_service allows to get the status of a processing core. * * @param core_id The core of which the status is got. * @param core_status Core status returned by GetCoreStatus. * * @retval E_OK: No error, the core status was successfully written * in <core_status> (standard & extended). * E_OS_ID: <core_id> is invalid (extended). */ FUNC(StatusType, OS_CODE) tpl_get_core_status_service( CONST(CoreIdType, AUTOMATIC) core_id, CONSTP2VAR(CoreStatusType, AUTOMATIC, OS_APPL_DATA) status); /** * tpl_sync_barrier does a synchronization barrier * * @param enter_count the counter used to count the number of cores * @param lock the lock used to protect the critical section */ FUNC(void, OS_CODE) tpl_sync_barrier( CONSTP2VAR(uint16, AUTOMATIC, OS_VAR) enter_count, CONSTP2VAR(tpl_lock, AUTOMATIC, OS_VAR) lock); #define OS_STOP_SEC_CODE #include "tpl_memmap.h" #endif /* NUMBER_OF_CORES > 1 */ /* TPL_OS_MULTICORE_KERNEL_H */ #endif /* End of file tpl_os_multicore_kernel.h */
{ "pile_set_name": "Github" }
/***************************************************************************/ /* */ /* ftver.rc */ /* */ /* FreeType VERSIONINFO resource for Windows DLLs. */ /* */ /* Copyright (C) 2018-2019 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #include<windows.h> #define FT_VERSION 2,10,1,0 #define FT_VERSION_STR "2.10.1" VS_VERSION_INFO VERSIONINFO FILEVERSION FT_VERSION PRODUCTVERSION FT_VERSION FILEFLAGSMASK VS_FFI_FILEFLAGSMASK #ifdef _DEBUG FILEFLAGS VS_FF_DEBUG #endif #ifdef DLL_EXPORT FILETYPE VFT_DLL #define FT_FILENAME "freetype.dll" #else FILETYPE VFT_STATIC_LIB #define FT_FILENAME "freetype.lib" #endif BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904E4" BEGIN VALUE "CompanyName", "The FreeType Project" VALUE "FileDescription", "Font Rendering Library" VALUE "FileVersion", FT_VERSION_STR VALUE "ProductName", "FreeType" VALUE "ProductVersion", FT_VERSION_STR VALUE "LegalCopyright", "\251 2018-2019 The FreeType Project www.freetype.org. All rights reserved." VALUE "InternalName", "freetype" VALUE "OriginalFilename", FT_FILENAME END END BLOCK "VarFileInfo" BEGIN /* The following line should only be modified for localized versions. */ /* It consists of any number of WORD,WORD pairs, with each pair */ /* describing a "language,codepage" combination supported by the file. */ VALUE "Translation", 0x409, 1252 END END
{ "pile_set_name": "Github" }
%% -*- coding: utf-8 -*- {" has set the subject to: "," ตั้งหัวข้อว่า: "}. {"Access denied by service policy","การเข้าถึงถูกปฏิเสธโดยนโยบายการบริการ"}. {"Action on user","การดำเนินการกับผู้ใช้"}. {"Add Jabber ID","เพิ่ม Jabber ID"}. {"Add New","เพิ่มผู้ใช้ใหม่"}. {"Add User","เพิ่มผู้ใช้"}. {"Administration of ","การดูแล "}. {"Administration","การดูแล"}. {"Administrator privileges required","ต้องมีสิทธิพิเศษของผู้ดูแลระบบ"}. {"All activity","กิจกรรมทั้งหมด"}. {"All Users","ผู้ใช้ทั้งหมด"}. {"Allow users to query other users","อนุญาตให้ผู้ใช้ถามคำถามกับผู้ใช้คนอื่นๆ ได้"}. {"Allow users to send invites","อนุญาตให้ผู้ใช้ส่งคำเชิญถึงกันได้"}. {"Allow users to send private messages","อนุญาตให้ผู้ใช้ส่งข้อความส่วนตัว"}. {"Announcements","ประกาศ"}. {"April","เมษายน"}. {"August","สิงหาคม"}. {"Backup Management","การจัดการข้อมูลสำรอง"}. {"Backup to File at ","สำรองไฟล์ข้อมูลที่"}. {"Backup","การสำรองข้อมูล "}. {"Bad format","รูปแบบที่ไม่ถูกต้อง"}. {"Birthday","วันเกิด"}. {"Change Password","เปลี่ยนรหัสผ่าน"}. {"Change User Password","เปลี่ยนรหัสผ่านของผู้ใช้"}. {"Chatroom configuration modified","มีการปรับเปลี่ยนการกำหนดค่าของห้องสนทนา"}. {"Chatrooms","ห้องสนทนา"}. {"Choose a username and password to register with this server","เลือกชื่อผู้ใช้และรหัสผ่านเพื่อลงทะเบียนกับเซิร์ฟเวอร์นี้"}. {"Choose storage type of tables","เลือกชนิดการจัดเก็บของตาราง"}. {"Choose whether to approve this entity's subscription.","เลือกว่าจะอนุมัติการสมัครเข้าใช้งานของเอนทิตี้นี้หรือไม่"}. {"City","เมือง"}. {"Commands","คำสั่ง"}. {"Conference room does not exist","ไม่มีห้องประชุม"}. {"Configuration","การกำหนดค่า"}. {"Connected Resources:","ทรัพยากรที่เชื่อมต่อ:"}. {"Country","ประเทศ"}. {"CPU Time:","เวลาการทำงานของ CPU:"}. {"Database Tables Configuration at ","การกำหนดค่าตารางฐานข้อมูลที่"}. {"Database","ฐานข้อมูล"}. {"December","ธันวาคม"}. {"Default users as participants","ผู้ใช้เริ่มต้นเป็นผู้เข้าร่วม"}. {"Delete message of the day on all hosts","ลบข้อความของวันบนโฮสต์ทั้งหมด"}. {"Delete message of the day","ลบข้อความของวัน"}. {"Delete Selected","ลบข้อความที่เลือก"}. {"Delete User","ลบผู้ใช้"}. {"Description:","รายละเอียด:"}. {"Disc only copy","คัดลอกเฉพาะดิสก์"}. {"Displayed Groups:","กลุ่มที่แสดง:"}. {"Dump Backup to Text File at ","ถ่ายโอนการสำรองข้อมูลไปยังไฟล์ข้อความที่"}. {"Dump to Text File","ถ่ายโอนข้อมูลไปยังไฟล์ข้อความ"}. {"Edit Properties","แก้ไขคุณสมบัติ"}. {"ejabberd MUC module","ejabberd MUC module"}. {"ejabberd Publish-Subscribe module","ejabberd Publish-Subscribe module"}. {"ejabberd SOCKS5 Bytestreams module","ejabberd SOCKS5 Bytestreams module"}. {"ejabberd vCard module","ejabberd vCard module"}. {"Email","อีเมล"}. {"Enable logging","เปิดใช้งานการบันทึก"}. {"End User Session","สิ้นสุดเซสชันของผู้ใช้"}. {"Enter nickname you want to register","ป้อนชื่อเล่นที่คุณต้องการลงทะเบียน"}. {"Enter path to backup file","ป้อนพาธเพื่อสำรองไฟล์ข้อมูล"}. {"Enter path to jabberd14 spool dir","ป้อนพาธไปยัง jabberd14 spool dir"}. {"Enter path to jabberd14 spool file","ป้อนพาธไปยังไฟล์เก็บพักข้อมูล jabberd14"}. {"Enter path to text file","ป้อนพาธของไฟล์ข้อความ"}. {"Erlang Jabber Server","Erlang Jabber Server"}. {"Family Name","นามสกุล"}. {"February","กุมภาพันธ์"}. {"Friday","วันศุกร์"}. {"From","จาก"}. {"Full Name","ชื่อเต็ม"}. {"Get Number of Online Users","แสดงจำนวนผู้ใช้ออนไลน์"}. {"Get Number of Registered Users","แสดงจำนวนผู้ใช้ที่ลงทะเบียน"}. {"Get User Last Login Time","แสดงเวลาเข้าสู่ระบบครั้งล่าสุดของผู้ใช้"}. {"Get User Password","ขอรับรหัสผ่านของผู้ใช้"}. {"Get User Statistics","แสดงสถิติของผู้ใช้"}. {"Group ","กลุ่ม"}. {"Groups","กลุ่ม"}. {"has been banned","ถูกสั่งห้าม"}. {"has been kicked","ถูกไล่ออก"}. {"Host","โฮสต์"}. {"Import Directory","อิมพอร์ตไดเร็กทอรี"}. {"Import File","อิมพอร์ตไฟล์"}. {"Import User from File at ","อิมพอร์ตผู้ใช้จากไฟล์ที่"}. {"Import Users from Dir at ","อิมพอร์ตผู้ใช้จาก Dir ที่"}. {"Import Users From jabberd14 Spool Files","อิมพอร์ตผู้ใช้จากไฟล์เก็บพักข้อมูล jabberd14"}. {"Improper message type","ประเภทข้อความไม่เหมาะสม"}. {"Incorrect password","รหัสผ่านไม่ถูกต้อง"}. {"IP addresses","ที่อยู่ IP"}. {"is now known as","ซึ่งรู้จักกันในชื่อ"}. {"It is not allowed to send private messages of type \"groupchat\"","ไม่อนุญาตให้ส่งข้อความส่วนตัวไปยัง \"กลุ่มสนทนา\""}. {"It is not allowed to send private messages to the conference","ไม่อนุญาตให้ส่งข้อความส่วนตัวไปยังห้องประชุม"}. {"Jabber ID","Jabber ID"}. {"January","มกราคม"}. {"joins the room","เข้าห้องสนทนานี้"}. {"July","กรกฎาคม"}. {"June","มิถุนายน"}. {"Last Activity","กิจกรรมล่าสุด"}. {"Last login","การเข้าสู่ระบบครั้งล่าสุด"}. {"Last month","เดือนที่แล้ว"}. {"Last year","ปีที่แล้ว"}. {"leaves the room","ออกจากห้อง"}. {"Low level update script","อัพเดตสคริปต์ระดับต่ำ"}. {"Make participants list public","สร้างรายการผู้เข้าร่วมสำหรับใช้งานโดยบุคคลทั่วไป"}. {"Make room members-only","สร้างห้องสำหรับสมาชิกเท่านั้น"}. {"Make room password protected","สร้างห้องที่มีการป้องกันด้วยรหัสผ่าน"}. {"Make room persistent","สร้างเป็นห้องถาวร"}. {"Make room public searchable","สร้างเป็นห้องที่บุคคลทั่วไปสามารถค้นหาได้"}. {"March","มีนาคม"}. {"Maximum Number of Occupants","จำนวนผู้ครอบครองห้องสูงสุด"}. {"May","พฤษภาคม"}. {"Members:","สมาชิก:"}. {"Memory","หน่วยความจำ"}. {"Message body","เนื้อหาของข้อความ"}. {"Middle Name","ชื่อกลาง"}. {"Moderator privileges required","ต้องมีสิทธิพิเศษของผู้ดูแลการสนทนา"}. {"Monday","วันจันทร์"}. {"Name","ชื่อ"}. {"Name:","ชื่อ:"}. {"Never","ไม่เคย"}. {"Nickname Registration at ","การลงทะเบียนชื่อเล่นที่ "}. {"Nickname","ชื่อเล่น"}. {"No body provided for announce message","ไม่ได้ป้อนเนื้อหาสำหรับข้อความที่ประกาศ"}. {"No Data","ไม่มีข้อมูล"}. {"No limit","ไม่จำกัด"}. {"Node not found","ไม่พบโหนด"}. {"Nodes","โหนด"}. {"None","ไม่มี"}. {"November","พฤศจิกายน"}. {"Number of online users","จำนวนผู้ใช้ออนไลน์"}. {"Number of registered users","จำนวนผู้ใช้ที่ลงทะเบียน"}. {"October","ตุลาคม"}. {"Offline Messages","ข้อความออฟไลน์"}. {"Offline Messages:","ข้อความออฟไลน์:"}. {"OK","ตกลง"}. {"Online Users","ผู้ใช้ออนไลน์"}. {"Online Users:","ผู้ใช้ออนไลน์:"}. {"Online","ออนไลน์"}. {"Only occupants are allowed to send messages to the conference","ผู้ครอบครองห้องเท่านั้นที่ได้รับอนุญาตให้ส่งข้อความไปยังห้องประชุม"}. {"Only occupants are allowed to send queries to the conference","ผู้ครอบครองห้องเท่านั้นที่ได้รับอนุญาตให้ส่งกระทู้ถามไปยังห้องประชุม"}. {"Only service administrators are allowed to send service messages","ผู้ดูแลด้านการบริการเท่านั้นที่ได้รับอนุญาตให้ส่งข้อความการบริการ"}. {"Organization Name","ชื่อองค์กร"}. {"Organization Unit","หน่วยขององค์กร"}. {"Outgoing s2s Connections","การเชื่อมต่อ s2s ขาออก"}. {"Outgoing s2s Connections:","การเชื่อมต่อ s2s ขาออก:"}. {"Owner privileges required","ต้องมีสิทธิพิเศษของเจ้าของ"}. {"Packet","แพ็กเก็ต"}. {"Password Verification","การตรวจสอบรหัสผ่าน"}. {"Password","รหัสผ่าน"}. {"Password:","รหัสผ่าน:"}. {"Path to Dir","พาธไปยัง Dir"}. {"Path to File","พาธของไฟล์ข้อมูล"}. {"Pending","ค้างอยู่"}. {"Period: ","ระยะเวลา:"}. {"Ping","Ping"}. {"Pong","Pong"}. {"private, ","ส่วนตัว, "}. {"Publish-Subscribe","เผยแพร่-สมัครเข้าใช้งาน"}. {"PubSub subscriber request","คำร้องขอของผู้สมัครเข้าใช้งาน PubSub"}. {"Queries to the conference members are not allowed in this room","ห้องนี้ไม่อนุญาตให้ส่งกระทู้ถามถึงสมาชิกในห้องประชุม"}. {"RAM and disc copy","คัดลอก RAM และดิสก์"}. {"RAM copy","คัดลอก RAM"}. {"Really delete message of the day?","แน่ใจว่าต้องการลบข้อความของวันหรือไม่"}. {"Recipient is not in the conference room","ผู้รับไม่ได้อยู่ในห้องประชุม"}. {"Registered Users","ผู้ใช้ที่ลงทะเบียน"}. {"Registered Users:","ผู้ใช้ที่ลงทะเบียน:"}. {"Remote copy","คัดลอกระยะไกล"}. {"Remove User","ลบผู้ใช้"}. {"Remove","ลบ"}. {"Replaced by new connection","แทนที่ด้วยการเชื่อมต่อใหม่"}. {"Resources","ทรัพยากร"}. {"Restart Service","เริ่มต้นการบริการใหม่อีกครั้ง"}. {"Restart","เริ่มต้นใหม่"}. {"Restore Backup from File at ","คืนค่าการสำรองข้อมูลจากไฟล์ที่"}. {"Restore binary backup after next ejabberd restart (requires less memory):","คืนค่าข้อมูลสำรองแบบไบนารีหลังจากที่ ejabberd ถัดไปเริ่มการทำงานใหม่ (ใช้หน่วยความจำน้อยลง):"}. {"Restore binary backup immediately:","คืนค่าข้อมูลสำรองแบบไบนารีโดยทันที:"}. {"Restore plain text backup immediately:","คืนค่าข้อมูลสำรองที่เป็นข้อความธรรมดาโดยทันที:"}. {"Restore","การคืนค่า"}. {"Room Configuration","การกำหนดค่าห้องสนทนา"}. {"Room creation is denied by service policy","การสร้างห้องสนทนาถูกปฏิเสธโดยนโยบายการบริการ"}. {"Room title","ชื่อห้อง"}. {"Roster size","ขนาดของบัญชีรายชื่อ"}. {"Roster","บัญชีรายชื่อ"}. {"RPC Call Error","ข้อผิดพลาดจากการเรียกใช้ RPC"}. {"Running Nodes","โหนดที่ทำงาน"}. {"Saturday","วันเสาร์"}. {"Script check","ตรวจสอบคริปต์"}. {"Search Results for ","ผลการค้นหาสำหรับ "}. {"Search users in ","ค้นหาผู้ใช้ใน "}. {"Send announcement to all online users on all hosts","ส่งประกาศถึงผู้ใช้ออนไลน์ทั้งหมดบนโฮสต์ทั้งหมด"}. {"Send announcement to all online users","ส่งประกาศถึงผู้ใช้ออนไลน์ทั้งหมด"}. {"Send announcement to all users on all hosts","ส่งประกาศถึงผู้ใช้ทั้งหมดบนโฮสต์ทั้งหมด"}. {"Send announcement to all users","ส่งประกาศถึงผู้ใช้ทั้งหมด"}. {"September","กันยายน"}. {"Set message of the day and send to online users","ตั้งค่าข้อความของวันและส่งถึงผู้ใช้ออนไลน์"}. {"Set message of the day on all hosts and send to online users","ตั้งค่าข้อความของวันบนโฮสต์ทั้งหมดและส่งถึงผู้ใช้ออนไลน์"}. {"Shared Roster Groups","กลุ่มบัญชีรายชื่อที่ใช้งานร่วมกัน"}. {"Show Integral Table","แสดงตารางรวม"}. {"Show Ordinary Table","แสดงตารางทั่วไป"}. {"Shut Down Service","ปิดการบริการ"}. {"Statistics of ~p","สถิติของ ~p"}. {"Statistics","สถิติ"}. {"Stopped Nodes","โหนดที่หยุด"}. {"Stop","หยุด"}. {"Storage Type","ชนิดที่เก็บข้อมูล"}. {"Store binary backup:","จัดเก็บข้อมูลสำรองแบบไบนารี:"}. {"Store plain text backup:","จัดเก็บข้อมูลสำรองที่เป็นข้อความธรรมดา:"}. {"Subject","หัวเรื่อง"}. {"Submitted","ส่งแล้ว"}. {"Submit","ส่ง"}. {"Subscription","การสมัครสมาชิก"}. {"Sunday","วันอาทิตย์"}. {"the password is","รหัสผ่านคือ"}. {"This room is not anonymous","ห้องนี้ไม่ปิดบังชื่อ"}. {"Thursday","วันพฤหัสบดี"}. {"Time delay","การหน่วงเวลา"}. {"Time","เวลา"}. {"To","ถึง"}. {"Traffic rate limit is exceeded","อัตราของปริมาณการเข้าใช้เกินขีดจำกัด"}. {"Transactions Aborted:","ทรานแซกชันที่ถูกยกเลิก:"}. {"Transactions Committed:","ทรานแซกชันที่ได้รับมอบหมาย:"}. {"Transactions Logged:","ทรานแซกชันที่บันทึก:"}. {"Transactions Restarted:","ทรานแซกชันที่เริ่มทำงานใหม่อีกครั้ง:"}. {"Tuesday","วันอังคาร"}. {"Update message of the day (don't send)","อัพเดตข้อความของวัน (ไม่ต้องส่ง)"}. {"Update message of the day on all hosts (don't send)","อัพเดตข้อความของวันบนโฮสต์ทั้งหมด (ไม่ต้องส่ง) "}. {"Update plan","แผนการอัพเดต"}. {"Update script","อัพเดตสคริปต์"}. {"Update","อัพเดต"}. {"Uptime:","เวลาการทำงานต่อเนื่อง:"}. {"User Management","การจัดการผู้ใช้"}. {"Users Last Activity","กิจกรรมล่าสุดของผู้ใช้"}. {"Users","ผู้ใช้"}. {"User","ผู้ใช้"}. {"Validate","ตรวจสอบ"}. {"vCard User Search","ค้นหาผู้ใช้ vCard "}. {"Virtual Hosts","โฮสต์เสมือน"}. {"Visitors are not allowed to send messages to all occupants","ผู้เยี่ยมเยือนไม่ได้รับอนุญาตให้ส่งข้อความถึงผู้ครอบครองห้องทั้งหมด"}. {"Wednesday","วันพุธ"}. {"You have been banned from this room","คุณถูกสั่งห้ามไมให้เข้าห้องนี้"}. {"You must fill in field \"Nickname\" in the form","คุณต้องกรอกฟิลด์ \"Nickname\" ในแบบฟอร์ม"}. {"You need an x:data capable client to search","คุณต้องใช้ไคลเอ็นต์ที่รองรับ x:data เพื่อค้นหา"}. {"Your contact offline message queue is full. The message has been discarded.","ลำดับข้อความออฟไลน์ของผู้ที่ติดต่อของคุณเต็มแล้ว ข้อความถูกลบทิ้งแล้ว"}.
{ "pile_set_name": "Github" }
/* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package validation import ( "strings" "testing" "k8s.io/apimachinery/pkg/util/validation/field" ) func TestValidateLabels(t *testing.T) { successCases := []map[string]string{ {"simple": "bar"}, {"now-with-dashes": "bar"}, {"1-starts-with-num": "bar"}, {"1234": "bar"}, {"simple/simple": "bar"}, {"now-with-dashes/simple": "bar"}, {"now-with-dashes/now-with-dashes": "bar"}, {"now.with.dots/simple": "bar"}, {"now-with.dashes-and.dots/simple": "bar"}, {"1-num.2-num/3-num": "bar"}, {"1234/5678": "bar"}, {"1.2.3.4/5678": "bar"}, {"UpperCaseAreOK123": "bar"}, {"goodvalue": "123_-.BaR"}, } for i := range successCases { errs := ValidateLabels(successCases[i], field.NewPath("field")) if len(errs) != 0 { t.Errorf("case[%d] expected success, got %#v", i, errs) } } namePartErrMsg := "name part must consist of" nameErrMsg := "a qualified name must consist of" labelErrMsg := "a valid label must be an empty string or consist of" maxLengthErrMsg := "must be no more than" labelNameErrorCases := []struct { labels map[string]string expect string }{ {map[string]string{"nospecialchars^=@": "bar"}, namePartErrMsg}, {map[string]string{"cantendwithadash-": "bar"}, namePartErrMsg}, {map[string]string{"only/one/slash": "bar"}, nameErrMsg}, {map[string]string{strings.Repeat("a", 254): "bar"}, maxLengthErrMsg}, } for i := range labelNameErrorCases { errs := ValidateLabels(labelNameErrorCases[i].labels, field.NewPath("field")) if len(errs) != 1 { t.Errorf("case[%d]: expected failure", i) } else { if !strings.Contains(errs[0].Detail, labelNameErrorCases[i].expect) { t.Errorf("case[%d]: error details do not include %q: %q", i, labelNameErrorCases[i].expect, errs[0].Detail) } } } labelValueErrorCases := []struct { labels map[string]string expect string }{ {map[string]string{"toolongvalue": strings.Repeat("a", 64)}, maxLengthErrMsg}, {map[string]string{"backslashesinvalue": "some\\bad\\value"}, labelErrMsg}, {map[string]string{"nocommasallowed": "bad,value"}, labelErrMsg}, {map[string]string{"strangecharsinvalue": "?#$notsogood"}, labelErrMsg}, } for i := range labelValueErrorCases { errs := ValidateLabels(labelValueErrorCases[i].labels, field.NewPath("field")) if len(errs) != 1 { t.Errorf("case[%d]: expected failure", i) } else { if !strings.Contains(errs[0].Detail, labelValueErrorCases[i].expect) { t.Errorf("case[%d]: error details do not include %q: %q", i, labelValueErrorCases[i].expect, errs[0].Detail) } } } }
{ "pile_set_name": "Github" }
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to [email protected] so we can send you a copy immediately. * * @category Zend * @package Zend_Validate_File * @subpackage UnitTests * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ // Call Zend_Validate_File_MimeTypeTest::main() if this source file is executed directly. if (!defined("PHPUnit_MAIN_METHOD")) { define("PHPUnit_MAIN_METHOD", "Zend_Validate_File_IsCompressedTest::main"); } /** * @see Zend_Validate_File_IsCompressed */ require_once 'Zend/Validate/File/IsCompressed.php'; /** * IsCompressed testbed * * @category Zend * @package Zend_Validate_File * @subpackage UnitTests * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Validate */ class Zend_Validate_File_IsCompressedTest extends PHPUnit_Framework_TestCase { /** * Runs the test methods of this class. * * @return void */ public static function main() { $suite = new PHPUnit_Framework_TestSuite("Zend_Validate_File_IsCompressedTest"); $result = PHPUnit_TextUI_TestRunner::run($suite); } /** * Ensures that the validator follows expected behavior * * @return void */ public function testBasic() { if (!extension_loaded('fileinfo') && function_exists('mime_content_type') && ini_get('mime_magic.magicfile') && (mime_content_type(dirname(__FILE__) . '/_files/test.zip') == 'text/plain') ) { $this->markTestSkipped('This PHP Version has no finfo, has mime_content_type, ' . ' but mime_content_type exhibits buggy behavior on this system.' ); } // Prevent error in the next check if (!function_exists('mime_content_type')) { $this->markTestSkipped('mime_content_type function is not available.'); } // Sometimes mime_content_type() gives application/zip and sometimes // application/x-zip ... $expectedMimeType = mime_content_type(dirname(__FILE__) . '/_files/test.zip'); if (!in_array($expectedMimeType, array('application/zip', 'application/x-zip'))) { $this->markTestSkipped('mime_content_type exhibits buggy behavior on this system!'); } $valuesExpected = array( array(null, true), array('zip', true), array('test/notype', false), array('application/x-zip, application/zip, application/x-tar', true), array(array('application/x-zip', 'application/zip', 'application/x-tar'), true), array(array('zip', 'tar'), true), array(array('tar', 'arj'), false), ); $files = array( 'name' => 'test.zip', 'type' => $expectedMimeType, 'size' => 200, 'tmp_name' => dirname(__FILE__) . '/_files/test.zip', 'error' => 0 ); foreach ($valuesExpected as $element) { $validator = new Zend_Validate_File_IsCompressed($element[0]); $validator->enableHeaderCheck(); $this->assertEquals( $element[1], $validator->isValid(dirname(__FILE__) . '/_files/test.zip', $files), "Tested with " . var_export($element, 1) ); } } /** * Ensures that getMimeType() returns expected value * * @return void */ public function testGetMimeType() { $validator = new Zend_Validate_File_IsCompressed('image/gif'); $this->assertEquals('image/gif', $validator->getMimeType()); $validator = new Zend_Validate_File_IsCompressed(array('image/gif', 'video', 'text/test')); $this->assertEquals('image/gif,video,text/test', $validator->getMimeType()); $validator = new Zend_Validate_File_IsCompressed(array('image/gif', 'video', 'text/test')); $this->assertEquals(array('image/gif', 'video', 'text/test'), $validator->getMimeType(true)); } /** * Ensures that setMimeType() returns expected value * * @return void */ public function testSetMimeType() { $validator = new Zend_Validate_File_IsCompressed('image/gif'); $validator->setMimeType('image/jpeg'); $this->assertEquals('image/jpeg', $validator->getMimeType()); $this->assertEquals(array('image/jpeg'), $validator->getMimeType(true)); $validator->setMimeType('image/gif, text/test'); $this->assertEquals('image/gif,text/test', $validator->getMimeType()); $this->assertEquals(array('image/gif', 'text/test'), $validator->getMimeType(true)); $validator->setMimeType(array('video/mpeg', 'gif')); $this->assertEquals('video/mpeg,gif', $validator->getMimeType()); $this->assertEquals(array('video/mpeg', 'gif'), $validator->getMimeType(true)); } /** * Ensures that addMimeType() returns expected value * * @return void */ public function testAddMimeType() { $validator = new Zend_Validate_File_IsCompressed('image/gif'); $validator->addMimeType('text'); $this->assertEquals('image/gif,text', $validator->getMimeType()); $this->assertEquals(array('image/gif', 'text'), $validator->getMimeType(true)); $validator->addMimeType('jpg, to'); $this->assertEquals('image/gif,text,jpg,to', $validator->getMimeType()); $this->assertEquals(array('image/gif', 'text', 'jpg', 'to'), $validator->getMimeType(true)); $validator->addMimeType(array('zip', 'ti')); $this->assertEquals('image/gif,text,jpg,to,zip,ti', $validator->getMimeType()); $this->assertEquals(array('image/gif', 'text', 'jpg', 'to', 'zip', 'ti'), $validator->getMimeType(true)); $validator->addMimeType(''); $this->assertEquals('image/gif,text,jpg,to,zip,ti', $validator->getMimeType()); $this->assertEquals(array('image/gif', 'text', 'jpg', 'to', 'zip', 'ti'), $validator->getMimeType(true)); } /** * @ZF-8111 */ public function testErrorMessages() { $files = array( 'name' => 'picture.jpg', 'type' => 'image/jpeg', 'size' => 200, 'tmp_name' => dirname(__FILE__) . '/_files/picture.jpg', 'error' => 0 ); $validator = new Zend_Validate_File_IsCompressed('test/notype'); $validator->enableHeaderCheck(); $this->assertFalse($validator->isValid(dirname(__FILE__) . '/_files/picture.jpg', $files)); $error = $validator->getMessages(); $this->assertTrue(array_key_exists('fileIsCompressedFalseType', $error)); } public function testOptionsAtConstructor() { if (!extension_loaded('fileinfo')) { $this->markTestSkipped('This PHP Version has no finfo installed'); } if (version_compare(PHP_VERSION, '5.3', '>=')) { $magicFile = dirname(__FILE__) . '/_files/magic-php53.mime'; } else { $magicFile = dirname(__FILE__) . '/_files/magic.mime'; } $validator = new Zend_Validate_File_IsCompressed(array( 'image/gif', 'image/jpg', 'magicfile' => $magicFile, 'headerCheck' => true)); $this->assertEquals($magicFile, $validator->getMagicFile()); $this->assertTrue($validator->getHeaderCheck()); $this->assertEquals('image/gif,image/jpg', $validator->getMimeType()); } } // Call Zend_Validate_File_MimeTypeTest::main() if this source file is executed directly. if (PHPUnit_MAIN_METHOD == "Zend_Validate_File_IsCompressedTest::main") { Zend_Validate_File_IsCompressedTest::main(); }
{ "pile_set_name": "Github" }
require('./angular-locale_teo'); module.exports = 'ngLocale';
{ "pile_set_name": "Github" }
const Parse = require("./Parse").Parse exports.default = { "opts.string": [ { name: "with short options", argv: ["-a001", "-b001", "-c", ".5", "-d", ".5", "-x-1"], opts: { string: ["a", "c", "x"] }, expected: { _: [], a: "001", b: 1, c: ".5", d: 0.5, x: "-1" } }, { name: "with clustered short options (string)", argv: ["-abc", "foo"], opts: { string: ["b"] }, expected: { _: ["foo"], a: true, b: "c" } }, { name: "with clustered short options with implicit value (string)", argv: ["-abc001", "foo"], opts: { string: ["b"] }, expected: { _: ["foo"], a: true, b: "c001" } }, { name: "with long options", argv: ["--foo=001", "--bar=001", "--baz", ".5", "--fum"], opts: { string: ["foo", "baz", "fum"] }, expected: { _: [], foo: "001", bar: 1, baz: ".5", fum: "" } }, { name: "with repeating options", argv: ["-ab", "-ax", "--foo=0101", "--foo=0011"], opts: { string: ["a", "foo"] }, expected: { _: [], a: ["b", "x"], foo: ["0101", "0011"] } }, { name: "with mixed string/non-string short options", argv: ["-Aa", "-Bb05", "-Cc", "010", "-d"], opts: { string: ["a", "b", "c", "d"] }, expected: { _: [], A: true, a: "", B: true, b: "05", C: true, c: "010", d: "" } }, { name: "have a default value when not in argv", argv: [], opts: { string: ["foo", "bar"] }, expected: { _: [], foo: "", bar: "" } }, { name: "with aliases", argv: ["--foo", "01", "-b", "02"], opts: { string: ["f", "b"], alias: { foo: "f", bar: "b" } }, expected: { _: [], f: "01", foo: "01", b: "02", bar: "02" } }, { name: "explicit 'false' is not cast to boolean", argv: ["-afalse", "--foo=false"], opts: { string: ["a", "foo"] }, expected: { _: [], a: "false", foo: "false" } } ].map(Parse) }
{ "pile_set_name": "Github" }
# frozen_string_literal: true class CreateRoles < ActiveRecord::Migration[5.1] def change create_table :roles do |t| t.string :name, null: false t.text :permissions t.string :type, null: false t.timestamps end end end
{ "pile_set_name": "Github" }
/* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package v1 import ( api "k8s.io/client-go/1.5/pkg/api" v1 "k8s.io/client-go/1.5/pkg/api/v1" watch "k8s.io/client-go/1.5/pkg/watch" ) // ServiceAccountsGetter has a method to return a ServiceAccountInterface. // A group's client should implement this interface. type ServiceAccountsGetter interface { ServiceAccounts(namespace string) ServiceAccountInterface } // ServiceAccountInterface has methods to work with ServiceAccount resources. type ServiceAccountInterface interface { Create(*v1.ServiceAccount) (*v1.ServiceAccount, error) Update(*v1.ServiceAccount) (*v1.ServiceAccount, error) Delete(name string, options *api.DeleteOptions) error DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error Get(name string) (*v1.ServiceAccount, error) List(opts api.ListOptions) (*v1.ServiceAccountList, error) Watch(opts api.ListOptions) (watch.Interface, error) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *v1.ServiceAccount, err error) ServiceAccountExpansion } // serviceAccounts implements ServiceAccountInterface type serviceAccounts struct { client *CoreClient ns string } // newServiceAccounts returns a ServiceAccounts func newServiceAccounts(c *CoreClient, namespace string) *serviceAccounts { return &serviceAccounts{ client: c, ns: namespace, } } // Create takes the representation of a serviceAccount and creates it. Returns the server's representation of the serviceAccount, and an error, if there is any. func (c *serviceAccounts) Create(serviceAccount *v1.ServiceAccount) (result *v1.ServiceAccount, err error) { result = &v1.ServiceAccount{} err = c.client.Post(). Namespace(c.ns). Resource("serviceaccounts"). Body(serviceAccount). Do(). Into(result) return } // Update takes the representation of a serviceAccount and updates it. Returns the server's representation of the serviceAccount, and an error, if there is any. func (c *serviceAccounts) Update(serviceAccount *v1.ServiceAccount) (result *v1.ServiceAccount, err error) { result = &v1.ServiceAccount{} err = c.client.Put(). Namespace(c.ns). Resource("serviceaccounts"). Name(serviceAccount.Name). Body(serviceAccount). Do(). Into(result) return } // Delete takes name of the serviceAccount and deletes it. Returns an error if one occurs. func (c *serviceAccounts) Delete(name string, options *api.DeleteOptions) error { return c.client.Delete(). Namespace(c.ns). Resource("serviceaccounts"). Name(name). Body(options). Do(). Error() } // DeleteCollection deletes a collection of objects. func (c *serviceAccounts) DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error { return c.client.Delete(). Namespace(c.ns). Resource("serviceaccounts"). VersionedParams(&listOptions, api.ParameterCodec). Body(options). Do(). Error() } // Get takes name of the serviceAccount, and returns the corresponding serviceAccount object, and an error if there is any. func (c *serviceAccounts) Get(name string) (result *v1.ServiceAccount, err error) { result = &v1.ServiceAccount{} err = c.client.Get(). Namespace(c.ns). Resource("serviceaccounts"). Name(name). Do(). Into(result) return } // List takes label and field selectors, and returns the list of ServiceAccounts that match those selectors. func (c *serviceAccounts) List(opts api.ListOptions) (result *v1.ServiceAccountList, err error) { result = &v1.ServiceAccountList{} err = c.client.Get(). Namespace(c.ns). Resource("serviceaccounts"). VersionedParams(&opts, api.ParameterCodec). Do(). Into(result) return } // Watch returns a watch.Interface that watches the requested serviceAccounts. func (c *serviceAccounts) Watch(opts api.ListOptions) (watch.Interface, error) { return c.client.Get(). Prefix("watch"). Namespace(c.ns). Resource("serviceaccounts"). VersionedParams(&opts, api.ParameterCodec). Watch() } // Patch applies the patch and returns the patched serviceAccount. func (c *serviceAccounts) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *v1.ServiceAccount, err error) { result = &v1.ServiceAccount{} err = c.client.Patch(pt). Namespace(c.ns). Resource("serviceaccounts"). SubResource(subresources...). Name(name). Body(data). Do(). Into(result) return }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!-- Generated with glade 3.22.1 --> <interface domain="sc"> <requires lib="gtk+" version="3.18"/> <object class="GtkEntry" id="entry"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="hexpand">True</property> <property name="vexpand">False</property> <property name="activates_default">True</property> <property name="width_chars">32</property> </object> <object class="GtkLabel" id="label"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="halign">end</property> <property name="use_underline">True</property> <property name="mnemonic_widget">entry</property> <property name="xalign">0</property> </object> </interface>
{ "pile_set_name": "Github" }
scan = (string, pattern, callback) -> result = "" while string.length > 0 match = string.match pattern if match result += string.slice 0, match.index result += callback match string = string.slice(match.index + match[0].length) else result += string string = "" result exports.split = (line = "") -> words = [] field = "" scan line, /// \s* # Leading whitespace (?: # ([^\s\\\'\"]+) # Normal words | # '((?:[^\'\\]|\\.)*)' # Stuff in single quotes | # "((?:[^\"\\]|\\.)*)" # Stuff in double quotes | # (\\.?) # Escaped character | # (\S) # Garbage ) # (\s|$)? # Seperator ///, (match) -> [raw, word, sq, dq, escape, garbage, seperator] = match throw new Error "Unmatched quote" if garbage? field += (word or (sq or dq or escape).replace(/\\(?=.)/, "")) if seperator? words.push field field = "" words.push field if field words exports.escape = (str = "") -> return "''" unless str? str.replace(/([^A-Za-z0-9_\-.,:\/@\n])/g, "\\$1").replace(/\n/g, "'\n'")
{ "pile_set_name": "Github" }
#!/bin/sh export LD_LIBRARY_PATH="$(pwd):${LD_LIBRARY_PATH}" exec ./shcl "$@"
{ "pile_set_name": "Github" }
<?xml version="1.0"?> <doc> <assembly> <name>GalaSoft.MvvmLight.Win8</name> </assembly> <members> <member name="T:GalaSoft.MvvmLight.Command.RelayCommand"> <summary> A command whose sole purpose is to relay its functionality to other objects by invoking delegates. The default return value for the CanExecute method is 'true'. This class does not allow you to accept command parameters in the Execute and CanExecute callback methods. </summary> </member> <member name="M:GalaSoft.MvvmLight.Command.RelayCommand.#ctor(System.Action)"> <summary> Initializes a new instance of the RelayCommand class that can always execute. </summary> <param name="execute">The execution logic.</param> <exception cref="T:System.ArgumentNullException">If the execute argument is null.</exception> </member> <member name="M:GalaSoft.MvvmLight.Command.RelayCommand.#ctor(System.Action,System.Func{System.Boolean})"> <summary> Initializes a new instance of the RelayCommand class. </summary> <param name="execute">The execution logic.</param> <param name="canExecute">The execution status logic.</param> <exception cref="T:System.ArgumentNullException">If the execute argument is null.</exception> </member> <member name="M:GalaSoft.MvvmLight.Command.RelayCommand.RaiseCanExecuteChanged"> <summary> Raises the <see cref="E:GalaSoft.MvvmLight.Command.RelayCommand.CanExecuteChanged"/> event. </summary> </member> <member name="M:GalaSoft.MvvmLight.Command.RelayCommand.CanExecute(System.Object)"> <summary> Defines the method that determines whether the command can execute in its current state. </summary> <param name="parameter">This parameter will always be ignored.</param> <returns>true if this command can be executed; otherwise, false.</returns> </member> <member name="M:GalaSoft.MvvmLight.Command.RelayCommand.Execute(System.Object)"> <summary> Defines the method to be called when the command is invoked. </summary> <param name="parameter">This parameter will always be ignored.</param> </member> <member name="E:GalaSoft.MvvmLight.Command.RelayCommand.CanExecuteChanged"> <summary> Occurs when changes occur that affect whether the command should execute. </summary> </member> <member name="T:GalaSoft.MvvmLight.Command.RelayCommand`1"> <summary> A generic command whose sole purpose is to relay its functionality to other objects by invoking delegates. The default return value for the CanExecute method is 'true'. This class allows you to accept command parameters in the Execute and CanExecute callback methods. </summary> <typeparam name="T">The type of the command parameter.</typeparam> </member> <member name="M:GalaSoft.MvvmLight.Command.RelayCommand`1.#ctor(System.Action{`0})"> <summary> Initializes a new instance of the RelayCommand class that can always execute. </summary> <param name="execute">The execution logic.</param> <exception cref="T:System.ArgumentNullException">If the execute argument is null.</exception> </member> <member name="M:GalaSoft.MvvmLight.Command.RelayCommand`1.#ctor(System.Action{`0},System.Func{`0,System.Boolean})"> <summary> Initializes a new instance of the RelayCommand class. </summary> <param name="execute">The execution logic.</param> <param name="canExecute">The execution status logic.</param> <exception cref="T:System.ArgumentNullException">If the execute argument is null.</exception> </member> <member name="M:GalaSoft.MvvmLight.Command.RelayCommand`1.RaiseCanExecuteChanged"> <summary> Raises the <see cref="E:GalaSoft.MvvmLight.Command.RelayCommand`1.CanExecuteChanged"/> event. </summary> </member> <member name="M:GalaSoft.MvvmLight.Command.RelayCommand`1.CanExecute(System.Object)"> <summary> Defines the method that determines whether the command can execute in its current state. </summary> <param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to a null reference</param> <returns>true if this command can be executed; otherwise, false.</returns> </member> <member name="M:GalaSoft.MvvmLight.Command.RelayCommand`1.Execute(System.Object)"> <summary> Defines the method to be called when the command is invoked. </summary> <param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to a null reference</param> </member> <member name="E:GalaSoft.MvvmLight.Command.RelayCommand`1.CanExecuteChanged"> <summary> Occurs when changes occur that affect whether the command should execute. </summary> </member> <member name="T:GalaSoft.MvvmLight.Helpers.IExecuteWithObject"> <summary> This interface is meant for the <see cref="T:GalaSoft.MvvmLight.Helpers.WeakAction`1"/> class and can be useful if you store multiple WeakAction{T} instances but don't know in advance what type T represents. </summary> </member> <member name="M:GalaSoft.MvvmLight.Helpers.IExecuteWithObject.ExecuteWithObject(System.Object)"> <summary> Executes an action. </summary> <param name="parameter">A parameter passed as an object, to be casted to the appropriate type.</param> </member> <member name="M:GalaSoft.MvvmLight.Helpers.IExecuteWithObject.MarkForDeletion"> <summary> Deletes all references, which notifies the cleanup method that this entry must be deleted. </summary> </member> <member name="P:GalaSoft.MvvmLight.Helpers.IExecuteWithObject.Target"> <summary> The target of the WeakAction. </summary> </member> <member name="T:GalaSoft.MvvmLight.ICleanup"> <summary> Defines a common interface for classes that should be cleaned up, but without the implications that IDisposable presupposes. An instance implementing ICleanup can be cleaned up without being disposed and garbage collected. </summary> </member> <member name="M:GalaSoft.MvvmLight.ICleanup.Cleanup"> <summary> Cleans up the instance, for example by saving its state, removing resources, etc... </summary> </member> <member name="T:GalaSoft.MvvmLight.Messaging.GenericMessage`1"> <summary> Passes a generic value (Content) to a recipient. </summary> <typeparam name="T">The type of the Content property.</typeparam> </member> <member name="T:GalaSoft.MvvmLight.Messaging.MessageBase"> <summary> Base class for all messages broadcasted by the Messenger. You can create your own message types by extending this class. </summary> </member> <member name="M:GalaSoft.MvvmLight.Messaging.MessageBase.#ctor"> <summary> Initializes a new instance of the MessageBase class. </summary> </member> <member name="M:GalaSoft.MvvmLight.Messaging.MessageBase.#ctor(System.Object)"> <summary> Initializes a new instance of the MessageBase class. </summary> <param name="sender">The message's original sender.</param> </member> <member name="M:GalaSoft.MvvmLight.Messaging.MessageBase.#ctor(System.Object,System.Object)"> <summary> Initializes a new instance of the MessageBase class. </summary> <param name="sender">The message's original sender.</param> <param name="target">The message's intended target. This parameter can be used to give an indication as to whom the message was intended for. Of course this is only an indication, amd may be null.</param> </member> <member name="P:GalaSoft.MvvmLight.Messaging.MessageBase.Sender"> <summary> Gets or sets the message's sender. </summary> </member> <member name="P:GalaSoft.MvvmLight.Messaging.MessageBase.Target"> <summary> Gets or sets the message's intended target. This property can be used to give an indication as to whom the message was intended for. Of course this is only an indication, amd may be null. </summary> </member> <member name="M:GalaSoft.MvvmLight.Messaging.GenericMessage`1.#ctor(`0)"> <summary> Initializes a new instance of the GenericMessage class. </summary> <param name="content">The message content.</param> </member> <member name="M:GalaSoft.MvvmLight.Messaging.GenericMessage`1.#ctor(System.Object,`0)"> <summary> Initializes a new instance of the GenericMessage class. </summary> <param name="sender">The message's sender.</param> <param name="content">The message content.</param> </member> <member name="M:GalaSoft.MvvmLight.Messaging.GenericMessage`1.#ctor(System.Object,System.Object,`0)"> <summary> Initializes a new instance of the GenericMessage class. </summary> <param name="sender">The message's sender.</param> <param name="target">The message's intended target. This parameter can be used to give an indication as to whom the message was intended for. Of course this is only an indication, amd may be null.</param> <param name="content">The message content.</param> </member> <member name="P:GalaSoft.MvvmLight.Messaging.GenericMessage`1.Content"> <summary> Gets or sets the message's content. </summary> </member> <member name="T:GalaSoft.MvvmLight.Messaging.IMessenger"> <summary> The Messenger is a class allowing objects to exchange messages. </summary> </member> <member name="M:GalaSoft.MvvmLight.Messaging.IMessenger.Register``1(System.Object,System.Action{``0})"> <summary> Registers a recipient for a type of message TMessage. The action parameter will be executed when a corresponding message is sent. <para>Registering a recipient does not create a hard reference to it, so if this recipient is deleted, no memory leak is caused.</para> </summary> <typeparam name="TMessage">The type of message that the recipient registers for.</typeparam> <param name="recipient">The recipient that will receive the messages.</param> <param name="action">The action that will be executed when a message of type TMessage is sent.</param> </member> <member name="M:GalaSoft.MvvmLight.Messaging.IMessenger.Register``1(System.Object,System.Object,System.Action{``0})"> <summary> Registers a recipient for a type of message TMessage. The action parameter will be executed when a corresponding message is sent. See the receiveDerivedMessagesToo parameter for details on how messages deriving from TMessage (or, if TMessage is an interface, messages implementing TMessage) can be received too. <para>Registering a recipient does not create a hard reference to it, so if this recipient is deleted, no memory leak is caused.</para> </summary> <typeparam name="TMessage">The type of message that the recipient registers for.</typeparam> <param name="recipient">The recipient that will receive the messages.</param> <param name="token">A token for a messaging channel. If a recipient registers using a token, and a sender sends a message using the same token, then this message will be delivered to the recipient. Other recipients who did not use a token when registering (or who used a different token) will not get the message. Similarly, messages sent without any token, or with a different token, will not be delivered to that recipient.</param> <param name="action">The action that will be executed when a message of type TMessage is sent.</param> </member> <member name="M:GalaSoft.MvvmLight.Messaging.IMessenger.Register``1(System.Object,System.Object,System.Boolean,System.Action{``0})"> <summary> Registers a recipient for a type of message TMessage. The action parameter will be executed when a corresponding message is sent. See the receiveDerivedMessagesToo parameter for details on how messages deriving from TMessage (or, if TMessage is an interface, messages implementing TMessage) can be received too. <para>Registering a recipient does not create a hard reference to it, so if this recipient is deleted, no memory leak is caused.</para> </summary> <typeparam name="TMessage">The type of message that the recipient registers for.</typeparam> <param name="recipient">The recipient that will receive the messages.</param> <param name="token">A token for a messaging channel. If a recipient registers using a token, and a sender sends a message using the same token, then this message will be delivered to the recipient. Other recipients who did not use a token when registering (or who used a different token) will not get the message. Similarly, messages sent without any token, or with a different token, will not be delivered to that recipient.</param> <param name="receiveDerivedMessagesToo">If true, message types deriving from TMessage will also be transmitted to the recipient. For example, if a SendOrderMessage and an ExecuteOrderMessage derive from OrderMessage, registering for OrderMessage and setting receiveDerivedMessagesToo to true will send SendOrderMessage and ExecuteOrderMessage to the recipient that registered. <para>Also, if TMessage is an interface, message types implementing TMessage will also be transmitted to the recipient. For example, if a SendOrderMessage and an ExecuteOrderMessage implement IOrderMessage, registering for IOrderMessage and setting receiveDerivedMessagesToo to true will send SendOrderMessage and ExecuteOrderMessage to the recipient that registered.</para> </param> <param name="action">The action that will be executed when a message of type TMessage is sent.</param> </member> <member name="M:GalaSoft.MvvmLight.Messaging.IMessenger.Register``1(System.Object,System.Boolean,System.Action{``0})"> <summary> Registers a recipient for a type of message TMessage. The action parameter will be executed when a corresponding message is sent. See the receiveDerivedMessagesToo parameter for details on how messages deriving from TMessage (or, if TMessage is an interface, messages implementing TMessage) can be received too. <para>Registering a recipient does not create a hard reference to it, so if this recipient is deleted, no memory leak is caused.</para> </summary> <typeparam name="TMessage">The type of message that the recipient registers for.</typeparam> <param name="recipient">The recipient that will receive the messages.</param> <param name="receiveDerivedMessagesToo">If true, message types deriving from TMessage will also be transmitted to the recipient. For example, if a SendOrderMessage and an ExecuteOrderMessage derive from OrderMessage, registering for OrderMessage and setting receiveDerivedMessagesToo to true will send SendOrderMessage and ExecuteOrderMessage to the recipient that registered. <para>Also, if TMessage is an interface, message types implementing TMessage will also be transmitted to the recipient. For example, if a SendOrderMessage and an ExecuteOrderMessage implement IOrderMessage, registering for IOrderMessage and setting receiveDerivedMessagesToo to true will send SendOrderMessage and ExecuteOrderMessage to the recipient that registered.</para> </param> <param name="action">The action that will be executed when a message of type TMessage is sent.</param> </member> <member name="M:GalaSoft.MvvmLight.Messaging.IMessenger.Send``1(``0)"> <summary> Sends a message to registered recipients. The message will reach all recipients that registered for this message type using one of the Register methods. </summary> <typeparam name="TMessage">The type of message that will be sent.</typeparam> <param name="message">The message to send to registered recipients.</param> </member> <member name="M:GalaSoft.MvvmLight.Messaging.IMessenger.Send``2(``0)"> <summary> Sends a message to registered recipients. The message will reach only recipients that registered for this message type using one of the Register methods, and that are of the targetType. </summary> <typeparam name="TMessage">The type of message that will be sent.</typeparam> <typeparam name="TTarget">The type of recipients that will receive the message. The message won't be sent to recipients of another type.</typeparam> <param name="message">The message to send to registered recipients.</param> </member> <member name="M:GalaSoft.MvvmLight.Messaging.IMessenger.Send``1(``0,System.Object)"> <summary> Sends a message to registered recipients. The message will reach only recipients that registered for this message type using one of the Register methods, and that are of the targetType. </summary> <typeparam name="TMessage">The type of message that will be sent.</typeparam> <param name="message">The message to send to registered recipients.</param> <param name="token">A token for a messaging channel. If a recipient registers using a token, and a sender sends a message using the same token, then this message will be delivered to the recipient. Other recipients who did not use a token when registering (or who used a different token) will not get the message. Similarly, messages sent without any token, or with a different token, will not be delivered to that recipient.</param> </member> <member name="M:GalaSoft.MvvmLight.Messaging.IMessenger.Unregister(System.Object)"> <summary> Unregisters a messager recipient completely. After this method is executed, the recipient will not receive any messages anymore. </summary> <param name="recipient">The recipient that must be unregistered.</param> </member> <member name="M:GalaSoft.MvvmLight.Messaging.IMessenger.Unregister``1(System.Object)"> <summary> Unregisters a message recipient for a given type of messages only. After this method is executed, the recipient will not receive messages of type TMessage anymore, but will still receive other message types (if it registered for them previously). </summary> <typeparam name="TMessage">The type of messages that the recipient wants to unregister from.</typeparam> <param name="recipient">The recipient that must be unregistered.</param> </member> <member name="M:GalaSoft.MvvmLight.Messaging.IMessenger.Unregister``1(System.Object,System.Object)"> <summary> Unregisters a message recipient for a given type of messages only and for a given token. After this method is executed, the recipient will not receive messages of type TMessage anymore with the given token, but will still receive other message types or messages with other tokens (if it registered for them previously). </summary> <param name="recipient">The recipient that must be unregistered.</param> <param name="token">The token for which the recipient must be unregistered.</param> <typeparam name="TMessage">The type of messages that the recipient wants to unregister from.</typeparam> </member> <member name="M:GalaSoft.MvvmLight.Messaging.IMessenger.Unregister``1(System.Object,System.Action{``0})"> <summary> Unregisters a message recipient for a given type of messages and for a given action. Other message types will still be transmitted to the recipient (if it registered for them previously). Other actions that have been registered for the message type TMessage and for the given recipient (if available) will also remain available. </summary> <typeparam name="TMessage">The type of messages that the recipient wants to unregister from.</typeparam> <param name="recipient">The recipient that must be unregistered.</param> <param name="action">The action that must be unregistered for the recipient and for the message type TMessage.</param> </member> <member name="M:GalaSoft.MvvmLight.Messaging.IMessenger.Unregister``1(System.Object,System.Object,System.Action{``0})"> <summary> Unregisters a message recipient for a given type of messages, for a given action and a given token. Other message types will still be transmitted to the recipient (if it registered for them previously). Other actions that have been registered for the message type TMessage, for the given recipient and other tokens (if available) will also remain available. </summary> <typeparam name="TMessage">The type of messages that the recipient wants to unregister from.</typeparam> <param name="recipient">The recipient that must be unregistered.</param> <param name="token">The token for which the recipient must be unregistered.</param> <param name="action">The action that must be unregistered for the recipient and for the message type TMessage.</param> </member> <member name="T:GalaSoft.MvvmLight.Messaging.NotificationMessage"> <summary> Passes a string message (Notification) to a recipient. <para>Typically, notifications are defined as unique strings in a static class. To define a unique string, you can use Guid.NewGuid().ToString() or any other unique identifier.</para> </summary> </member> <member name="M:GalaSoft.MvvmLight.Messaging.NotificationMessage.#ctor(System.String)"> <summary> Initializes a new instance of the NotificationMessage class. </summary> <param name="notification">A string containing any arbitrary message to be passed to recipient(s)</param> </member> <member name="M:GalaSoft.MvvmLight.Messaging.NotificationMessage.#ctor(System.Object,System.String)"> <summary> Initializes a new instance of the NotificationMessage class. </summary> <param name="sender">The message's sender.</param> <param name="notification">A string containing any arbitrary message to be passed to recipient(s)</param> </member> <member name="M:GalaSoft.MvvmLight.Messaging.NotificationMessage.#ctor(System.Object,System.Object,System.String)"> <summary> Initializes a new instance of the NotificationMessage class. </summary> <param name="sender">The message's sender.</param> <param name="target">The message's intended target. This parameter can be used to give an indication as to whom the message was intended for. Of course this is only an indication, amd may be null.</param> <param name="notification">A string containing any arbitrary message to be passed to recipient(s)</param> </member> <member name="P:GalaSoft.MvvmLight.Messaging.NotificationMessage.Notification"> <summary> Gets a string containing any arbitrary message to be passed to recipient(s). </summary> </member> <member name="T:GalaSoft.MvvmLight.Messaging.NotificationMessageAction"> <summary> Provides a message class with a built-in callback. When the recipient is done processing the message, it can execute the callback to notify the sender that it is done. Use the <see cref="M:GalaSoft.MvvmLight.Messaging.NotificationMessageAction.Execute"/> method to execute the callback. </summary> </member> <member name="T:GalaSoft.MvvmLight.Messaging.NotificationMessageWithCallback"> <summary> Provides a message class with a built-in callback. When the recipient is done processing the message, it can execute the callback to notify the sender that it is done. Use the <see cref="M:GalaSoft.MvvmLight.Messaging.NotificationMessageWithCallback.Execute(System.Object[])"/> method to execute the callback. The callback method has one parameter. <seealso cref="T:GalaSoft.MvvmLight.Messaging.NotificationMessageAction"/> and <seealso cref="T:GalaSoft.MvvmLight.Messaging.NotificationMessageAction`1"/>. </summary> </member> <member name="M:GalaSoft.MvvmLight.Messaging.NotificationMessageWithCallback.#ctor(System.String,System.Delegate)"> <summary> Initializes a new instance of the <see cref="T:GalaSoft.MvvmLight.Messaging.NotificationMessageWithCallback"/> class. </summary> <param name="notification">An arbitrary string that will be carried by the message.</param> <param name="callback">The callback method that can be executed by the recipient to notify the sender that the message has been processed.</param> </member> <member name="M:GalaSoft.MvvmLight.Messaging.NotificationMessageWithCallback.#ctor(System.Object,System.String,System.Delegate)"> <summary> Initializes a new instance of the <see cref="T:GalaSoft.MvvmLight.Messaging.NotificationMessageWithCallback"/> class. </summary> <param name="sender">The message's sender.</param> <param name="notification">An arbitrary string that will be carried by the message.</param> <param name="callback">The callback method that can be executed by the recipient to notify the sender that the message has been processed.</param> </member> <member name="M:GalaSoft.MvvmLight.Messaging.NotificationMessageWithCallback.#ctor(System.Object,System.Object,System.String,System.Delegate)"> <summary> Initializes a new instance of the <see cref="T:GalaSoft.MvvmLight.Messaging.NotificationMessageWithCallback"/> class. </summary> <param name="sender">The message's sender.</param> <param name="target">The message's intended target. This parameter can be used to give an indication as to whom the message was intended for. Of course this is only an indication, amd may be null.</param> <param name="notification">An arbitrary string that will be carried by the message.</param> <param name="callback">The callback method that can be executed by the recipient to notify the sender that the message has been processed.</param> </member> <member name="M:GalaSoft.MvvmLight.Messaging.NotificationMessageWithCallback.Execute(System.Object[])"> <summary> Executes the callback that was provided with the message with an arbitrary number of parameters. </summary> <param name="arguments">A number of parameters that will be passed to the callback method.</param> <returns>The object returned by the callback method.</returns> </member> <member name="M:GalaSoft.MvvmLight.Messaging.NotificationMessageAction.#ctor(System.String,System.Action)"> <summary> Initializes a new instance of the <see cref="T:GalaSoft.MvvmLight.Messaging.NotificationMessageAction"/> class. </summary> <param name="notification">An arbitrary string that will be carried by the message.</param> <param name="callback">The callback method that can be executed by the recipient to notify the sender that the message has been processed.</param> </member> <member name="M:GalaSoft.MvvmLight.Messaging.NotificationMessageAction.#ctor(System.Object,System.String,System.Action)"> <summary> Initializes a new instance of the <see cref="T:GalaSoft.MvvmLight.Messaging.NotificationMessageAction"/> class. </summary> <param name="sender">The message's sender.</param> <param name="notification">An arbitrary string that will be carried by the message.</param> <param name="callback">The callback method that can be executed by the recipient to notify the sender that the message has been processed.</param> </member> <member name="M:GalaSoft.MvvmLight.Messaging.NotificationMessageAction.#ctor(System.Object,System.Object,System.String,System.Action)"> <summary> Initializes a new instance of the <see cref="T:GalaSoft.MvvmLight.Messaging.NotificationMessageAction"/> class. </summary> <param name="sender">The message's sender.</param> <param name="target">The message's intended target. This parameter can be used to give an indication as to whom the message was intended for. Of course this is only an indication, amd may be null.</param> <param name="notification">An arbitrary string that will be carried by the message.</param> <param name="callback">The callback method that can be executed by the recipient to notify the sender that the message has been processed.</param> </member> <member name="M:GalaSoft.MvvmLight.Messaging.NotificationMessageAction.Execute"> <summary> Executes the callback that was provided with the message. </summary> </member> <member name="T:GalaSoft.MvvmLight.Messaging.NotificationMessageAction`1"> <summary> Provides a message class with a built-in callback. When the recipient is done processing the message, it can execute the callback to notify the sender that it is done. Use the <see cref="M:GalaSoft.MvvmLight.Messaging.NotificationMessageAction`1.Execute(`0)"/> method to execute the callback. The callback method has one parameter. <seealso cref="T:GalaSoft.MvvmLight.Messaging.NotificationMessageAction"/>. </summary> <typeparam name="TCallbackParameter">The type of the callback method's only parameter.</typeparam> </member> <member name="M:GalaSoft.MvvmLight.Messaging.NotificationMessageAction`1.#ctor(System.String,System.Action{`0})"> <summary> Initializes a new instance of the <see cref="T:GalaSoft.MvvmLight.Messaging.NotificationMessageAction`1"/> class. </summary> <param name="notification">An arbitrary string that will be carried by the message.</param> <param name="callback">The callback method that can be executed by the recipient to notify the sender that the message has been processed.</param> </member> <member name="M:GalaSoft.MvvmLight.Messaging.NotificationMessageAction`1.#ctor(System.Object,System.String,System.Action{`0})"> <summary> Initializes a new instance of the <see cref="T:GalaSoft.MvvmLight.Messaging.NotificationMessageAction`1"/> class. </summary> <param name="sender">The message's sender.</param> <param name="notification">An arbitrary string that will be carried by the message.</param> <param name="callback">The callback method that can be executed by the recipient to notify the sender that the message has been processed.</param> </member> <member name="M:GalaSoft.MvvmLight.Messaging.NotificationMessageAction`1.#ctor(System.Object,System.Object,System.String,System.Action{`0})"> <summary> Initializes a new instance of the <see cref="T:GalaSoft.MvvmLight.Messaging.NotificationMessageAction`1"/> class. </summary> <param name="sender">The message's sender.</param> <param name="target">The message's intended target. This parameter can be used to give an indication as to whom the message was intended for. Of course this is only an indication, amd may be null.</param> <param name="notification">An arbitrary string that will be carried by the message.</param> <param name="callback">The callback method that can be executed by the recipient to notify the sender that the message has been processed.</param> </member> <member name="M:GalaSoft.MvvmLight.Messaging.NotificationMessageAction`1.Execute(`0)"> <summary> Executes the callback that was provided with the message. </summary> <param name="parameter">A parameter requested by the message's sender and providing additional information on the recipient's state.</param> </member> <member name="T:GalaSoft.MvvmLight.Messaging.NotificationMessage`1"> <summary> Passes a string message (Notification) and a generic value (Content) to a recipient. </summary> <typeparam name="T">The type of the Content property.</typeparam> </member> <member name="M:GalaSoft.MvvmLight.Messaging.NotificationMessage`1.#ctor(`0,System.String)"> <summary> Initializes a new instance of the NotificationMessage class. </summary> <param name="content">A value to be passed to recipient(s).</param> <param name="notification">A string containing any arbitrary message to be passed to recipient(s)</param> </member> <member name="M:GalaSoft.MvvmLight.Messaging.NotificationMessage`1.#ctor(System.Object,`0,System.String)"> <summary> Initializes a new instance of the NotificationMessage class. </summary> <param name="sender">The message's sender.</param> <param name="content">A value to be passed to recipient(s).</param> <param name="notification">A string containing any arbitrary message to be passed to recipient(s)</param> </member> <member name="M:GalaSoft.MvvmLight.Messaging.NotificationMessage`1.#ctor(System.Object,System.Object,`0,System.String)"> <summary> Initializes a new instance of the NotificationMessage class. </summary> <param name="sender">The message's sender.</param> <param name="target">The message's intended target. This parameter can be used to give an indication as to whom the message was intended for. Of course this is only an indication, amd may be null.</param> <param name="content">A value to be passed to recipient(s).</param> <param name="notification">A string containing any arbitrary message to be passed to recipient(s)</param> </member> <member name="P:GalaSoft.MvvmLight.Messaging.NotificationMessage`1.Notification"> <summary> Gets a string containing any arbitrary message to be passed to recipient(s). </summary> </member> <member name="T:GalaSoft.MvvmLight.Messaging.PropertyChangedMessage`1"> <summary> Passes a string property name (PropertyName) and a generic value (<see cref="P:GalaSoft.MvvmLight.Messaging.PropertyChangedMessage`1.OldValue"/> and <see cref="P:GalaSoft.MvvmLight.Messaging.PropertyChangedMessage`1.NewValue"/>) to a recipient. This message type can be used to propagate a PropertyChanged event to a recipient using the messenging system. </summary> <typeparam name="T">The type of the OldValue and NewValue property.</typeparam> </member> <member name="T:GalaSoft.MvvmLight.Messaging.PropertyChangedMessageBase"> <summary> Basis class for the <see cref="T:GalaSoft.MvvmLight.Messaging.PropertyChangedMessage`1"/> class. This class allows a recipient to register for all PropertyChangedMessages without having to specify the type T. </summary> </member> <member name="M:GalaSoft.MvvmLight.Messaging.PropertyChangedMessageBase.#ctor(System.Object,System.String)"> <summary> Initializes a new instance of the <see cref="T:GalaSoft.MvvmLight.Messaging.PropertyChangedMessageBase"/> class. </summary> <param name="sender">The message's sender.</param> <param name="propertyName">The name of the property that changed.</param> </member> <member name="M:GalaSoft.MvvmLight.Messaging.PropertyChangedMessageBase.#ctor(System.Object,System.Object,System.String)"> <summary> Initializes a new instance of the <see cref="T:GalaSoft.MvvmLight.Messaging.PropertyChangedMessageBase"/> class. </summary> <param name="sender">The message's sender.</param> <param name="target">The message's intended target. This parameter can be used to give an indication as to whom the message was intended for. Of course this is only an indication, amd may be null.</param> <param name="propertyName">The name of the property that changed.</param> </member> <member name="M:GalaSoft.MvvmLight.Messaging.PropertyChangedMessageBase.#ctor(System.String)"> <summary> Initializes a new instance of the <see cref="T:GalaSoft.MvvmLight.Messaging.PropertyChangedMessageBase"/> class. </summary> <param name="propertyName">The name of the property that changed.</param> </member> <member name="P:GalaSoft.MvvmLight.Messaging.PropertyChangedMessageBase.PropertyName"> <summary> Gets or sets the name of the property that changed. </summary> </member> <member name="M:GalaSoft.MvvmLight.Messaging.PropertyChangedMessage`1.#ctor(System.Object,`0,`0,System.String)"> <summary> Initializes a new instance of the <see cref="T:GalaSoft.MvvmLight.Messaging.PropertyChangedMessage`1"/> class. </summary> <param name="sender">The message's sender.</param> <param name="oldValue">The property's value before the change occurred.</param> <param name="newValue">The property's value after the change occurred.</param> <param name="propertyName">The name of the property that changed.</param> </member> <member name="M:GalaSoft.MvvmLight.Messaging.PropertyChangedMessage`1.#ctor(`0,`0,System.String)"> <summary> Initializes a new instance of the <see cref="T:GalaSoft.MvvmLight.Messaging.PropertyChangedMessage`1"/> class. </summary> <param name="oldValue">The property's value before the change occurred.</param> <param name="newValue">The property's value after the change occurred.</param> <param name="propertyName">The name of the property that changed.</param> </member> <member name="M:GalaSoft.MvvmLight.Messaging.PropertyChangedMessage`1.#ctor(System.Object,System.Object,`0,`0,System.String)"> <summary> Initializes a new instance of the <see cref="T:GalaSoft.MvvmLight.Messaging.PropertyChangedMessage`1"/> class. </summary> <param name="sender">The message's sender.</param> <param name="target">The message's intended target. This parameter can be used to give an indication as to whom the message was intended for. Of course this is only an indication, amd may be null.</param> <param name="oldValue">The property's value before the change occurred.</param> <param name="newValue">The property's value after the change occurred.</param> <param name="propertyName">The name of the property that changed.</param> </member> <member name="P:GalaSoft.MvvmLight.Messaging.PropertyChangedMessage`1.NewValue"> <summary> Gets the value that the property has after the change. </summary> </member> <member name="P:GalaSoft.MvvmLight.Messaging.PropertyChangedMessage`1.OldValue"> <summary> Gets the value that the property had before the change. </summary> </member> <member name="T:GalaSoft.MvvmLight.ObservableObject"> <summary> A base class for objects of which the properties must be observable. </summary> </member> <member name="T:System.ComponentModel.INotifyPropertyChanging"> <summary> Defines an event for notifying clients that a property value is changing. </summary> </member> <member name="E:System.ComponentModel.INotifyPropertyChanging.PropertyChanging"> <summary> Occurs when a property value is changing. </summary> </member> <member name="M:GalaSoft.MvvmLight.ObservableObject.VerifyPropertyName(System.String)"> <summary> Verifies that a property name exists in this ViewModel. This method can be called before the property is used, for instance before calling RaisePropertyChanged. It avoids errors when a property name is changed but some places are missed. <para>This method is only active in DEBUG mode.</para> </summary> <param name="propertyName"></param> </member> <member name="M:GalaSoft.MvvmLight.ObservableObject.RaisePropertyChanging(System.String)"> <summary> Raises the PropertyChanging event if needed. </summary> <remarks>If the propertyName parameter does not correspond to an existing property on the current class, an exception is thrown in DEBUG configuration only.</remarks> <param name="propertyName">The name of the property that changed.</param> </member> <member name="M:GalaSoft.MvvmLight.ObservableObject.RaisePropertyChanged(System.String)"> <summary> Raises the PropertyChanged event if needed. </summary> <remarks>If the propertyName parameter does not correspond to an existing property on the current class, an exception is thrown in DEBUG configuration only.</remarks> <param name="propertyName">The name of the property that changed.</param> </member> <member name="M:GalaSoft.MvvmLight.ObservableObject.RaisePropertyChanging``1(System.Linq.Expressions.Expression{System.Func{``0}})"> <summary> Raises the PropertyChanging event if needed. </summary> <typeparam name="T">The type of the property that changes.</typeparam> <param name="propertyExpression">An expression identifying the property that changes.</param> </member> <member name="M:GalaSoft.MvvmLight.ObservableObject.RaisePropertyChanged``1(System.Linq.Expressions.Expression{System.Func{``0}})"> <summary> Raises the PropertyChanged event if needed. </summary> <typeparam name="T">The type of the property that changed.</typeparam> <param name="propertyExpression">An expression identifying the property that changed.</param> </member> <member name="M:GalaSoft.MvvmLight.ObservableObject.GetPropertyName``1(System.Linq.Expressions.Expression{System.Func{``0}})"> <summary> Extracts the name of a property from an expression. </summary> <typeparam name="T">The type of the property.</typeparam> <param name="propertyExpression">An expression returning the property's name.</param> <returns>The name of the property returned by the expression.</returns> <exception cref="T:System.ArgumentNullException">If the expression is null.</exception> <exception cref="T:System.ArgumentException">If the expression does not represent a property.</exception> </member> <member name="M:GalaSoft.MvvmLight.ObservableObject.Set``1(System.Linq.Expressions.Expression{System.Func{``0}},``0@,``0)"> <summary> Assigns a new value to the property. Then, raises the PropertyChanged event if needed. </summary> <typeparam name="T">The type of the property that changed.</typeparam> <param name="propertyExpression">An expression identifying the property that changed.</param> <param name="field">The field storing the property's value.</param> <param name="newValue">The property's value after the change occurred.</param> <returns>True if the PropertyChanged event has been raised, false otherwise. The event is not raised if the old value is equal to the new value.</returns> </member> <member name="M:GalaSoft.MvvmLight.ObservableObject.Set``1(System.String,``0@,``0)"> <summary> Assigns a new value to the property. Then, raises the PropertyChanged event if needed. </summary> <typeparam name="T">The type of the property that changed.</typeparam> <param name="propertyName">The name of the property that changed.</param> <param name="field">The field storing the property's value.</param> <param name="newValue">The property's value after the change occurred.</param> <returns>True if the PropertyChanged event has been raised, false otherwise. The event is not raised if the old value is equal to the new value.</returns> </member> <member name="E:GalaSoft.MvvmLight.ObservableObject.PropertyChanged"> <summary> Occurs after a property value changes. </summary> </member> <member name="P:GalaSoft.MvvmLight.ObservableObject.PropertyChangedHandler"> <summary> Provides access to the PropertyChanged event handler to derived classes. </summary> </member> <member name="E:GalaSoft.MvvmLight.ObservableObject.PropertyChanging"> <summary> Occurs before a property value changes. </summary> </member> <member name="P:GalaSoft.MvvmLight.ObservableObject.PropertyChangingHandler"> <summary> Provides access to the PropertyChanging event handler to derived classes. </summary> </member> <member name="T:GalaSoft.MvvmLight.Threading.DispatcherHelper"> <summary> Helper class for dispatcher operations on the UI thread. </summary> </member> <member name="M:GalaSoft.MvvmLight.Threading.DispatcherHelper.CheckBeginInvokeOnUI(System.Action)"> <summary> Executes an action on the UI thread. If this method is called from the UI thread, the action is executed immendiately. If the method is called from another thread, the action will be enqueued on the UI thread's dispatcher and executed asynchronously. <para>For additional operations on the UI thread, you can get a reference to the UI thread's dispatcher thanks to the property <see cref="P:GalaSoft.MvvmLight.Threading.DispatcherHelper.UIDispatcher"/></para>. </summary> <param name="action">The action that will be executed on the UI thread.</param> </member> <member name="M:GalaSoft.MvvmLight.Threading.DispatcherHelper.RunAsync(System.Action)"> <summary> Invokes an action asynchronously on the UI thread. </summary> <param name="action">The action that must be executed.</param> </member> <member name="M:GalaSoft.MvvmLight.Threading.DispatcherHelper.Initialize"> <summary> This method should be called once on the UI thread to ensure that the <see cref="P:GalaSoft.MvvmLight.Threading.DispatcherHelper.UIDispatcher"/> property is initialized. <para>In a Silverlight application, call this method in the Application_Startup event handler, after the MainPage is constructed.</para> <para>In WPF, call this method on the static App() constructor.</para> </summary> </member> <member name="P:GalaSoft.MvvmLight.Threading.DispatcherHelper.UIDispatcher"> <summary> Gets a reference to the UI thread's dispatcher, after the <see cref="M:GalaSoft.MvvmLight.Threading.DispatcherHelper.Initialize"/> method has been called on the UI thread. </summary> </member> <member name="T:GalaSoft.MvvmLight.ViewModelBase"> <summary> A base class for the ViewModel classes in the MVVM pattern. </summary> </member> <member name="M:GalaSoft.MvvmLight.ViewModelBase.#ctor"> <summary> Initializes a new instance of the ViewModelBase class. </summary> </member> <member name="M:GalaSoft.MvvmLight.ViewModelBase.#ctor(GalaSoft.MvvmLight.Messaging.IMessenger)"> <summary> Initializes a new instance of the ViewModelBase class. </summary> <param name="messenger">An instance of a <see cref="T:GalaSoft.MvvmLight.Messaging.Messenger"/> used to broadcast messages to other objects. If null, this class will attempt to broadcast using the Messenger's default instance.</param> </member> <member name="M:GalaSoft.MvvmLight.ViewModelBase.Cleanup"> <summary> Unregisters this instance from the Messenger class. <para>To cleanup additional resources, override this method, clean up and then call base.Cleanup().</para> </summary> </member> <member name="M:GalaSoft.MvvmLight.ViewModelBase.Broadcast``1(``0,``0,System.String)"> <summary> Broadcasts a PropertyChangedMessage using either the instance of the Messenger that was passed to this class (if available) or the Messenger's default instance. </summary> <typeparam name="T">The type of the property that changed.</typeparam> <param name="oldValue">The value of the property before it changed.</param> <param name="newValue">The value of the property after it changed.</param> <param name="propertyName">The name of the property that changed.</param> </member> <member name="M:GalaSoft.MvvmLight.ViewModelBase.RaisePropertyChanged``1(System.String,``0,``0,System.Boolean)"> <summary> Raises the PropertyChanged event if needed, and broadcasts a PropertyChangedMessage using the Messenger instance (or the static default instance if no Messenger instance is available). </summary> <typeparam name="T">The type of the property that changed.</typeparam> <param name="propertyName">The name of the property that changed.</param> <param name="oldValue">The property's value before the change occurred.</param> <param name="newValue">The property's value after the change occurred.</param> <param name="broadcast">If true, a PropertyChangedMessage will be broadcasted. If false, only the event will be raised.</param> <remarks>If the propertyName parameter does not correspond to an existing property on the current class, an exception is thrown in DEBUG configuration only.</remarks> </member> <member name="M:GalaSoft.MvvmLight.ViewModelBase.RaisePropertyChanged``1(System.Linq.Expressions.Expression{System.Func{``0}},``0,``0,System.Boolean)"> <summary> Raises the PropertyChanged event if needed, and broadcasts a PropertyChangedMessage using the Messenger instance (or the static default instance if no Messenger instance is available). </summary> <typeparam name="T">The type of the property that changed.</typeparam> <param name="propertyExpression">An expression identifying the property that changed.</param> <param name="oldValue">The property's value before the change occurred.</param> <param name="newValue">The property's value after the change occurred.</param> <param name="broadcast">If true, a PropertyChangedMessage will be broadcasted. If false, only the event will be raised.</param> </member> <member name="M:GalaSoft.MvvmLight.ViewModelBase.Set``1(System.Linq.Expressions.Expression{System.Func{``0}},``0@,``0,System.Boolean)"> <summary> Assigns a new value to the property. Then, raises the PropertyChanged event if needed, and broadcasts a PropertyChangedMessage using the Messenger instance (or the static default instance if no Messenger instance is available). </summary> <typeparam name="T">The type of the property that changed.</typeparam> <param name="propertyExpression">An expression identifying the property that changed.</param> <param name="field">The field storing the property's value.</param> <param name="newValue">The property's value after the change occurred.</param> <param name="broadcast">If true, a PropertyChangedMessage will be broadcasted. If false, only the event will be raised.</param> </member> <member name="M:GalaSoft.MvvmLight.ViewModelBase.Set``1(System.String,``0@,``0,System.Boolean)"> <summary> Assigns a new value to the property. Then, raises the PropertyChanged event if needed, and broadcasts a PropertyChangedMessage using the Messenger instance (or the static default instance if no Messenger instance is available). </summary> <typeparam name="T">The type of the property that changed.</typeparam> <param name="propertyName">The name of the property that changed.</param> <param name="field">The field storing the property's value.</param> <param name="newValue">The property's value after the change occurred.</param> <param name="broadcast">If true, a PropertyChangedMessage will be broadcasted. If false, only the event will be raised.</param> </member> <member name="P:GalaSoft.MvvmLight.ViewModelBase.IsInDesignMode"> <summary> Gets a value indicating whether the control is in design mode (running under Blend or Visual Studio). </summary> </member> <member name="P:GalaSoft.MvvmLight.ViewModelBase.IsInDesignModeStatic"> <summary> Gets a value indicating whether the control is in design mode (running in Blend or Visual Studio). </summary> </member> <member name="P:GalaSoft.MvvmLight.ViewModelBase.MessengerInstance"> <summary> Gets or sets an instance of a <see cref="T:GalaSoft.MvvmLight.Messaging.IMessenger"/> used to broadcast messages to other objects. If null, this class will attempt to broadcast using the Messenger's default instance. </summary> </member> <member name="T:System.ComponentModel.PropertyChangingEventArgs"> <summary> Provides data for the System.ComponentModel.INotifyPropertyChanging.PropertyChanging event. </summary> </member> <member name="M:System.ComponentModel.PropertyChangingEventArgs.#ctor(System.String)"> <summary> Initializes a new instance of the System.ComponentModel.PropertyChangingEventArgs class. </summary> <param name="propertyName">The name of the property that is changing.</param> </member> <member name="P:System.ComponentModel.PropertyChangingEventArgs.PropertyName"> <summary> Gets the name of the property that is changing. </summary> </member> <member name="T:System.ComponentModel.PropertyChangingEventHandler"> <summary> Represents a method that will handle the System.ComponentModel.INotifyPropertyChanging.PropertyChanging event. </summary> <param name="sender">The source of the event.</param> <param name="e">The event data.</param> </member> <member name="M:GalaSoft.MvvmLight.Helpers.IExecuteWithObjectAndResult`1.ExecuteWithObject(System.Object)"> <summary> Executes an action. </summary> <param name="parameter">A parameter passed as an object, to be casted to the appropriate type.</param> </member> <member name="M:GalaSoft.MvvmLight.Helpers.IExecuteWithObjectAndResult`1.MarkForDeletion"> <summary> Deletes all references, which notifies the cleanup method that this entry must be deleted. </summary> </member> <member name="P:GalaSoft.MvvmLight.Helpers.IExecuteWithObjectAndResult`1.Target"> <summary> The target of the WeakAction. </summary> </member> <member name="T:GalaSoft.MvvmLight.Helpers.WeakAction"> <summary> Stores an <see cref="P:GalaSoft.MvvmLight.Helpers.WeakAction.Action"/> without causing a hard reference to be created to the Action's owner. The owner can be garbage collected at any time. </summary> </member> <member name="M:GalaSoft.MvvmLight.Helpers.WeakAction.#ctor(System.Object,System.Action)"> <summary> Initializes a new instance of the <see cref="T:GalaSoft.MvvmLight.Helpers.WeakAction"/> class. </summary> <param name="target">The action's owner.</param> <param name="action">The action that will be associated to this instance.</param> </member> <member name="M:GalaSoft.MvvmLight.Helpers.WeakAction.Execute"> <summary> Executes the action. This only happens if the action's owner is still alive. </summary> </member> <member name="M:GalaSoft.MvvmLight.Helpers.WeakAction.MarkForDeletion"> <summary> Sets the reference that this instance stores to null. </summary> </member> <member name="P:GalaSoft.MvvmLight.Helpers.WeakAction.Action"> <summary> Gets the Action associated to this instance. </summary> </member> <member name="P:GalaSoft.MvvmLight.Helpers.WeakAction.IsAlive"> <summary> Gets a value indicating whether the Action's owner is still alive, or if it was collected by the Garbage Collector already. </summary> </member> <member name="P:GalaSoft.MvvmLight.Helpers.WeakAction.Target"> <summary> Gets the Action's owner. This object is stored as a <see cref="T:System.WeakReference"/>. </summary> </member> <member name="T:GalaSoft.MvvmLight.Helpers.WeakAction`1"> <summary> Stores an Action without causing a hard reference to be created to the Action's owner. The owner can be garbage collected at any time. </summary> <typeparam name="T">The type of the Action's parameter.</typeparam> </member> <member name="M:GalaSoft.MvvmLight.Helpers.WeakAction`1.#ctor(System.Object,System.Action{`0})"> <summary> Initializes a new instance of the WeakAction class. </summary> <param name="target">The action's owner.</param> <param name="action">The action that will be associated to this instance.</param> </member> <member name="M:GalaSoft.MvvmLight.Helpers.WeakAction`1.Execute"> <summary> Executes the action. This only happens if the action's owner is still alive. The action's parameter is set to default(T). </summary> </member> <member name="M:GalaSoft.MvvmLight.Helpers.WeakAction`1.Execute(`0)"> <summary> Executes the action. This only happens if the action's owner is still alive. </summary> <param name="parameter">A parameter to be passed to the action.</param> </member> <member name="M:GalaSoft.MvvmLight.Helpers.WeakAction`1.ExecuteWithObject(System.Object)"> <summary> Executes the action with a parameter of type object. This parameter will be casted to T. This method implements <see cref="M:GalaSoft.MvvmLight.Helpers.IExecuteWithObject.ExecuteWithObject(System.Object)"/> and can be useful if you store multiple WeakAction{T} instances but don't know in advance what type T represents. </summary> <param name="parameter">The parameter that will be passed to the action after being casted to T.</param> </member> <member name="P:GalaSoft.MvvmLight.Helpers.WeakAction`1.Action"> <summary> Gets the Action associated to this instance. </summary> </member> <member name="T:GalaSoft.MvvmLight.Helpers.WeakFunc`1"> <summary> Stores a <see cref="P:GalaSoft.MvvmLight.Helpers.WeakFunc`1.Func"/> without causing a hard reference to be created to the Func's owner. The owner can be garbage collected at any time. </summary> </member> <member name="M:GalaSoft.MvvmLight.Helpers.WeakFunc`1.#ctor(System.Object,System.Func{`0})"> <summary> Initializes a new instance of the <see cref="!:WeakFunc"/> class. </summary> <param name="target">The func's owner.</param> <param name="func">The func that will be associated to this instance.</param> </member> <member name="M:GalaSoft.MvvmLight.Helpers.WeakFunc`1.Execute"> <summary> Executes the Func. This only happens if the Func's owner is still alive. </summary> </member> <member name="M:GalaSoft.MvvmLight.Helpers.WeakFunc`1.MarkForDeletion"> <summary> Sets the reference that this instance stores to null. </summary> </member> <member name="P:GalaSoft.MvvmLight.Helpers.WeakFunc`1.Func"> <summary> Gets the Func associated to this instance. </summary> </member> <member name="P:GalaSoft.MvvmLight.Helpers.WeakFunc`1.IsAlive"> <summary> Gets a value indicating whether the Func's owner is still alive, or if it was collected by the Garbage Collector already. </summary> </member> <member name="P:GalaSoft.MvvmLight.Helpers.WeakFunc`1.Target"> <summary> Gets the Func's owner. This object is stored as a <see cref="T:System.WeakReference"/>. </summary> </member> <member name="T:GalaSoft.MvvmLight.Helpers.WeakFunc`2"> <summary> Stores a Func without causing a hard reference to be created to the Func's owner. The owner can be garbage collected at any time. </summary> <typeparam name="T">The type of the Func's parameter.</typeparam> </member> <member name="M:GalaSoft.MvvmLight.Helpers.WeakFunc`2.#ctor(System.Object,System.Func{`0,`1})"> <summary> Initializes a new instance of the WeakFunc class. </summary> <param name="target">The func's owner.</param> <param name="func">The func that will be associated to this instance.</param> </member> <member name="M:GalaSoft.MvvmLight.Helpers.WeakFunc`2.Execute"> <summary> Executes the func. This only happens if the func's owner is still alive. The func's parameter is set to default(T). </summary> </member> <member name="M:GalaSoft.MvvmLight.Helpers.WeakFunc`2.Execute(`0)"> <summary> Executes the func. This only happens if the func's owner is still alive. </summary> <param name="parameter">A parameter to be passed to the func.</param> </member> <member name="M:GalaSoft.MvvmLight.Helpers.WeakFunc`2.ExecuteWithObject(System.Object)"> <summary> Executes the func with a parameter of type object. This parameter will be casted to T. This method implements <see cref="M:GalaSoft.MvvmLight.Helpers.IExecuteWithObject.ExecuteWithObject(System.Object)"/> and can be useful if you store multiple WeakFunc{T} instances but don't know in advance what type T represents. </summary> <param name="parameter">The parameter that will be passed to the action after being casted to T.</param> </member> <member name="P:GalaSoft.MvvmLight.Helpers.WeakFunc`2.Func"> <summary> Gets the Func associated to this instance. </summary> </member> <member name="T:GalaSoft.MvvmLight.Messaging.Messenger"> <summary> The Messenger is a class allowing objects to exchange messages. </summary> </member> <member name="M:GalaSoft.MvvmLight.Messaging.Messenger.Register``1(System.Object,System.Action{``0})"> <summary> Registers a recipient for a type of message TMessage. The action parameter will be executed when a corresponding message is sent. <para>Registering a recipient does not create a hard reference to it, so if this recipient is deleted, no memory leak is caused.</para> </summary> <typeparam name="TMessage">The type of message that the recipient registers for.</typeparam> <param name="recipient">The recipient that will receive the messages.</param> <param name="action">The action that will be executed when a message of type TMessage is sent.</param> </member> <member name="M:GalaSoft.MvvmLight.Messaging.Messenger.Register``1(System.Object,System.Boolean,System.Action{``0})"> <summary> Registers a recipient for a type of message TMessage. The action parameter will be executed when a corresponding message is sent. See the receiveDerivedMessagesToo parameter for details on how messages deriving from TMessage (or, if TMessage is an interface, messages implementing TMessage) can be received too. <para>Registering a recipient does not create a hard reference to it, so if this recipient is deleted, no memory leak is caused.</para> </summary> <typeparam name="TMessage">The type of message that the recipient registers for.</typeparam> <param name="recipient">The recipient that will receive the messages.</param> <param name="receiveDerivedMessagesToo">If true, message types deriving from TMessage will also be transmitted to the recipient. For example, if a SendOrderMessage and an ExecuteOrderMessage derive from OrderMessage, registering for OrderMessage and setting receiveDerivedMessagesToo to true will send SendOrderMessage and ExecuteOrderMessage to the recipient that registered. <para>Also, if TMessage is an interface, message types implementing TMessage will also be transmitted to the recipient. For example, if a SendOrderMessage and an ExecuteOrderMessage implement IOrderMessage, registering for IOrderMessage and setting receiveDerivedMessagesToo to true will send SendOrderMessage and ExecuteOrderMessage to the recipient that registered.</para> </param> <param name="action">The action that will be executed when a message of type TMessage is sent.</param> </member> <member name="M:GalaSoft.MvvmLight.Messaging.Messenger.Register``1(System.Object,System.Object,System.Action{``0})"> <summary> Registers a recipient for a type of message TMessage. The action parameter will be executed when a corresponding message is sent. <para>Registering a recipient does not create a hard reference to it, so if this recipient is deleted, no memory leak is caused.</para> </summary> <typeparam name="TMessage">The type of message that the recipient registers for.</typeparam> <param name="recipient">The recipient that will receive the messages.</param> <param name="token">A token for a messaging channel. If a recipient registers using a token, and a sender sends a message using the same token, then this message will be delivered to the recipient. Other recipients who did not use a token when registering (or who used a different token) will not get the message. Similarly, messages sent without any token, or with a different token, will not be delivered to that recipient.</param> <param name="action">The action that will be executed when a message of type TMessage is sent.</param> </member> <member name="M:GalaSoft.MvvmLight.Messaging.Messenger.Register``1(System.Object,System.Object,System.Boolean,System.Action{``0})"> <summary> Registers a recipient for a type of message TMessage. The action parameter will be executed when a corresponding message is sent. See the receiveDerivedMessagesToo parameter for details on how messages deriving from TMessage (or, if TMessage is an interface, messages implementing TMessage) can be received too. <para>Registering a recipient does not create a hard reference to it, so if this recipient is deleted, no memory leak is caused.</para> </summary> <typeparam name="TMessage">The type of message that the recipient registers for.</typeparam> <param name="recipient">The recipient that will receive the messages.</param> <param name="token">A token for a messaging channel. If a recipient registers using a token, and a sender sends a message using the same token, then this message will be delivered to the recipient. Other recipients who did not use a token when registering (or who used a different token) will not get the message. Similarly, messages sent without any token, or with a different token, will not be delivered to that recipient.</param> <param name="receiveDerivedMessagesToo">If true, message types deriving from TMessage will also be transmitted to the recipient. For example, if a SendOrderMessage and an ExecuteOrderMessage derive from OrderMessage, registering for OrderMessage and setting receiveDerivedMessagesToo to true will send SendOrderMessage and ExecuteOrderMessage to the recipient that registered. <para>Also, if TMessage is an interface, message types implementing TMessage will also be transmitted to the recipient. For example, if a SendOrderMessage and an ExecuteOrderMessage implement IOrderMessage, registering for IOrderMessage and setting receiveDerivedMessagesToo to true will send SendOrderMessage and ExecuteOrderMessage to the recipient that registered.</para> </param> <param name="action">The action that will be executed when a message of type TMessage is sent.</param> </member> <member name="M:GalaSoft.MvvmLight.Messaging.Messenger.Send``1(``0)"> <summary> Sends a message to registered recipients. The message will reach all recipients that registered for this message type using one of the Register methods. </summary> <typeparam name="TMessage">The type of message that will be sent.</typeparam> <param name="message">The message to send to registered recipients.</param> </member> <member name="M:GalaSoft.MvvmLight.Messaging.Messenger.Send``2(``0)"> <summary> Sends a message to registered recipients. The message will reach only recipients that registered for this message type using one of the Register methods, and that are of the targetType. </summary> <typeparam name="TMessage">The type of message that will be sent.</typeparam> <typeparam name="TTarget">The type of recipients that will receive the message. The message won't be sent to recipients of another type.</typeparam> <param name="message">The message to send to registered recipients.</param> </member> <member name="M:GalaSoft.MvvmLight.Messaging.Messenger.Send``1(``0,System.Object)"> <summary> Sends a message to registered recipients. The message will reach only recipients that registered for this message type using one of the Register methods, and that are of the targetType. </summary> <typeparam name="TMessage">The type of message that will be sent.</typeparam> <param name="message">The message to send to registered recipients.</param> <param name="token">A token for a messaging channel. If a recipient registers using a token, and a sender sends a message using the same token, then this message will be delivered to the recipient. Other recipients who did not use a token when registering (or who used a different token) will not get the message. Similarly, messages sent without any token, or with a different token, will not be delivered to that recipient.</param> </member> <member name="M:GalaSoft.MvvmLight.Messaging.Messenger.Unregister(System.Object)"> <summary> Unregisters a messager recipient completely. After this method is executed, the recipient will not receive any messages anymore. </summary> <param name="recipient">The recipient that must be unregistered.</param> </member> <member name="M:GalaSoft.MvvmLight.Messaging.Messenger.Unregister``1(System.Object)"> <summary> Unregisters a message recipient for a given type of messages only. After this method is executed, the recipient will not receive messages of type TMessage anymore, but will still receive other message types (if it registered for them previously). </summary> <param name="recipient">The recipient that must be unregistered.</param> <typeparam name="TMessage">The type of messages that the recipient wants to unregister from.</typeparam> </member> <member name="M:GalaSoft.MvvmLight.Messaging.Messenger.Unregister``1(System.Object,System.Object)"> <summary> Unregisters a message recipient for a given type of messages only and for a given token. After this method is executed, the recipient will not receive messages of type TMessage anymore with the given token, but will still receive other message types or messages with other tokens (if it registered for them previously). </summary> <param name="recipient">The recipient that must be unregistered.</param> <param name="token">The token for which the recipient must be unregistered.</param> <typeparam name="TMessage">The type of messages that the recipient wants to unregister from.</typeparam> </member> <member name="M:GalaSoft.MvvmLight.Messaging.Messenger.Unregister``1(System.Object,System.Action{``0})"> <summary> Unregisters a message recipient for a given type of messages and for a given action. Other message types will still be transmitted to the recipient (if it registered for them previously). Other actions that have been registered for the message type TMessage and for the given recipient (if available) will also remain available. </summary> <typeparam name="TMessage">The type of messages that the recipient wants to unregister from.</typeparam> <param name="recipient">The recipient that must be unregistered.</param> <param name="action">The action that must be unregistered for the recipient and for the message type TMessage.</param> </member> <member name="M:GalaSoft.MvvmLight.Messaging.Messenger.Unregister``1(System.Object,System.Object,System.Action{``0})"> <summary> Unregisters a message recipient for a given type of messages, for a given action and a given token. Other message types will still be transmitted to the recipient (if it registered for them previously). Other actions that have been registered for the message type TMessage, for the given recipient and other tokens (if available) will also remain available. </summary> <typeparam name="TMessage">The type of messages that the recipient wants to unregister from.</typeparam> <param name="recipient">The recipient that must be unregistered.</param> <param name="token">The token for which the recipient must be unregistered.</param> <param name="action">The action that must be unregistered for the recipient and for the message type TMessage.</param> </member> <member name="M:GalaSoft.MvvmLight.Messaging.Messenger.OverrideDefault(GalaSoft.MvvmLight.Messaging.Messenger)"> <summary> Provides a way to override the Messenger.Default instance with a custom instance, for example for unit testing purposes. </summary> <param name="newMessenger">The instance that will be used as Messenger.Default.</param> </member> <member name="M:GalaSoft.MvvmLight.Messaging.Messenger.Reset"> <summary> Sets the Messenger's default (static) instance to null. </summary> </member> <member name="P:GalaSoft.MvvmLight.Messaging.Messenger.Default"> <summary> Gets the Messenger's default instance, allowing to register and send messages in a static manner. </summary> </member> </members> </doc>
{ "pile_set_name": "Github" }
// @flow import React from 'react'; import noop from 'lodash/noop'; import SuggestedPill from './SuggestedPill'; import type { SuggestedPill as SuggestedPillType, SuggestedPills, SuggestedPillsFilter } from './flowTypes'; import './SuggestedPillsRow.scss'; type Props = { onSuggestedPillAdd?: SuggestedPillType => void, selectedPillsValues?: Array<number>, suggestedPillsData?: SuggestedPills, suggestedPillsFilter?: SuggestedPillsFilter, title?: string, }; const SuggestedPillsRow = ({ onSuggestedPillAdd = noop, selectedPillsValues = [], suggestedPillsData = [], suggestedPillsFilter = 'id', title, }: Props) => { // Prevents pills from being rendered that are in the form by checking for value (id or custom value) const filteredSuggestedPillData = suggestedPillsData.filter( item => !selectedPillsValues.includes(item[suggestedPillsFilter]), ); if (filteredSuggestedPillData.length === 0) { return null; } return ( <div className="pill-selector-suggested"> <span>{title}</span> {filteredSuggestedPillData.map(item => ( <SuggestedPill key={item.id} email={item.email} id={item.id} name={item.name} onAdd={onSuggestedPillAdd} /> ))} </div> ); }; export default SuggestedPillsRow;
{ "pile_set_name": "Github" }
#ifndef BT_CLIP_POLYGON_H_INCLUDED #define BT_CLIP_POLYGON_H_INCLUDED /*! \file btClipPolygon.h \author Francisco Leon Najera */ /* This source file is part of GIMPACT Library. For the latest info, see http://gimpact.sourceforge.net/ Copyright (c) 2007 Francisco Leon Najera. C.C. 80087371. email: [email protected] This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "LinearMath/btTransform.h" #include "LinearMath/btGeometryUtil.h" SIMD_FORCE_INLINE btScalar bt_distance_point_plane(const btVector4 & plane,const btVector3 &point) { return point.dot(plane) - plane[3]; } /*! Vector blending Takes two vectors a, b, blends them together*/ SIMD_FORCE_INLINE void bt_vec_blend(btVector3 &vr, const btVector3 &va,const btVector3 &vb, btScalar blend_factor) { vr = (1-blend_factor)*va + blend_factor*vb; } //! This function calcs the distance from a 3D plane SIMD_FORCE_INLINE void bt_plane_clip_polygon_collect( const btVector3 & point0, const btVector3 & point1, btScalar dist0, btScalar dist1, btVector3 * clipped, int & clipped_count) { bool _prevclassif = (dist0>SIMD_EPSILON); bool _classif = (dist1>SIMD_EPSILON); if(_classif!=_prevclassif) { btScalar blendfactor = -dist0/(dist1-dist0); bt_vec_blend(clipped[clipped_count],point0,point1,blendfactor); clipped_count++; } if(!_classif) { clipped[clipped_count] = point1; clipped_count++; } } //! Clips a polygon by a plane /*! *\return The count of the clipped counts */ SIMD_FORCE_INLINE int bt_plane_clip_polygon( const btVector4 & plane, const btVector3 * polygon_points, int polygon_point_count, btVector3 * clipped) { int clipped_count = 0; //clip first point btScalar firstdist = bt_distance_point_plane(plane,polygon_points[0]);; if(!(firstdist>SIMD_EPSILON)) { clipped[clipped_count] = polygon_points[0]; clipped_count++; } btScalar olddist = firstdist; for(int i=1;i<polygon_point_count;i++) { btScalar dist = bt_distance_point_plane(plane,polygon_points[i]); bt_plane_clip_polygon_collect( polygon_points[i-1],polygon_points[i], olddist, dist, clipped, clipped_count); olddist = dist; } //RETURN TO FIRST point bt_plane_clip_polygon_collect( polygon_points[polygon_point_count-1],polygon_points[0], olddist, firstdist, clipped, clipped_count); return clipped_count; } //! Clips a polygon by a plane /*! *\param clipped must be an array of 16 points. *\return The count of the clipped counts */ SIMD_FORCE_INLINE int bt_plane_clip_triangle( const btVector4 & plane, const btVector3 & point0, const btVector3 & point1, const btVector3& point2, btVector3 * clipped // an allocated array of 16 points at least ) { int clipped_count = 0; //clip first point0 btScalar firstdist = bt_distance_point_plane(plane,point0);; if(!(firstdist>SIMD_EPSILON)) { clipped[clipped_count] = point0; clipped_count++; } // point 1 btScalar olddist = firstdist; btScalar dist = bt_distance_point_plane(plane,point1); bt_plane_clip_polygon_collect( point0,point1, olddist, dist, clipped, clipped_count); olddist = dist; // point 2 dist = bt_distance_point_plane(plane,point2); bt_plane_clip_polygon_collect( point1,point2, olddist, dist, clipped, clipped_count); olddist = dist; //RETURN TO FIRST point0 bt_plane_clip_polygon_collect( point2,point0, olddist, firstdist, clipped, clipped_count); return clipped_count; } #endif // GIM_TRI_COLLISION_H_INCLUDED
{ "pile_set_name": "Github" }
:107E000001C0B7C0112484B790E89093610010922C :107E10006100882361F0982F9A70923041F081FFC1 :107E200002C097EF94BF282E80E0C6D0E9C085E05D :107E30008093810082E08093C80088E18093C9002C :107E400087E48093CC0086E08093CA008EE0B4D0B3 :107E5000279A84E02AEB3AEF91E030938500209353 :107E6000840096BBB09BFECF1F9AA8954091C80096 :107E700047FD02C0815089F793D0813479F490D0C6 :107E8000182FA0D0123811F480E004C088E0113817 :107E900009F083E07ED080E17CD0EECF823419F40B :107EA00084E198D0F8CF853411F485E0FACF853598 :107EB00041F476D0C82F74D0D82FCC0FDD1F82D0DC :107EC000EACF863519F484E085D0DECF843691F58B :107ED00067D066D0F82E64D0D82E00E011E05801AB :107EE0008FEFA81AB80A5CD0F80180838501FA10D8 :107EF000F6CF68D0F5E4DF1201C0FFCF50E040E0DC :107F000063E0CE0136D08E01E0E0F1E06F0182E067 :107F1000C80ED11C4081518161E0C8012AD00E5F9A :107F20001F4FF601FC10F2CF50E040E065E0CE01BB :107F300020D0B1CF843771F433D032D0F82E30D086 :107F400041D08E01F80185918F0123D0FA94F11070 :107F5000F9CFA1CF853739F435D08EE11AD085E934 :107F600018D081E197CF813509F0A9CF88E024D0DE :107F7000A6CFFC010A0167BFE895112407B600FCF3 :107F8000FDCF667029F0452B19F481E187BFE89594 :107F900008959091C80095FFFCCF8093CE0008957E :107FA0008091C80087FFFCCF8091C80084FD01C08C :107FB000A8958091CE000895E0E6F0E098E19083E6 :107FC00080830895EDDF803219F088E0F5DFFFCF80 :107FD00084E1DFCFCF93C82FE3DFC150E9F7CF9122 :027FE000F1CFDF :027FFE00000879 :0400000300007E007B :00000001FF
{ "pile_set_name": "Github" }
package algs.model.interval; import algs.model.IBinaryTreeNode; /** * Interface for constructing nodes in a Segment Tree. * <p> * Exposed in this way to enable individual SegmentTrees to have nodes that * store different pieces of information, yet need to construct nodes as needed. * * @author George Heineman * @version 1.0, 6/15/08 * @since 1.0 */ public interface IConstructor<T extends IBinaryTreeNode<T>> { /** * Instantiate the actual node. * * @param left left boundary of the range * @param right right boundary of the range * @return {@link SegmentTreeNode} object created in response to request */ SegmentTreeNode<T> construct(int left, int right); }
{ "pile_set_name": "Github" }
// go-libtor - Self-contained Tor from Go // Copyright (c) 2018 Péter Szilágyi. All rights reserved. package libtor /* #define DSO_NONE #define OPENSSLDIR "/usr/local/ssl" #define ENGINESDIR "/usr/local/lib/engines" #include <../crypto/evp/m_mdc2.c> */ import "C"
{ "pile_set_name": "Github" }
[ { "date": "2022-01-01 00:00:00", "start": "2022-01-01T03:00:00.000Z", "end": "2022-01-02T03:00:00.000Z", "name": "Ano Novo", "type": "public", "rule": "01-01", "_weekday": "Sat" }, { "date": "2022-02-26 00:00:00", "start": "2022-02-26T03:00:00.000Z", "end": "2022-03-02T17:00:00.000Z", "name": "Carnaval", "type": "optional", "rule": "easter -50 PT110H", "_weekday": "Sat" }, { "date": "2022-04-15 00:00:00", "start": "2022-04-15T03:00:00.000Z", "end": "2022-04-16T03:00:00.000Z", "name": "Sexta-Feira Santa", "type": "public", "rule": "easter -2", "_weekday": "Fri" }, { "date": "2022-04-17 00:00:00", "start": "2022-04-17T03:00:00.000Z", "end": "2022-04-18T03:00:00.000Z", "name": "Páscoa", "type": "observance", "rule": "easter", "_weekday": "Sun" }, { "date": "2022-04-21 00:00:00", "start": "2022-04-21T03:00:00.000Z", "end": "2022-04-22T03:00:00.000Z", "name": "Dia de Tiradentes", "type": "public", "rule": "04-21", "_weekday": "Thu" }, { "date": "2022-05-01 00:00:00", "start": "2022-05-01T03:00:00.000Z", "end": "2022-05-02T03:00:00.000Z", "name": "Dia do trabalhador", "type": "public", "rule": "05-01", "_weekday": "Sun" }, { "date": "2022-05-08 00:00:00", "start": "2022-05-08T03:00:00.000Z", "end": "2022-05-09T03:00:00.000Z", "name": "Dia das Mães", "type": "observance", "rule": "2nd sunday in May", "_weekday": "Sun" }, { "date": "2022-06-12 00:00:00", "start": "2022-06-12T03:00:00.000Z", "end": "2022-06-13T03:00:00.000Z", "name": "Dia dos Namorados", "type": "public", "rule": "06-12", "_weekday": "Sun" }, { "date": "2022-06-16 00:00:00", "start": "2022-06-16T03:00:00.000Z", "end": "2022-06-17T03:00:00.000Z", "name": "Corpo de Deus", "type": "optional", "rule": "easter 60", "_weekday": "Thu" }, { "date": "2022-07-26 00:00:00", "start": "2022-07-26T03:00:00.000Z", "end": "2022-07-27T03:00:00.000Z", "name": "Homenagem à memória do ex-presidente João Pessoa", "type": "public", "rule": "07-26", "_weekday": "Tue" }, { "date": "2022-08-05 00:00:00", "start": "2022-08-05T03:00:00.000Z", "end": "2022-08-06T03:00:00.000Z", "name": "Nossa Senhora das Neves", "type": "public", "note": "Fundação do Estado em 1585 e dia da sua padroeira", "rule": "08-05", "_weekday": "Fri" }, { "date": "2022-08-14 00:00:00", "start": "2022-08-14T03:00:00.000Z", "end": "2022-08-15T03:00:00.000Z", "name": "Dia dos Pais", "type": "observance", "rule": "2nd sunday in August", "_weekday": "Sun" }, { "date": "2022-09-07 00:00:00", "start": "2022-09-07T03:00:00.000Z", "end": "2022-09-08T03:00:00.000Z", "name": "Dia da Independência", "type": "public", "rule": "09-07", "_weekday": "Wed" }, { "date": "2022-10-02 00:00:00", "start": "2022-10-02T03:00:00.000Z", "end": "2022-10-03T03:00:00.000Z", "name": "Dia de Eleição", "type": "public", "rule": "1st sunday in October in even years", "_weekday": "Sun" }, { "date": "2022-10-12 00:00:00", "start": "2022-10-12T03:00:00.000Z", "end": "2022-10-13T03:00:00.000Z", "name": "Nossa Senhora Aparecida", "type": "public", "rule": "10-12", "_weekday": "Wed" }, { "date": "2022-10-30 00:00:00", "start": "2022-10-30T03:00:00.000Z", "end": "2022-10-31T03:00:00.000Z", "name": "Dia de Eleição", "type": "public", "rule": "1st sunday before 11-01 in even years", "_weekday": "Sun" }, { "date": "2022-11-02 00:00:00", "start": "2022-11-02T03:00:00.000Z", "end": "2022-11-03T03:00:00.000Z", "name": "Dia de Finados", "type": "public", "rule": "11-02", "_weekday": "Wed" }, { "date": "2022-11-15 00:00:00", "start": "2022-11-15T03:00:00.000Z", "end": "2022-11-16T03:00:00.000Z", "name": "Proclamação da República", "type": "public", "rule": "11-15", "_weekday": "Tue" }, { "date": "2022-12-24 14:00:00", "start": "2022-12-24T17:00:00.000Z", "end": "2022-12-25T03:00:00.000Z", "name": "Noite de Natal", "type": "optional", "rule": "12-24 14:00", "_weekday": "Sat" }, { "date": "2022-12-25 00:00:00", "start": "2022-12-25T03:00:00.000Z", "end": "2022-12-26T03:00:00.000Z", "name": "Natal", "type": "public", "rule": "12-25", "_weekday": "Sun" }, { "date": "2022-12-31 14:00:00", "start": "2022-12-31T17:00:00.000Z", "end": "2023-01-01T03:00:00.000Z", "name": "Véspera de Ano Novo", "type": "optional", "rule": "12-31 14:00", "_weekday": "Sat" } ]
{ "pile_set_name": "Github" }
#!/bin/bash echo removing: find . -path ./node_modules -prune -o \( -name \*~ -type f -print -exec rm {} \; \)
{ "pile_set_name": "Github" }
5 Aug 2013 - This library is no longer supported or maintained. A more recent Clickatell library can be found here https://github.com/xploshioOn/clickatellsend h1. Clickatell SMS Library To use this gem, you will need sign up for an account at www.clickatell.com. Once you are registered and logged into your account centre, you should add an HTTP API connection to your account. This will give you your API_ID. h2. Basic Usage You will need your API_ID as well as your account username and password. <pre> <code> require 'rubygems' require 'clickatell' api = Clickatell::API.authenticate('your_api_id', 'your_username', 'your_password') api.send_message('447771234567', 'Hello from clickatell') </code> </pre> To send a message to multiple recipients, simply pass in an array of numbers. <pre> <code> api.send_message(['447771234567', '447771234568'], 'Hello from clickatell') </code> </pre> h2. HTTP Proxy You can configure the library to use a HTTP proxy when communicating with Clickatell. <pre> <code> Clickatell::API.proxy_host = 'my.proxy.com' Clickatell::API.proxy_port = 1234 Clickatell::API.proxy_username = 'joeschlub' Clickatell::API.proxy_password = 'secret' </code> </pre> h2. Command-line SMS Utility The Clickatell gem also comes with a command-line utility that will allow you to send an SMS directly from the command-line. You will need to create a YAML configuration file in your home directory, in a file called .clickatell that resembles the following: <pre> <code> # ~/.clickatell api_key: your_api_id username: your_username password: your_password </code> </pre> You can then use the sms utility to send a message to a single recipient: <pre> <code> sms 447771234567 'Hello from clickatell' </code> </pre> Alternatively, you can specify the username and password as a command line option. Run +sms+ without any arguments for a full list of options. The sms utility also supports multiple, comma-separated recipients (up to 100). <pre> <code> sms 447771111111,447772222222 "Hello everyone" </code> </pre> See http://clickatell.rubyforge.org for further instructions.
{ "pile_set_name": "Github" }
using System.Collections.Generic; namespace Cake.Core { /// <summary> /// Acts as a context providing info about the overall build before its started. /// </summary> public interface ISetupContext : ICakeContext { /// <summary> /// Gets target (initiating) task. /// </summary> ICakeTaskInfo TargetTask { get; } /// <summary> /// Gets all registered tasks that are going to be executed. /// </summary> IReadOnlyCollection<ICakeTaskInfo> TasksToExecute { get; } } }
{ "pile_set_name": "Github" }
±²³SolveSpaceREVa Group.h.v=00000001 Group.type=5000 Group.name=#references Group.color=ff000000 Group.skipFirst=0 Group.predef.swapUV=0 Group.predef.negateU=0 Group.predef.negateV=0 Group.visible=1 Group.suppress=0 Group.relaxConstraints=0 Group.allowRedundant=0 Group.allDimsReference=0 Group.scale=1.00000000000000000000 Group.remap={ } AddGroup Group.h.v=00000002 Group.type=5001 Group.order=1 Group.name=sketch-in-plane Group.activeWorkplane.v=80020000 Group.color=ff000000 Group.subtype=6000 Group.skipFirst=0 Group.predef.q.w=1.00000000000000000000 Group.predef.origin.v=00010001 Group.predef.swapUV=0 Group.predef.negateU=0 Group.predef.negateV=0 Group.visible=1 Group.suppress=0 Group.relaxConstraints=0 Group.allowRedundant=0 Group.allDimsReference=0 Group.scale=1.00000000000000000000 Group.remap={ } AddGroup Param.h.v.=00010010 AddParam Param.h.v.=00010011 AddParam Param.h.v.=00010012 AddParam Param.h.v.=00010020 Param.val=1.00000000000000000000 AddParam Param.h.v.=00010021 AddParam Param.h.v.=00010022 AddParam Param.h.v.=00010023 AddParam Param.h.v.=00020010 AddParam Param.h.v.=00020011 AddParam Param.h.v.=00020012 AddParam Param.h.v.=00020020 Param.val=0.50000000000000000000 AddParam Param.h.v.=00020021 Param.val=0.50000000000000000000 AddParam Param.h.v.=00020022 Param.val=0.50000000000000000000 AddParam Param.h.v.=00020023 Param.val=0.50000000000000000000 AddParam Param.h.v.=00030010 AddParam Param.h.v.=00030011 AddParam Param.h.v.=00030012 AddParam Param.h.v.=00030020 Param.val=0.50000000000000000000 AddParam Param.h.v.=00030021 Param.val=-0.50000000000000000000 AddParam Param.h.v.=00030022 Param.val=-0.50000000000000000000 AddParam Param.h.v.=00030023 Param.val=-0.50000000000000000000 AddParam Param.h.v.=00040010 Param.val=-10.00000000000000000000 AddParam Param.h.v.=00040011 Param.val=10.00000000000000000000 AddParam Param.h.v.=00040040 Param.val=5.00000000000000000000 AddParam Request.h.v=00000001 Request.type=100 Request.group.v=00000001 Request.construction=0 AddRequest Request.h.v=00000002 Request.type=100 Request.group.v=00000001 Request.construction=0 AddRequest Request.h.v=00000003 Request.type=100 Request.group.v=00000001 Request.construction=0 AddRequest Request.h.v=00000004 Request.type=400 Request.workplane.v=80020000 Request.group.v=00000002 Request.construction=0 AddRequest Entity.h.v=00010000 Entity.type=10000 Entity.construction=0 Entity.point[0].v=00010001 Entity.normal.v=00010020 Entity.actVisible=1 AddEntity Entity.h.v=00010001 Entity.type=2000 Entity.construction=1 Entity.actVisible=1 AddEntity Entity.h.v=00010020 Entity.type=3000 Entity.construction=0 Entity.point[0].v=00010001 Entity.actNormal.w=1.00000000000000000000 Entity.actVisible=1 AddEntity Entity.h.v=00020000 Entity.type=10000 Entity.construction=0 Entity.point[0].v=00020001 Entity.normal.v=00020020 Entity.actVisible=1 AddEntity Entity.h.v=00020001 Entity.type=2000 Entity.construction=1 Entity.actVisible=1 AddEntity Entity.h.v=00020020 Entity.type=3000 Entity.construction=0 Entity.point[0].v=00020001 Entity.actNormal.w=0.50000000000000000000 Entity.actNormal.vx=0.50000000000000000000 Entity.actNormal.vy=0.50000000000000000000 Entity.actNormal.vz=0.50000000000000000000 Entity.actVisible=1 AddEntity Entity.h.v=00030000 Entity.type=10000 Entity.construction=0 Entity.point[0].v=00030001 Entity.normal.v=00030020 Entity.actVisible=1 AddEntity Entity.h.v=00030001 Entity.type=2000 Entity.construction=1 Entity.actVisible=1 AddEntity Entity.h.v=00030020 Entity.type=3000 Entity.construction=0 Entity.point[0].v=00030001 Entity.actNormal.w=0.50000000000000000000 Entity.actNormal.vx=-0.50000000000000000000 Entity.actNormal.vy=-0.50000000000000000000 Entity.actNormal.vz=-0.50000000000000000000 Entity.actVisible=1 AddEntity Entity.h.v=00040000 Entity.type=13000 Entity.construction=0 Entity.point[0].v=00040001 Entity.normal.v=00040020 Entity.distance.v=00040040 Entity.workplane.v=80020000 Entity.actVisible=1 AddEntity Entity.h.v=00040001 Entity.type=2001 Entity.construction=0 Entity.workplane.v=80020000 Entity.actPoint.x=-10.00000000000000000000 Entity.actPoint.y=10.00000000000000000000 Entity.actVisible=1 AddEntity Entity.h.v=00040020 Entity.type=3001 Entity.construction=0 Entity.point[0].v=00040001 Entity.workplane.v=80020000 Entity.actNormal.w=1.00000000000000000000 Entity.actVisible=1 AddEntity Entity.h.v=00040040 Entity.type=4000 Entity.construction=0 Entity.workplane.v=80020000 Entity.actDistance=5.00000000000000000000 Entity.actVisible=1 AddEntity Entity.h.v=80020000 Entity.type=10000 Entity.construction=0 Entity.point[0].v=80020002 Entity.normal.v=80020001 Entity.actVisible=1 AddEntity Entity.h.v=80020001 Entity.type=3010 Entity.construction=0 Entity.point[0].v=80020002 Entity.actNormal.w=1.00000000000000000000 Entity.actVisible=1 AddEntity Entity.h.v=80020002 Entity.type=2012 Entity.construction=1 Entity.actVisible=1 AddEntity Constraint.h.v=00000001 Constraint.type=90 Constraint.group.v=00000002 Constraint.workplane.v=80020000 Constraint.valA=10.00000000000000000000 Constraint.entityA.v=00040000 Constraint.other=0 Constraint.other2=0 Constraint.reference=0 Constraint.disp.offset.x=5.00000000000000000000 Constraint.disp.offset.y=5.00000000000000000000 AddConstraint
{ "pile_set_name": "Github" }
/* * Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.max.annotate; import java.lang.annotation.*; import com.sun.max.vm.jni.*; /** * Denotes a <i>private static native</i> method whose stub is lighter than a standard JNI stub. In particular, * the {@link NativeStubGenerator native stub} generated for such methods will: * <ul> * <li>marshal only the parameters explicit in the Java signature for the native function call (i.e. the JniEnv and * jclass parameters are omitted)</li> * </ul> * <p> * No parameter type or return type of VM entry or exit points may refer to object references - only primitive Java * values and 'Word' values are allowed. * <p> * This annotation should <b>never</b> be used for calling native code that can block. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface C_FUNCTION { }
{ "pile_set_name": "Github" }
package io.renren.utils.aop; import com.alibaba.fastjson.JSON; import io.renren.utils.annotation.SysLog; import io.renren.entity.SysLogEntity; import io.renren.service.SysLogService; import io.renren.utils.HttpContextUtils; import io.renren.utils.IPUtils; import io.renren.utils.ShiroUtils; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import java.lang.reflect.Method; import java.util.Date; /** * 系统日志,切面处理类 * * @author chenshun * @email [email protected] * @date 2017年3月8日 上午11:07:35 */ @Aspect @Component public class SysLogAspect { @Autowired private SysLogService sysLogService; @Pointcut("@annotation(io.renren.utils.annotation.SysLog)") public void logPointCut() { } @Before("logPointCut()") public void saveSysLog(JoinPoint joinPoint) { MethodSignature signature = (MethodSignature) joinPoint.getSignature(); Method method = signature.getMethod(); SysLogEntity sysLog = new SysLogEntity(); SysLog syslog = method.getAnnotation(SysLog.class); if(syslog != null){ //注解上的描述 sysLog.setOperation(syslog.value()); } //请求的方法名 String className = joinPoint.getTarget().getClass().getName(); String methodName = signature.getName(); sysLog.setMethod(className + "." + methodName + "()"); //请求的参数 Object[] args = joinPoint.getArgs(); String params = JSON.toJSONString(args[0]); sysLog.setParams(params); //获取request HttpServletRequest request = HttpContextUtils.getHttpServletRequest(); //设置IP地址 sysLog.setIp(IPUtils.getIpAddr(request)); //用户名 String username = ShiroUtils.getUserEntity().getUsername(); sysLog.setUsername(username); sysLog.setCreateDate(new Date()); //保存系统日志 sysLogService.save(sysLog); } }
{ "pile_set_name": "Github" }
/* Copyright 2018-present MongoDB 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. */ namespace MongoDB.Driver.Core.WireProtocol.Messages.Encoders { /// <summary> /// Represents the changes that can be made to a message after it has been encoded. /// </summary> public interface IMessageEncoderPostProcessor { /// <summary> /// Changes the write concern from w0 to w1. /// </summary> void ChangeWriteConcernFromW0ToW1(); } }
{ "pile_set_name": "Github" }
config BR2_PACKAGE_XAVANTE bool "xavante" # Runtime dependency only select BR2_PACKAGE_CGILUA select BR2_PACKAGE_COPAS select BR2_PACKAGE_COXPCALL select BR2_PACKAGE_LUAFILESYSTEM select BR2_PACKAGE_LUASOCKET select BR2_PACKAGE_WSAPI help Xavante is a Lua HTTP 1.1 Web server that uses a modular architecture based on URI mapped handlers. http://keplerproject.github.com/xavante/
{ "pile_set_name": "Github" }
parameters: BuildConfiguration: release BuildPlatform: any cpu Architecture: x64 jobs: - job: build_windows_${{ parameters.Architecture }} displayName: Build Windows - ${{ parameters.Architecture }} condition: succeeded() pool: name: Package ES Standard Build variables: BuildConfiguration: ${{ parameters.BuildConfiguration }} BuildPlatform: ${{ parameters.BuildPlatform }} Architecture: ${{ parameters.Architecture }} steps: - checkout: self clean: true persistCredentials: true - template: shouldSign.yml - template: SetVersionVariables.yml parameters: ReleaseTagVar: $(ReleaseTagVar) - task: PkgESSetupBuild@10 displayName: 'Initialize build' env: SYSTEM_ACCESSTOKEN: $(System.AccessToken) inputs: useDfs: false productName: PowerShellCore branchVersion: true disableWorkspace: true disableBuildTools: true disableNugetPack: true condition: and(succeeded(), eq(variables['SHOULD_SIGN'], 'true')) - template: insert-nuget-config-azfeed.yml - powershell: | docker container prune --force docker container ls --all --format '{{ json .ID }}' | ConvertFrom-Json | ForEach-Object {docker container rm --force --volumes $_} displayName: 'Remove all containers [Port to PSRelease]' # Cleanup is not critical it passes every time it runs continueOnError: true - powershell: | docker image ls --format '{{ json .}}'|ConvertFrom-Json| ForEach-Object { if($_.tag -eq '<none>') { $formatString = 'yyyy-MM-dd HH:mm:ss zz00' $createdAtString = $_.CreatedAt.substring(0,$_.CreatedAt.Length -4) $createdAt = [DateTime]::ParseExact($createdAtString, $formatString,[System.Globalization.CultureInfo]::InvariantCulture) if($createdAt -lt (Get-Date).adddays(-1)) { docker image rm $_.ID } } } exit 0 displayName: 'Remove old images [Port to PSRelease]' # Cleanup is not critical it passes every time it runs continueOnError: true - powershell: | Write-verbose "--docker info---" -verbose docker info Write-verbose "--docker image ls---" -verbose docker image ls Write-verbose "--docker container ls --all---" -verbose docker container ls --all exit 0 displayName: 'Capture docker info' # Diagnostics is not critical it passes every time it runs continueOnError: true - powershell: | tools/releaseBuild/vstsbuild.ps1 -ReleaseTag $(ReleaseTagVar) -Name win-$(Architecture)-symbols displayName: 'Build Windows Universal - $(Architecture) Symbols zip' - powershell: | if ("$env:Architecture" -like 'fxdependent*') { $(Build.SourcesDirectory)\tools\releaseBuild\updateSigning.ps1 -SkipPwshExe } else { $(Build.SourcesDirectory)\tools\releaseBuild\updateSigning.ps1 } displayName: 'Update Signing Xml' - powershell: | $vstsCommandString = "vso[task.setvariable variable=Symbols]${env:Symbols_$(Architecture)}" Write-Host "sending " + $vstsCommandString Write-Host "##$vstsCommandString" displayName: 'Get Symbols path [Update build.json]' - task: PkgESCodeSign@10 displayName: 'CodeSign $(Architecture)' env: SYSTEM_ACCESSTOKEN: $(System.AccessToken) inputs: signConfigXml: '$(Build.SourcesDirectory)\tools\releaseBuild\signing.xml' inPathRoot: '$(Symbols)' outPathRoot: '$(Symbols)\signed' binVersion: $(SigingVersion) binVersionOverride: $(SigningVersionOverride) condition: and(succeeded(), eq(variables['SHOULD_SIGN'], 'true')) - powershell: | New-Item -ItemType Directory -Path $(Symbols)\signed -Force displayName: 'Create empty signed folder' condition: and(succeeded(), ne(variables['SHOULD_SIGN'], 'true')) - powershell: | tools/releaseBuild/vstsbuild.ps1 -ReleaseTag $(ReleaseTagVar) -Name win-$(Architecture)-package -BuildPath $(Symbols) -SignedFilesPath $(Symbols)\signed displayName: 'Build Windows Universal - $(Architecture) Package' - task: ms.vss-governance-buildtask.governance-build-task-component-detection.ComponentGovernanceComponentDetection@0 displayName: 'Component Detection' inputs: sourceScanPath: '$(Build.SourcesDirectory)' snapshotForceEnabled: true
{ "pile_set_name": "Github" }
<div id="automation_domain" class="hg-popup-b" data-role="popup" data-position-to="window" data-overlay-theme="b"> <a href="#" data-rel="back" class="ui-btn ui-corner-all ui-shadow ui-icon-delete ui-btn-icon-notext ui-btn-right">Close</a> <div data-role="header"> <h1>Wizard (1/5)</h1> </div> <div class="ui-content ui-corner-bottom"> <div> <p data-locale-id="configure_program_selectconditioncontext" style="margin-top:-10px;font-weight:bold">Select condition context</p> <p id="condition_wizard_text" style="font-family:courier;font-size:9pt;margin:0px;margin-top:-10px;margin-bottom:10px;height:70px;"></p> </div> <ul id="automation_conditiontarget" data-role="listview" data-inset="false" style="height:180px;max-height:180px;overflow-y:scroll;overflow-x:hidden;"> <li data-context-value="HomeAutomation.HomeGenie"><a data-rel="popup" href="#automation_target_popup">HomeGenie</a></li> </ul> </div> <div data-role="footer" data-tap-toggle="false"> <div class="ui-grid-a" align="center"> <div class="ui-block-a"> <a data-locale-id="configure_program_deletecancel" data-rel="back" class="ui-btn ui-icon-back ui-btn-icon-left ui-corner-all" href="#">Cancel</a> </div> <div class="ui-block-b"> <a data-locale-id="configure_program_oroperator" id="condition_add_oroperator" class="ui-btn ui-icon-plus ui-btn-icon-left ui-corner-all" href="#cancel">OR operator</a> </div> </div> </div> </div> <div id="automation_target_popup" class="hg-popup-b" data-role="popup" data-position-to="window" data-overlay-theme="b"> <a href="#" data-rel="back" class="ui-btn ui-corner-all ui-shadow ui-icon-delete ui-btn-icon-notext ui-btn-right">Close</a> <div data-role="header"><h1>Wizard (2/5)</h1></div> <div class="ui-content ui-corner-bottom"> <div> <p data-locale-id="configure_program_selectconditionsubject" style="margin-top:-10px;font-weight:bold">Select condition subject</p> <p id="condition_wizard_text" style="font-family:courier;font-size:9pt;margin:0px;margin-top:-10px;margin-bottom:10px;height:70px;"></p> </div> <ul id="automation_condition_target" data-role="listview" data-inset="false" style="height:180px;max-height:180px;overflow-y:scroll;overflow-x:hidden;"></ul> </div> <div data-role="footer" data-tap-toggle="false"> <div class="ui-grid-a" align="center"> <div class="ui-block-a"> <a onclick="HG.Ui.SwitchPopup('#automation_target_popup', '#automation_domain', true)" class="ui-btn ui-icon-back ui-btn-icon-left ui-corner-all" data-locale-id="configure_program_wizardback">Back</a> </div> </div> </div> </div> <div id="automation_target_homegenie_parameter" class="hg-popup-b" data-position-to="window" data-role="popup" data-overlay-theme="b"> <a href="#" data-rel="back" class="ui-btn ui-corner-all ui-shadow ui-icon-delete ui-btn-icon-notext ui-btn-right">Close</a> <div data-role="header"><h1>Wizard (3/5)</h1></div> <div class="ui-content ui-corner-bottom"> <div> <p data-locale-id="configure_program_selectconditionproperty" style="margin-top:-10px;font-weight:bold">Select comparison property</p> <p id="condition_wizard_text" style="font-family:courier;font-size:9pt;margin:0px;margin-top:-10px;margin-bottom:10px;height:70px;"></p> </div> <ul id="automation_condition_property" data-role="listview" data-inset="false" style="height:180px;max-height:180px;overflow-y:scroll;overflow-x:hidden;"></ul> </div> <div data-role="footer" data-tap-toggle="false"> <div class="ui-grid-a" align="center"> <div class="ui-block-a"> <a onclick="HG.Ui.SwitchPopup('#automation_target_homegenie_parameter', '#automation_target_popup', true)" class="ui-btn ui-icon-back ui-btn-icon-left ui-corner-all" data-locale-id="configure_program_wizardback">Back</a> </div> </div> </div> </div> <div id="automation_condition_type" class="hg-popup-b" data-position-to="window" data-role="popup" data-overlay-theme="b"> <a href="#" data-rel="back" class="ui-btn ui-corner-all ui-shadow ui-icon-delete ui-btn-icon-notext ui-btn-right">Close</a> <div data-role="header"><h1>Wizard (4/5)</h1></div> <div class="ui-content ui-corner-bottom"> <div> <p data-locale-id="configure_program_selectoperator" style="margin-top:-10px;font-weight:bold">Select comparison operator</p> <p id="condition_wizard_text" style="font-family:courier;font-size:9pt;margin:0px;margin-top:-10px;margin-bottom:10px;height:70px;"></p> </div> <ul data-role="listview" data-inset="false" style="height:180px;max-height:180px;"> <li data-context-value="LessThan" id="configure_program_conditionlessthan"><a data-locale-id="configure_program_operatorless" data-rel="popup" href="#automation_condition_value">Less Than</a></li> <li data-context-value="Equals"><a data-locale-id="configure_program_operatorequal" data-rel="popup" href="#automation_condition_value">Equals</a></li> <li data-context-value="GreaterThan" id="configure_program_conditiongreaterthan"><a data-locale-id="configure_program_operatorgreaterthan" data-rel="popup" href="#automation_condition_value">Greater Than</a></li> </ul> </div> <div data-role="footer" data-tap-toggle="false"> <div class="ui-grid-a" align="center"> <div class="ui-block-a"> <a onclick="HG.Ui.SwitchPopup('#automation_condition_type', '#automation_target_homegenie_parameter', true)" class="ui-btn ui-icon-back ui-btn-icon-left ui-corner-all" data-locale-id="configure_program_wizardback">Back</a> </div> </div> </div> </div> <div id="automation_condition_value" class="hg-popup-b" data-position-to="window" data-role="popup" data-overlay-theme="b"> <a href="#" data-rel="back" class="ui-btn ui-corner-all ui-shadow ui-icon-delete ui-btn-icon-notext ui-btn-right">Close</a> <div data-role="header"><h1>Wizard (5/5)</h1></div> <div class="ui-content ui-corner-bottom"> <div> <p data-locale-id="configure_program_selectvalue" style="margin-top:-10px;font-weight:bold">Select comparison value</p> <p id="condition_wizard_text" style="font-family:courier;font-size:9pt;margin:0px;margin-top:-10px;margin-bottom:10px;height:70px;"></p> </div> <fieldset data-role="controlgroup" data-type="vertical" style="height:134px;max-height:134px;"> <input type="text" name="value" id="comparison_value_input" onkeyup="build_condition()" value="" placeholder="value" /> <a onclick="HG.Ui.SwitchPopup('#automation_condition_value', '#automation_condition_value_domain', true)" class="ui-btn ui-corner-all">Module Parameter Value</a> </fieldset> </div> <div data-role="footer" data-tap-toggle="false"> <div class="ui-grid-a" align="center"> <div class="ui-block-a"> <a onclick="HG.Ui.SwitchPopup('#automation_condition_value', '#automation_condition_type', true)" class="ui-btn ui-icon-back ui-btn-icon-left ui-corner-all" data-locale-id="configure_program_wizardback">Back</a> </div> <div class="ui-block-b"> <a data-locale-id="configure_program_wizarddone" id="condition_completed" class="ui-btn ui-icon-check ui-btn-icon-left ui-corner-all" href="#cancel">Done</a> </div> </div> </div> </div> <div id="automation_condition_value_domain" class="hg-popup-b" data-position-to="window" data-role="popup" data-overlay-theme="b"> <a href="#" data-rel="back" class="ui-btn ui-corner-all ui-shadow ui-icon-delete ui-btn-icon-notext ui-btn-right">Close</a> <div data-role="header"><h1>Wizard (5/5)</h1></div> <div class="ui-content ui-corner-bottom"> <div> <p data-locale-id="configure_program_selectvalue" style="margin-top:-10px;font-weight:bold">Select comparison value</p> <p id="condition_wizard_text" style="font-family:courier;font-size:9pt;margin:0px;margin-top:-10px;margin-bottom:10px;height:70px;"></p> </div> <ul id="automation_conditionvalue_domain" data-role="listview" data-inset="false" style="height:180px;max-height:180px;overflow-y:scroll;overflow-x:hidden;"> <li data-context-value="HomeAutomation.HomeGenie"><a data-rel="popup" href="#automation_target_popup">HomeGenie</a></li> </ul> </div> <div data-role="footer" data-tap-toggle="false"> <div class="ui-grid-a" align="center"> <div class="ui-block-a"> <a onclick="HG.Ui.SwitchPopup('#automation_condition_value_domain', '#automation_condition_value', true)" class="ui-btn ui-icon-back ui-btn-icon-left ui-corner-all" data-locale-id="configure_program_wizardback">Back</a> </div> </div> </div> </div> <div id="automation_condition_value_address" class="hg-popup-b" data-position-to="window" data-role="popup" data-overlay-theme="b"> <a href="#" data-rel="back" class="ui-btn ui-corner-all ui-shadow ui-icon-delete ui-btn-icon-notext ui-btn-right">Close</a> <div data-role="header"><h1>Wizard (5/5)</h1></div> <div class="ui-content ui-corner-bottom"> <div> <p data-locale-id="configure_program_selectvalue" style="margin-top:-10px;font-weight:bold">Select comparison value</p> <p id="condition_wizard_text" style="font-family:courier;font-size:9pt;margin:0px;margin-top:-10px;margin-bottom:10px;height:70px;"></p> </div> <ul id="automation_conditionvalue_address" data-role="listview" data-inset="false" style="height:180px;max-height:180px;overflow-y:scroll;overflow-x:hidden;"></ul> </div> <div data-role="footer" data-tap-toggle="false"> <div class="ui-grid-a"> <div class="ui-block-a" align="center"> <a onclick="HG.Ui.SwitchPopup('#automation_condition_value_address', '#automation_condition_value_domain', true)" class="ui-btn ui-icon-back ui-btn-icon-left ui-corner-all" data-locale-id="configure_program_wizardback">Back</a> </div> </div> </div> </div> <div id="automation_condition_value_property" class="hg-popup-b" data-position-to="window" data-role="popup" data-overlay-theme="b"> <a href="#" data-rel="back" class="ui-btn ui-corner-all ui-shadow ui-icon-delete ui-btn-icon-notext ui-btn-right">Close</a> <div data-role="header"><h1>Wizard (5/5)</h1></div> <div class="ui-content ui-corner-bottom"> <div> <p data-locale-id="configure_program_selectvalue" style="margin-top:-10px;font-weight:bold">Select comparison value</p> <p id="condition_wizard_text" style="font-family:courier;font-size:9pt;margin:0px;margin-top:-10px;margin-bottom:10px;height:70px;"></p> </div> <ul id="automation_conditionvalue_property" data-role="listview" data-inset="false" style="height:180px;max-height:180px;overflow-y:scroll;overflow-x:hidden;"></ul> </div> <div data-role="footer" data-tap-toggle="false"> <div class="ui-grid-a" align="center"> <div class="ui-block-a"> <a onclick="HG.Ui.SwitchPopup('#automation_condition_value_property', '#automation_condition_value_address', true)" class="ui-btn ui-icon-back ui-btn-icon-left ui-corner-all" data-locale-id="configure_program_wizardback">Back</a> </div> </div> </div> </div> <div id="automation_capture_condition_popup" class="ui-corner-all hg-popup-a" data-role="popup" data-position-to="window" data-overlay-theme="b" data-transition="pop"> <div data-role="header" class="ui-corner-top"> <h1 data-locale-id="configure_program_conditioncapturetitle">Capturing Conditions</h1> </div> <div class="ui-content ui-corner-bottom"> <h3 data-locale-id="configure_program_waitingnewcondition" class="ui-title">Waiting for new events...</h3> <p data-locale-id="configure_program_waitingnewconditionadvice"></p> <a data-locale-id="configure_program_capturestop" href="#" class="ui-btn ui-corner-all" data-inline="true" data-rel="back">Stop</a> </div> </div> <div id="automation_condition_delete" class="ui-corner-all hg-popup-a" data-role="popup" data-transition="pop" data-overlay-theme="b"> <div data-role="header" class="ui-corner-top"> <h1 data-locale-id="configure_program_wizard_editline_title">Edit Line</h1> </div> <div class="ui-content ui-corner-bottom"> <p data-locale-id="configure_program_wizard_editconline_prompt">Move or delete line <span id="condition_linenumber_label" style="font-weight:bold"></span></p> <ul data-role="listview" data-inset="true"> <li> <label data-locale-id="configure_program_wizard_editline_number" for="condition_linenumber_input">New line number</label> <input id="condition_linenumber_input" type="range" min="1" max="1" name="value" value="1" placeholder="line number" /> </li> </ul> <div class="ui-grid-a"> <div class="ui-block-a"> <a data-locale-id="configure_program_wizard_editline_delete" id="condition_delete_button" href="#" class="ui-btn ui-corner-all" data-rel="back" data-transition="flow">Delete</a> </div> <div class="ui-block-b"> <a data-locale-id="configure_program_wizard_editline_change" id="condition_move_button" href="#" class="ui-btn ui-corner-all" data-rel="back" data-transition="flow">Move</a> </div> </div> </div> </div> <script type="text/javascript"> // var condition_targetdomain = ''; var condition_targetsubject = ''; var condition_targetparameter = ''; var condition_type = ''; var condition_value = ''; // var selected_condition_index = -1; // $(document).ready(function (e) { // // automation pop wizard popups $('#automation_domain').on('popupbeforeposition', function (event) { condition_targetdomain = ''; condition_targetsubject = ''; condition_targetparameter = ''; condition_type = ''; condition_value = ''; // $('#comparison_value_input').val(''); // build_condition(); }); $('#automation_target_popup').on('popupbeforeposition', function (event) { $('#automation_condition_target').listview().empty(); // switch (condition_targetdomain) { case 'HomeAutomation.HomeGenie': $('#automation_condition_target').append('<li data-context-value="Scheduler"><a>Scheduler</a></li>'); break; default: $('#automation_condition_target').append(automationpage_GetModulesListViewItems(condition_targetdomain, false)); break; } $('#automation_condition_target').listview('refresh'); // build_condition(); }); $('#automation_target_homegenie_parameter').on('popupbeforeposition', function (event) { $('#automation_condition_property').listview().empty(); // var module = HG.WebApp.Utility.GetModuleByDomainAddress(condition_targetdomain, condition_targetsubject); if (module != null && (module.Address == "RF" || module.Address == "IR")) { $('#automation_condition_property').append('<li data-context-value="Receiver.RawData"><a>Receiver.RawData</a></li>'); } else { switch (condition_targetdomain) { case 'HomeAutomation.HomeGenie': //$('#automation_condition_property').append('<li data-context-value="Meter.WattsCounter"><a>Meter.WattsCounter</a></li>'); //$('#automation_condition_property').append('<li data-context-value="Meter.WattsLoad"><a>Meter.WattsLoad</a></li>'); //$('#automation_condition_property').append('<li data-context-value="Scheduler.TimeEvent"><a>Scheduler.TimeEvent</a></li>'); //$('#automation_condition_property').append('<li data-context-value="Scheduler.TriggeredEvent"><a>Scheduler.TriggeredEvent</a></li>'); $('#automation_condition_property').append('<li data-context-value="Scheduler.CronEvent"><a>Scheduler.CronEvent</a></li>'); $('#automation_condition_property').append('<li data-context-value="Scheduler.Date"><a>Scheduler.Date</a></li>'); $('#automation_condition_property').append('<li data-context-value="Scheduler.Time"><a>Scheduler.Time</a></li>'); $('#automation_condition_property').append('<li data-context-value="Scheduler.DateTime"><a>Scheduler.DateTime</a></li>'); $('#automation_condition_property').append('<li data-context-value="Scheduler.DateDay"><a>Scheduler.DateDay</a></li>'); $('#automation_condition_property').append('<li data-context-value="Scheduler.DateMonth"><a>Scheduler.DateMonth</a></li>'); $('#automation_condition_property').append('<li data-context-value="Scheduler.DateYear"><a>Scheduler.DateYear</a></li>'); $('#automation_condition_property').append('<li data-context-value="Scheduler.DateDayOfWeek"><a>Scheduler.DateDayOfWeek</a></li>'); $('#automation_condition_property').append('<li data-context-value="Scheduler.DateHour"><a>Scheduler.DateHour</a></li>'); $('#automation_condition_property').append('<li data-context-value="Scheduler.DateMinute"><a>Scheduler.DateMinute</a></li>'); //$('#automation_condition_property').append('<li data-context-value="Security.ArmedStatus"><a>Security.ArmedStatus</a></li>'); break; default: if (module != null) { var comparable_props = HG.WebApp.ProgramEdit.GetModuleComparableProperties(module); for (var p = 0; p < comparable_props.length; p++) { var prop = comparable_props[p]; $('#automation_condition_property').append('<li data-context-value="' + prop.Name + '"><a>' + prop.Name + '</a></li>'); } } break; } } $('#automation_condition_property').listview('refresh'); // build_condition(); }); $('#automation_condition_type').on('popupbeforeposition', function (event) { if (condition_targetparameter == 'Scheduler.TimeEvent' || condition_targetparameter == 'Receiver.RawData') { $('#configure_program_conditionlessthan').hide(); $('#configure_program_conditiongreaterthan').hide(); } else { $('#configure_program_conditionlessthan').show(); $('#configure_program_conditiongreaterthan').show(); } // build_condition(); }); $('#automation_condition_value').on('popupbeforeposition', function (event) { $('#comparison_value_input').val(condition_value); build_command(); }); $('#automation_condition_delete').on('popupbeforeposition', function (event) { $('#condition_linenumber_label').html('#' + (selected_condition_index + 1)); $('#condition_linenumber_input').val(selected_condition_index + 1); $('#condition_linenumber_input').attr('max', HG.WebApp.ProgramEdit._CurrentProgram.Conditions.length); $('#condition_linenumber_input').slider('refresh'); }); //$('#automation_program_conditions').on('click', ' > li', function () { // selected_condition_index = $(this).index(); //}); $('#condition_delete_button').bind('click', function (event) { if (selected_condition_index >= 0) { HG.WebApp.ProgramEdit._CurrentProgram.Conditions.splice(selected_condition_index, 1); automationpage_ConditionsRefresh(); } }); $('#condition_move_button').bind('click', function (event) { if (selected_condition_index >= 0 && newLine != selected_condition_index) { var newLine = $('#condition_linenumber_input').val() - 1; var conditions = HG.WebApp.ProgramEdit._CurrentProgram.Conditions; var conditionObj = conditions[selected_condition_index]; var direction = (selected_condition_index > newLine ? -1 : +1); for (var c = selected_condition_index; c != newLine; c += direction) { conditions[c] = conditions[c + direction]; } conditions[newLine] = conditionObj; automationpage_ConditionsRefresh(); } }); $('#automation_conditiontarget').on('click', 'li', function () { condition_targetdomain = $(this).attr('data-context-value'); HG.Ui.SwitchPopup('#automation_domain', '#automation_target_popup', true); }); $('#automation_target_popup').on('click', 'li', function () { condition_targetsubject = $(this).attr('data-context-value'); HG.Ui.SwitchPopup('#automation_target_popup', '#automation_target_homegenie_parameter', true); }); $('#automation_target_homegenie_parameter').on('click', 'li', function () { condition_targetparameter = $(this).attr('data-context-value') HG.Ui.SwitchPopup('#automation_target_homegenie_parameter', '#automation_condition_type', true); }); $('#automation_condition_type').on('click', 'li', function () { condition_type = $(this).attr('data-context-value') build_condition(); // HG.Ui.SwitchPopup('#automation_condition_type', '#automation_condition_value', true); }); $('#automation_conditionvalue_domain').on('click', 'li', function () { var domain = $(this).attr('data-context-value'); // $('#automation_conditionvalue_address').listview().empty(); // $('#automation_conditionvalue_address').append(automationpage_GetModulesListViewItems(domain, false)); // $('#automation_conditionvalue_address').listview('refresh'); // build_condition(); // HG.Ui.SwitchPopup('#automation_condition_value_domain', '#automation_condition_value_address', true); }); $('#automation_conditionvalue_address').on('click', 'li', function () { var domain = $(this).attr('data-context-domain'); var address = $(this).attr('data-context-value'); // $('#automation_conditionvalue_property').listview().empty(); // var module = HG.WebApp.Utility.GetModuleByDomainAddress(domain, address); if (module != null && (module.Address == "RF" || module.Address == "IR")) { $('#automation_conditionvalue_property').append('<li data-context-value="Receiver.RawData"><a>Receiver.RawData</a></li>'); } else if (module != null) { var comparable_props = HG.WebApp.ProgramEdit.GetModuleComparableProperties(module); for (var p = 0; p < comparable_props.length; p++) { var prop = comparable_props[p]; $('#automation_conditionvalue_property').append('<li data-context-value=":' + module.Domain + '/' + module.Address + '/' + prop.Name + '"><a>' + prop.Name + '</a></li>'); } } $('#automation_conditionvalue_property').listview('refresh'); // build_condition(); // HG.Ui.SwitchPopup('#automation_condition_value_address', '#automation_condition_value_property', true); }); $('#automation_conditionvalue_property').on('click', 'li', function () { condition_value = $(this).attr('data-context-value'); $('#comparison_value_input').val(condition_value); // build_condition(); // HG.Ui.SwitchPopup('#automation_condition_value_property', '#automation_condition_value', true); }); $('#comparison_value_input').on('keyup', function () { condition_value = $('#comparison_value_input').val(); // build_condition(); }); $('#condition_add_oroperator').bind('click', function (event) { conditionobj = { 'Domain': '', 'Target': '', 'Property': '', 'ComparisonOperator': 'LogicOrJoint', 'ComparisonValue': '' }; if (selected_condition_index == -1) { HG.WebApp.ProgramEdit._CurrentProgram.Conditions.push(conditionobj); } else { HG.WebApp.ProgramEdit._CurrentProgram.Conditions[selected_condition_index] = conditionobj; } automationpage_ConditionsRefresh(); }); $('#condition_completed').on('click', function () { condition_value = $('#comparison_value_input').val(); conditionobj = { 'Domain': condition_targetdomain, 'Target': condition_targetsubject, 'Property': condition_targetparameter, 'ComparisonOperator': condition_type, 'ComparisonValue': condition_value }; if (selected_condition_index == -1) { HG.WebApp.ProgramEdit._CurrentProgram.Conditions.push(conditionobj); } else { HG.WebApp.ProgramEdit._CurrentProgram.Conditions[selected_condition_index] = conditionobj; } automationpage_ConditionsRefresh(); }); }); function automationpage_WizardConditionAdd() { selected_condition_index = -1; $('#automation_domain').popup('open'); } function automationpage_GetModulesListViewItems(domain, showall) { var htmlopt = ''; var mods = HG.WebApp.ProgramEdit.GetDomainComparableModules(domain, showall); for (var m = 0; m < mods.length; m++) { htmlopt += '<li data-context-domain="' + mods[m].Domain + '" data-context-value="' + mods[m].Address + '"><a>' + mods[m].Address + ' (' + (mods[m].Name == null || mods[m].Name == '' ? mods[m].DeviceType : mods[m].Name) + ')' + '</a></li>' } return htmlopt; } function build_condition() { var conditionstring = '... ?'; if (condition_targetdomain != '') { conditionstring = condition_targetdomain; } if (condition_targetsubject != '') { conditionstring += '<strong>/</strong>' + condition_targetsubject; } if (condition_targetparameter != '') { conditionstring += '<br />&bull; <b>' + condition_targetparameter + '</b>'; } if (condition_type != '') { conditionstring += '<br />' + condition_type; } if (condition_value != '') { var cval = condition_value; if (cval[0] == ':') { var path = cval.split('/'); var lastdot = path[0].lastIndexOf('.'); if (lastdot > 0) { cval = cval.substring(lastdot + 1); } } conditionstring += '<br />&bull; <b>' + cval + '</b>'; } $('body').find('[id=condition_wizard_text]').each(function () { $(this).html(conditionstring); }); } function automationpage_ConditionChangeLine(lineNumber) { selected_condition_index = lineNumber; $('#automation_condition_delete').popup('open'); } function automationpage_ConditionEditLine(lineNumber) { selected_condition_index = lineNumber; var condition = HG.WebApp.ProgramEdit._CurrentProgram.Conditions[lineNumber]; condition_targetdomain = condition.Domain; condition_targetsubject = condition.Target; condition_targetparameter = condition.Property; condition_type = condition.ComparisonOperator; condition_value = condition.ComparisonValue; $('#automation_condition_value').popup('open'); build_condition(); } function automationpage_ConditionsRefresh() { $('#automation_program_conditions').empty(); if (HG.WebApp.ProgramEdit._CurrentProgram.Conditions) { var html = ''; for (i = 0; i < HG.WebApp.ProgramEdit._CurrentProgram.Conditions.length; i++) { var condition = HG.WebApp.ProgramEdit._CurrentProgram.Conditions[i]; var module = HG.WebApp.Utility.GetModuleByDomainAddress(condition.Domain, condition.Target); if (condition.ComparisonOperator == "-1") { condition.ComparisonOperator = "LessThan"; } else if (condition.ComparisonOperator == "0") { condition.ComparisonOperator = "Equals"; } else if (condition.ComparisonOperator == "1") { condition.ComparisonOperator = "GreaterThan"; } else if (condition.ComparisonOperator == "100") { condition.ComparisonOperator = "LogicOrJoint"; } var lineNumber = ('0000' + (i + 1).toString()).substr((i + 1).toString().length); var displayName = (module != null ? module.Name : ''); html += '<div class="hg-wizard-grid-linenumber" onclick="automationpage_ConditionChangeLine(' + i + ')">#' + lineNumber + '</div>'; if (condition.ComparisonOperator == 'LogicOrJoint') { html += '<div class="ui-grid-b hg-wizard-grid" style="background-color:lightgray" onclick="automationpage_ConditionChangeLine(' + i + ')">'; html += '<div class="ui-block-a">&nbsp;</div>' html += '<div class="ui-block-b" align="center">OR</div>' html += '<div class="ui-block-c">&nbsp;</div>' html += '</div>'; } else { html += '<div class="ui-grid-d hg-wizard-grid" onclick="automationpage_ConditionEditLine(' + i + ')">'; html += '<div class="ui-block-a">&nbsp;' + condition.Domain + '/' + condition.Target + '</div>'; html += '<div class="ui-block-b">&nbsp;' + displayName + '</div>'; html += '<div class="ui-block-c">&nbsp;' + condition.Property + '</div>'; html += '<div class="ui-block-d">&nbsp;' + condition.ComparisonOperator + '</div>'; html += '<div class="ui-block-e">&nbsp;' + condition.ComparisonValue + '</div>'; /* $('#automation_program_conditions').append('' + '<li data-context-value="' + i + '"><a>' + ' <span style="color:gray">' + condition.Domain.split('.')[1] + '</span>' + ' ' + condition.Target + ' <span style="color:gray">property</span> <b>' + pname + '</b>' + ' <span style="color:gray">' + condition.ComparisonOperator + '</span>' + ' <b>' + condition.ComparisonValue + '</b>' + '</a><a data-rel="popup" data-position-to="window" class="ui-btn" data-inline="true" data-transition="pop" href="#automation_condition_delete">Delete</a></li>'); */ html += '</div>'; } } $('#automation_program_conditions').append(html); $('#automation_program_conditions').trigger('create'); } } </script>
{ "pile_set_name": "Github" }
# %% """ <table class="ee-notebook-buttons" align="left"> <td><a target="_blank" href="https://github.com/giswqs/earthengine-py-notebooks/tree/master/Image/edge_detection.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a></td> <td><a target="_blank" href="https://nbviewer.jupyter.org/github/giswqs/earthengine-py-notebooks/blob/master/Image/edge_detection.ipynb"><img width=26px src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Jupyter_logo.svg/883px-Jupyter_logo.svg.png" />Notebook Viewer</a></td> <td><a target="_blank" href="https://colab.research.google.com/github/giswqs/earthengine-py-notebooks/blob/master/Image/edge_detection.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" /> Run in Google Colab</a></td> </table> """ # %% """ ## Install Earth Engine API and geemap Install the [Earth Engine Python API](https://developers.google.com/earth-engine/python_install) and [geemap](https://github.com/giswqs/geemap). The **geemap** Python package is built upon the [ipyleaflet](https://github.com/jupyter-widgets/ipyleaflet) and [folium](https://github.com/python-visualization/folium) packages and implements several methods for interacting with Earth Engine data layers, such as `Map.addLayer()`, `Map.setCenter()`, and `Map.centerObject()`. The following script checks if the geemap package has been installed. If not, it will install geemap, which automatically installs its [dependencies](https://github.com/giswqs/geemap#dependencies), including earthengine-api, folium, and ipyleaflet. **Important note**: A key difference between folium and ipyleaflet is that ipyleaflet is built upon ipywidgets and allows bidirectional communication between the front-end and the backend enabling the use of the map to capture user input, while folium is meant for displaying static data only ([source](https://blog.jupyter.org/interactive-gis-in-jupyter-with-ipyleaflet-52f9657fa7a)). Note that [Google Colab](https://colab.research.google.com/) currently does not support ipyleaflet ([source](https://github.com/googlecolab/colabtools/issues/60#issuecomment-596225619)). Therefore, if you are using geemap with Google Colab, you should use [`import geemap.eefolium`](https://github.com/giswqs/geemap/blob/master/geemap/eefolium.py). If you are using geemap with [binder](https://mybinder.org/) or a local Jupyter notebook server, you can use [`import geemap`](https://github.com/giswqs/geemap/blob/master/geemap/geemap.py), which provides more functionalities for capturing user input (e.g., mouse-clicking and moving). """ # %% # Installs geemap package import subprocess try: import geemap except ImportError: print('geemap package not installed. Installing ...') subprocess.check_call(["python", '-m', 'pip', 'install', 'geemap']) # Checks whether this notebook is running on Google Colab try: import google.colab import geemap.eefolium as geemap except: import geemap # Authenticates and initializes Earth Engine import ee try: ee.Initialize() except Exception as e: ee.Authenticate() ee.Initialize() # %% """ ## Create an interactive map The default basemap is `Google Maps`. [Additional basemaps](https://github.com/giswqs/geemap/blob/master/geemap/basemaps.py) can be added using the `Map.add_basemap()` function. """ # %% Map = geemap.Map(center=[40,-100], zoom=4) Map # %% """ ## Add Earth Engine Python script """ # %% # Add Earth Engine dataset # Load a Landsat 8 image, select the panchromatic band. image = ee.Image('LANDSAT/LC08/C01/T1/LC08_044034_20140318').select('B8') # Perform Canny edge detection and display the result. canny = ee.Algorithms.CannyEdgeDetector(**{ 'image': image, 'threshold': 10, 'sigma': 1 }) Map.setCenter(-122.054, 37.7295, 10) Map.addLayer(canny, {}, 'canny') # Perform Hough transform of the Canny result and display. hough = ee.Algorithms.HoughTransform(canny, 256, 600, 100) Map.addLayer(hough, {}, 'hough') # Load a Landsat 8 image, select the panchromatic band. image = ee.Image('LANDSAT/LC08/C01/T1/LC08_044034_20140318').select('B8') Map.addLayer(image, {'max': 12000}) # Define a "fat" Gaussian kernel. fat = ee.Kernel.gaussian(**{ 'radius': 3, 'sigma': 3, 'units': 'pixels', 'normalize': True, 'magnitude': -1 }) # Define a "skinny" Gaussian kernel. skinny = ee.Kernel.gaussian(**{ 'radius': 3, 'sigma': 1, 'units': 'pixels', 'normalize': True, }) # Compute a difference-of-Gaussians (DOG) kernel. dog = fat.add(skinny) # Compute the zero crossings of the second derivative, display. zeroXings = image.convolve(dog).zeroCrossing() Map.setCenter(-122.054, 37.7295, 10) Map.addLayer(zeroXings.updateMask(zeroXings), {'palette': 'FF0000'}, 'zero crossings') # %% """ ## Display Earth Engine data layers """ # %% Map.addLayerControl() # This line is not needed for ipyleaflet-based Map. Map
{ "pile_set_name": "Github" }
/* * linux/drivers/media/platform/s5p-mfc/s5p_mfc_cmd_v5.c * * Copyright (C) 2011 Samsung Electronics Co., Ltd. * http://www.samsung.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. */ #include "regs-mfc.h" #include "s5p_mfc_cmd.h" #include "s5p_mfc_common.h" #include "s5p_mfc_debug.h" #include "s5p_mfc_cmd_v5.h" /* This function is used to send a command to the MFC */ static int s5p_mfc_cmd_host2risc_v5(struct s5p_mfc_dev *dev, int cmd, struct s5p_mfc_cmd_args *args) { int cur_cmd; unsigned long timeout; timeout = jiffies + msecs_to_jiffies(MFC_BW_TIMEOUT); /* wait until host to risc command register becomes 'H2R_CMD_EMPTY' */ do { if (time_after(jiffies, timeout)) { mfc_err("Timeout while waiting for hardware\n"); return -EIO; } cur_cmd = mfc_read(dev, S5P_FIMV_HOST2RISC_CMD); } while (cur_cmd != S5P_FIMV_H2R_CMD_EMPTY); mfc_write(dev, args->arg[0], S5P_FIMV_HOST2RISC_ARG1); mfc_write(dev, args->arg[1], S5P_FIMV_HOST2RISC_ARG2); mfc_write(dev, args->arg[2], S5P_FIMV_HOST2RISC_ARG3); mfc_write(dev, args->arg[3], S5P_FIMV_HOST2RISC_ARG4); /* Issue the command */ mfc_write(dev, cmd, S5P_FIMV_HOST2RISC_CMD); return 0; } /* Initialize the MFC */ static int s5p_mfc_sys_init_cmd_v5(struct s5p_mfc_dev *dev) { struct s5p_mfc_cmd_args h2r_args; memset(&h2r_args, 0, sizeof(struct s5p_mfc_cmd_args)); h2r_args.arg[0] = dev->fw_size; return s5p_mfc_cmd_host2risc_v5(dev, S5P_FIMV_H2R_CMD_SYS_INIT, &h2r_args); } /* Suspend the MFC hardware */ static int s5p_mfc_sleep_cmd_v5(struct s5p_mfc_dev *dev) { struct s5p_mfc_cmd_args h2r_args; memset(&h2r_args, 0, sizeof(struct s5p_mfc_cmd_args)); return s5p_mfc_cmd_host2risc_v5(dev, S5P_FIMV_H2R_CMD_SLEEP, &h2r_args); } /* Wake up the MFC hardware */ static int s5p_mfc_wakeup_cmd_v5(struct s5p_mfc_dev *dev) { struct s5p_mfc_cmd_args h2r_args; memset(&h2r_args, 0, sizeof(struct s5p_mfc_cmd_args)); return s5p_mfc_cmd_host2risc_v5(dev, S5P_FIMV_H2R_CMD_WAKEUP, &h2r_args); } static int s5p_mfc_open_inst_cmd_v5(struct s5p_mfc_ctx *ctx) { struct s5p_mfc_dev *dev = ctx->dev; struct s5p_mfc_cmd_args h2r_args; int ret; /* Preparing decoding - getting instance number */ mfc_debug(2, "Getting instance number (codec: %d)\n", ctx->codec_mode); dev->curr_ctx = ctx->num; memset(&h2r_args, 0, sizeof(struct s5p_mfc_cmd_args)); switch (ctx->codec_mode) { case S5P_MFC_CODEC_H264_DEC: h2r_args.arg[0] = S5P_FIMV_CODEC_H264_DEC; break; case S5P_MFC_CODEC_VC1_DEC: h2r_args.arg[0] = S5P_FIMV_CODEC_VC1_DEC; break; case S5P_MFC_CODEC_MPEG4_DEC: h2r_args.arg[0] = S5P_FIMV_CODEC_MPEG4_DEC; break; case S5P_MFC_CODEC_MPEG2_DEC: h2r_args.arg[0] = S5P_FIMV_CODEC_MPEG2_DEC; break; case S5P_MFC_CODEC_H263_DEC: h2r_args.arg[0] = S5P_FIMV_CODEC_H263_DEC; break; case S5P_MFC_CODEC_VC1RCV_DEC: h2r_args.arg[0] = S5P_FIMV_CODEC_VC1RCV_DEC; break; case S5P_MFC_CODEC_H264_ENC: h2r_args.arg[0] = S5P_FIMV_CODEC_H264_ENC; break; case S5P_MFC_CODEC_MPEG4_ENC: h2r_args.arg[0] = S5P_FIMV_CODEC_MPEG4_ENC; break; case S5P_MFC_CODEC_H263_ENC: h2r_args.arg[0] = S5P_FIMV_CODEC_H263_ENC; break; default: h2r_args.arg[0] = S5P_FIMV_CODEC_NONE; } h2r_args.arg[1] = 0; /* no crc & no pixelcache */ h2r_args.arg[2] = ctx->ctx.ofs; h2r_args.arg[3] = ctx->ctx.size; ret = s5p_mfc_cmd_host2risc_v5(dev, S5P_FIMV_H2R_CMD_OPEN_INSTANCE, &h2r_args); if (ret) { mfc_err("Failed to create a new instance\n"); ctx->state = MFCINST_ERROR; } return ret; } static int s5p_mfc_close_inst_cmd_v5(struct s5p_mfc_ctx *ctx) { struct s5p_mfc_dev *dev = ctx->dev; struct s5p_mfc_cmd_args h2r_args; int ret; if (ctx->state == MFCINST_FREE) { mfc_err("Instance already returned\n"); ctx->state = MFCINST_ERROR; return -EINVAL; } /* Closing decoding instance */ mfc_debug(2, "Returning instance number %d\n", ctx->inst_no); dev->curr_ctx = ctx->num; memset(&h2r_args, 0, sizeof(struct s5p_mfc_cmd_args)); h2r_args.arg[0] = ctx->inst_no; ret = s5p_mfc_cmd_host2risc_v5(dev, S5P_FIMV_H2R_CMD_CLOSE_INSTANCE, &h2r_args); if (ret) { mfc_err("Failed to return an instance\n"); ctx->state = MFCINST_ERROR; return -EINVAL; } return 0; } /* Initialize cmd function pointers for MFC v5 */ static struct s5p_mfc_hw_cmds s5p_mfc_cmds_v5 = { .cmd_host2risc = s5p_mfc_cmd_host2risc_v5, .sys_init_cmd = s5p_mfc_sys_init_cmd_v5, .sleep_cmd = s5p_mfc_sleep_cmd_v5, .wakeup_cmd = s5p_mfc_wakeup_cmd_v5, .open_inst_cmd = s5p_mfc_open_inst_cmd_v5, .close_inst_cmd = s5p_mfc_close_inst_cmd_v5, }; struct s5p_mfc_hw_cmds *s5p_mfc_init_hw_cmds_v5(void) { return &s5p_mfc_cmds_v5; }
{ "pile_set_name": "Github" }
import UIElement, { EVENT } from "@core/UIElement"; import { LOAD, CLICK, POINTERSTART, MOVE, BIND, CHANGE } from "@core/Event"; import { Length } from "@unit/Length"; import RangeEditor from "./RangeEditor"; import SelectEditor from "./SelectEditor"; import InputRangeEditor from "./InputRangeEditor"; import { Gradient } from "@property-parser/image-resource/Gradient"; import icon from "@icon/icon"; import { SVGFill } from "@property-parser/SVGFill"; import { SVGStaticGradient } from "@property-parser/image-resource/SVGStaticGradient"; import { isUndefined } from "@core/functions/func"; import SelectIconEditor from "./SelectIconEditor"; const imageTypeList = [ 'static-gradient', 'linear-gradient', 'radial-gradient', 'image-resource' ] const iconList = { 'image-resource': icon.photo } const presetPosition = { top: { x1: '0%', y1: '100%', x2: '0%', y2: '0%'}, 'top left': { x1: '100%', y1: '100%', x2: '0%', y2: '0%'}, 'top right': { x1: '0%', y1: '100%', x2: '100%', y2: '0%'}, left: { x1: '100%', y1: '0%', x2: '0%', y2: '0%'}, right: { x1: '0%', y1: '0%', x2: '100%', y2: '0%'}, bottom: { x1: '0%', y1: '0%', x2: '0%', y2: '100%'}, 'bottom left': { x1: '100%', y1: '0%', x2: '0%', y2: '100%'}, 'bottom right': { x1: '0%', y1: '0%', x2: '100%', y2: '100%'} } const props = [ 'x1', 'y1', 'x2', 'y2', 'cx', 'cy', 'r', 'fx', 'fy', 'fr', 'spreadMethod', 'patternUnits', 'patternWidth', 'patternHeight', 'imageX', 'imageY', 'imageWidth', 'imageHeight' ] const rangeEditorList = [ 'x1', 'y1', 'x2', 'y2', 'cx', 'cy', 'r', 'fx', 'fy', 'fr', 'patternWidth', 'patternHeight', 'imageX', 'imageY', 'imageWidth', 'imageHeight' ] export default class FillEditor extends UIElement { components() { return { InputRangeEditor, RangeEditor, SelectIconEditor, SelectEditor } } initState() { return { cachedRect: null, index: +(this.props.index || 0 ), value: this.props.value, image: SVGFill.parseImage(this.props.value || 'transparent') || SVGStaticGradient.create() } } setValue (value) { this.setState({ cachedRect: null, image: SVGFill.parseImage(value) }, false) this.refresh(); this.parent.trigger('changeTabType', this.state.image.type); } template() { var { image } = this.state; image = image || {} var type = image.type || 'static-gradient' if (type === 'url') type = 'image-resource' return /*html*/` <div class='fill-editor' data-selected-editor='${type}'> <div class='gradient-preview'> <div class='gradient-view' ref='$gradientView'> <div class='drag-pointer' ref='$dragPosition'></div> </div> <svg class='pointer-draw' ref='$pointerDrawArea'> <line data-type='line' ref='$line' /> <circle r='5' data-type='start' ref='$startPoint' /> <circle r='5' data-type='end' ref='$endPoint' /> <circle r='5' data-type='center' ref='$centerPoint' /> <circle r='5' data-type='f' ref='$fPoint' /> </svg> <div class='preset-position'> <div data-value='top' title='top'>${icon.chevron_right}</div> <div data-value='right' title='right'>${icon.chevron_right}</div> <div data-value='left' title='left'>${icon.chevron_right}</div> <div data-value='bottom' title='bottom'>${icon.chevron_right}</div> <div data-value='top left' title='top left'>${icon.chevron_right}</div> <div data-value='top right' title='top right'>${icon.chevron_right}</div> <div data-value='bottom left' title='bottom left'>${icon.chevron_right}</div> <div data-value='bottom right' title='bottom right'>${icon.chevron_right}</div> </div> <div data-editor='image-loader'> <input type='file' accept="image/*" ref='$file' /> </div> </div> <div class="picker-tab"> <div class="picker-tab-list" ref="$tab"> ${imageTypeList.map(it => { return `<span class='picker-tab-item ${it}' data-editor='${it}'><span class='icon'>${iconList[it] || ''}</span></span>` }).join('')} </div> </div> <div class='gradient-steps' data-editor='gradient'> <div class="hue-container" ref="$back"></div> <div class="hue" ref="$steps"> <div class='step-list' ref="$stepList" ></div> </div> </div> <div class='tools' data-editor='tools'> <RangeEditor label='${this.$i18n('fill.editor.offset')}' ref='$range' key='length' onchange='changeColorStepOffset' /> </div> <div class='sub-editor' ref='$subEditor'> <div data-editor='spreadMethod'> <SelectIconEditor label='${this.$i18n('fill.editor.spread')}' ref='$spreadMethod' value="pad" options='pad,reflect,repeat' key='spreadMethod' onchange='changeKeyValue' /> </div> <div data-editor='patternUnits'> <SelectEditor label='Pattern' ref='$patternUnits' options='userSpaceOnUse' key='patternUnits' onchange='changeKeyValue' /> </div> ${rangeEditorList.map(field => { const label = this.$i18n('fill.editor.' + field) return /*html*/` <div data-editor='${field}'> <RangeEditor label='${label}' ref='$${field}' value="${this.getImageFieldValue(image, field)}" key='${field}' onchange='changeKeyValue' /> </div> ` }).join('')} </div> </div> `; } getImageFieldValue(image, field) { var value = image[field] if (isUndefined(value)) { switch(field) { case 'cx': case 'cy': case 'r': case 'fx': case 'fy': return '50%' case 'x1': case 'y1': case 'y2': case 'fr': case 'imageX': case 'imageY': return '0%'; case 'x2': case 'patternWidth': case 'patternHeight': case 'imageWidth': case 'imageHeight': return '100%'; } } return value; } [CHANGE('$file')] (e) { var project = this.$selection.currentProject; if (project) { [...e.target.files].forEach(item => { this.emit('updateImageAssetItem', item, (local) => { this.trigger('setImageUrl', local); }); }) } } [CLICK('$el .preset-position [data-value]')] (e) { var type = e.$dt.attr('data-value') if (presetPosition[type]) { this.state.image.reset(presetPosition[type]) this.refresh(); this.refreshFieldValue(); this.updateData(); } } refreshFieldValue() { this.children.$x1.setValue(this.state.image.x1) this.children.$y1.setValue(this.state.image.y1) this.children.$x2.setValue(this.state.image.x2) this.children.$y2.setValue(this.state.image.y2) this.children.$cx.setValue(this.state.image.cx) this.children.$cy.setValue(this.state.image.cy) this.children.$r.setValue(this.state.image.r) this.children.$fx.setValue(this.state.image.fx) this.children.$fy.setValue(this.state.image.fy) this.children.$fr.setValue(this.state.image.fr) this.children.$spreadMethod.setValue(this.state.image.spreadMethod); this.children.$patternUnits.setValue(this.state.image.patternUnits); this.children.$patternWidth.setValue(this.state.image.patternWidth); this.children.$patternHeight.setValue(this.state.image.patternHeight); this.children.$imageX.setValue(this.state.image.imageX); this.children.$imageY.setValue(this.state.image.imageY); this.children.$imageWidth.setValue(this.state.image.imageWidth); this.children.$imagenHeight.setValue(this.state.image.imageHeight); } getDrawAreaRect () { return {width: 198, height: 150}; } getFieldValue(field) { return Length.parse(this.getImageFieldValue(this.state.image, field)); } [BIND('$line')] () { var {width, height} = this.getDrawAreaRect() var x1 = this.getFieldValue('x1').toPx(width) var y1 = this.getFieldValue('y1').toPx(height) var x2 = this.getFieldValue('x2').toPx(width) var y2 = this.getFieldValue('y2').toPx(height) return { x1, y1, x2, y2 } } [BIND('$startPoint')] () { var {width, height} = this.getDrawAreaRect() var cx = this.getFieldValue('x1').toPx(width) var cy = this.getFieldValue('y1').toPx(height) return { cx, cy } } [BIND('$endPoint')] () { var {width, height} = this.getDrawAreaRect() var cx = this.getFieldValue('x2').toPx(width) var cy = this.getFieldValue('y2').toPx(height) return { cx, cy } } [BIND('$centerPoint')] () { var {width, height} = this.getDrawAreaRect() var cx = this.getFieldValue('cx').toPx(width) var cy = this.getFieldValue('cy').toPx(height) return { cx, cy } } [BIND('$fPoint')] () { var {width, height} = this.getDrawAreaRect() var cx = this.getFieldValue('fx').toPx(width) var cy = this.getFieldValue('fy').toPx(height) return { cx, cy } } [POINTERSTART('$pointerDrawArea circle[data-type]') + MOVE('moveDragPointer')] (e) { this.containerRect = this.refs.$pointerDrawArea.rect(); this.startXY = e.xy; this.type = e.$dt.attr('data-type'); this.state.cachedRect = null; } getRectRate (rect, x, y) { var {width, height, x:rx, y: ry } = rect if (rx > x) { x = rx; } else if (rx + width < x) { x = rx + width; } if (ry > y) { y = ry; } else if (ry + height < y) { y = ry + height; } var left = Length.percent((x - rx ) / width * 100) var top = Length.percent((y - ry ) / height * 100) return {left, top} } moveDragPointer (dx, dy) { var x = this.startXY.x + dx; var y = this.startXY.y + dy; var {left, top } = this.getRectRate(this.containerRect, x, y); if (this.type == 'start') { this.state.image.reset({ x1: left, y1: top }) this.children.$x1.setValue(left) this.children.$y1.setValue(top) this.bindData('$startPoint') this.bindData('$line') } else if (this.type == 'end') { this.state.image.reset({ x2: left, y2: top }) this.children.$x2.setValue(left) this.children.$y2.setValue(top) this.bindData('$endPoint') this.bindData('$line') } else if (this.type == 'center') { this.state.image.reset({ cx: left, cy: top }) this.children.$cx.setValue(left) this.children.$cy.setValue(top) this.bindData('$centerPoint') } else if (this.type == 'f') { this.state.image.reset({ fx: left, fy: top }) this.children.$fx.setValue(left) this.children.$fy.setValue(top) this.bindData('$fPoint') } this.bindData('$gradientView') this.updateData(); } [CLICK('$tab .picker-tab-item')] (e) { var type = e.$dt.attr('data-editor') this.$el.attr('data-selected-editor', type); this.parent.trigger('changeTabType', type); var url = type === 'image-resource' ? this.state.image.url : this.state.url; var opt = {} props.forEach(it => { opt[it] = this.children[`$${it}`].getValue() }) this.state.image = SVGFill.changeImageType({ type, url, colorsteps: this.state.image.colorsteps || [] , ...opt }) this.refresh(); this.updateData(); this.sendMessage(); } sendMessage (type) { var type = this.$el.attr('data-selected-editor'); if (type === 'linear-gradient') { this.emit('addStatusBarMessage', ''); } else if (type === 'url' || type === 'image-resource') { this.emit('addStatusBarMessage', this.$i18n('fill.editor.message.click.image')); } else { this.emit('addStatusBarMessage', this.$i18n('fill.editor.message.drag.position')); } } [EVENT('changeKeyValue')] (key, value) { this.state.image.reset({ [key]: value }) this.bindData('$gradientView') this.bindData('$line') this.bindData('$startPoint') this.bindData('$endPoint') this.bindData('$centerPoint') this.bindData('$fPoint') this.updateData(); } [EVENT('changeColorStepOffset')] (key, value) { if (this.currentStep) { this.currentStep.percent = value.value; this.state.image.sortColorStep(); this.refresh() this.updateData(); } } [CLICK('$back')] (e) { var rect = this.refs.$stepList.rect(); var minX = rect.x; var maxX = rect.right; var x = e.xy.x if (x < minX) x = minX else if (x > maxX) x = maxX var percent = (x - minX) / rect.width * 100; this.state.image.insertColorStep(percent); this.state.image.sortColorStep() this.refresh(); this.updateData(); } [BIND('$el')] () { var type = this.state.image.type; if (type === 'url') { type = 'image-resource' } this.parent.trigger('changeTabType', type); return { "data-selected-editor": type } } [BIND('$stepList')] () { return { 'data-selected-index': this.state.index.toString(), 'style': { 'background-image' : this.getLinearGradient() } } } get fillId () { return this.id + 'fill'; } [BIND('$gradientView')] () { return { innerHTML : /*html*/` <svg x="0" y="0" width="100%" height="100%"> <defs> ${this.state.image.toSVGString(this.fillId)} </defs> <rect x="0" y="0" width="100%" height="100%" fill="${this.state.image.toFillValue(this.fillId)}" /> </svg> ` } } [LOAD('$stepList')] () { var colorsteps = this.state.image.colorsteps || [] return colorsteps.map( (it, index) => { var selected = this.$selection.isSelectedColorStep(it.id) ? 'selected' : ''; return /*html*/` <div class='step ${selected}' data-id='${it.id}' style='left: ${it.percent}%;'> <div class='color-view' style="background-color: ${it.color}"></div> <div class='arrow' style="background-color: ${it.color}"></div> </div>` }) } removeStep(id) { this.state.image.removeColorStep(id); this.refresh(); this.updateData(); } selectStep(id) { this.state.id = id; this.$selection.selectColorStep(id); if (this.state.image.colorsteps) { this.currentStep = this.state.image.colorsteps.find( it => this.$selection.isSelectedColorStep(it.id)) this.children.$range.setValue(Length.percent(this.currentStep.percent)); this.parent.trigger('selectColorStep', this.currentStep.color) } this.refresh(); } [POINTERSTART('$stepList .step') + MOVE()] (e) { var id = e.$dt.attr('data-id') if (e.altKey) { this.removeStep(id); return false; } else { this.selectStep(id); this.startXY = e.xy; this.cachedStepListRect = this.refs.$stepList.rect(); } } getStepListRect () { return this.cachedStepListRect; } move (dx, dy) { var rect = this.getStepListRect() var minX = rect.x; var maxX = rect.right; var x = this.startXY.x + dx if (x < minX) x = minX else if (x > maxX) x = maxX var percent = (x - minX) / rect.width * 100; this.currentStep.percent = percent; this.children.$range.setValue(Length.percent(percent)); this.state.image.sortColorStep(); this.refresh() this.updateData(); } refresh() { this.load(); } getLinearGradient () { var { image } = this.state; return `linear-gradient(to right, ${Gradient.toColorString(image.colorsteps)})`; } [EVENT('setColorStepColor')] (color) { if (this.state.image.type === 'static-gradient') { this.state.image.setColor(color) this.refresh() this.updateData(); } else { if (this.currentStep) { this.currentStep.color = color; this.refresh() this.updateData(); } } } [EVENT('setImageUrl')] (url) { if (this.state.image) { this.state.url = url; this.state.image.reset({ url }); this.refresh(); this.updateData(); } } updateData(data = {}) { this.setState(data, false); this.parent.trigger(this.props.onchange, this.state.image.toString()); } }
{ "pile_set_name": "Github" }
{ "name": "gutenberg", "version": "9.0.0", "private": true, "description": "A new WordPress editor experience.", "author": "The WordPress Contributors", "license": "GPL-2.0-or-later", "keywords": [ "WordPress", "editor" ], "homepage": "https://github.com/WordPress/gutenberg/", "repository": "git+https://github.com/WordPress/gutenberg.git", "bugs": { "url": "https://github.com/WordPress/gutenberg/issues" }, "engines": { "node": ">=10.0.0", "npm": ">=6.9.0" }, "config": { "GUTENBERG_PHASE": 2 }, "dependencies": { "@wordpress/a11y": "file:packages/a11y", "@wordpress/annotations": "file:packages/annotations", "@wordpress/api-fetch": "file:packages/api-fetch", "@wordpress/autop": "file:packages/autop", "@wordpress/blob": "file:packages/blob", "@wordpress/block-directory": "file:packages/block-directory", "@wordpress/block-editor": "file:packages/block-editor", "@wordpress/block-library": "file:packages/block-library", "@wordpress/block-serialization-default-parser": "file:packages/block-serialization-default-parser", "@wordpress/block-serialization-spec-parser": "file:packages/block-serialization-spec-parser", "@wordpress/blocks": "file:packages/blocks", "@wordpress/components": "file:packages/components", "@wordpress/compose": "file:packages/compose", "@wordpress/core-data": "file:packages/core-data", "@wordpress/data": "file:packages/data", "@wordpress/data-controls": "file:packages/data-controls", "@wordpress/date": "file:packages/date", "@wordpress/deprecated": "file:packages/deprecated", "@wordpress/dom": "file:packages/dom", "@wordpress/dom-ready": "file:packages/dom-ready", "@wordpress/edit-navigation": "file:packages/edit-navigation", "@wordpress/edit-post": "file:packages/edit-post", "@wordpress/edit-site": "file:packages/edit-site", "@wordpress/edit-widgets": "file:packages/edit-widgets", "@wordpress/editor": "file:packages/editor", "@wordpress/element": "file:packages/element", "@wordpress/escape-html": "file:packages/escape-html", "@wordpress/format-library": "file:packages/format-library", "@wordpress/hooks": "file:packages/hooks", "@wordpress/html-entities": "file:packages/html-entities", "@wordpress/i18n": "file:packages/i18n", "@wordpress/icons": "file:packages/icons", "@wordpress/interface": "file:packages/interface", "@wordpress/is-shallow-equal": "file:packages/is-shallow-equal", "@wordpress/keyboard-shortcuts": "file:packages/keyboard-shortcuts", "@wordpress/keycodes": "file:packages/keycodes", "@wordpress/list-reusable-blocks": "file:packages/list-reusable-blocks", "@wordpress/media-utils": "file:packages/media-utils", "@wordpress/notices": "file:packages/notices", "@wordpress/nux": "file:packages/nux", "@wordpress/plugins": "file:packages/plugins", "@wordpress/primitives": "file:packages/primitives", "@wordpress/priority-queue": "file:packages/priority-queue", "@wordpress/react-native-aztec": "file:packages/react-native-aztec", "@wordpress/react-native-bridge": "file:packages/react-native-bridge", "@wordpress/react-native-editor": "file:packages/react-native-editor", "@wordpress/redux-routine": "file:packages/redux-routine", "@wordpress/rich-text": "file:packages/rich-text", "@wordpress/server-side-render": "file:packages/server-side-render", "@wordpress/shortcode": "file:packages/shortcode", "@wordpress/token-list": "file:packages/token-list", "@wordpress/url": "file:packages/url", "@wordpress/viewport": "file:packages/viewport", "@wordpress/warning": "file:packages/warning", "@wordpress/wordcount": "file:packages/wordcount" }, "devDependencies": { "@actions/core": "1.0.0", "@actions/github": "1.0.0", "@babel/core": "7.11.6", "@babel/plugin-syntax-jsx": "7.10.4", "@babel/runtime-corejs3": "7.11.2", "@babel/traverse": "7.11.5", "@jest/types": "25.3.0", "@octokit/rest": "16.26.0", "@octokit/webhooks": "7.1.0", "@storybook/addon-a11y": "5.3.2", "@storybook/addon-docs": "5.3.2", "@storybook/addon-knobs": "5.3.2", "@storybook/addon-storysource": "5.3.2", "@storybook/addon-viewport": "5.3.2", "@storybook/react": "6.0.21", "@testing-library/react": "10.0.2", "@types/classnames": "2.2.10", "@types/eslint": "6.8.0", "@types/estree": "0.0.44", "@types/lodash": "4.14.149", "@types/npm-package-arg": "6.1.0", "@types/prettier": "1.19.0", "@types/qs": "6.9.1", "@types/requestidlecallback": "0.3.1", "@types/semver": "7.2.0", "@types/sprintf-js": "1.1.2", "@types/uuid": "7.0.2", "@types/webpack": "4.41.16", "@types/webpack-sources": "0.1.7", "@wordpress/babel-plugin-import-jsx-pragma": "file:packages/babel-plugin-import-jsx-pragma", "@wordpress/babel-plugin-makepot": "file:packages/babel-plugin-makepot", "@wordpress/babel-preset-default": "file:packages/babel-preset-default", "@wordpress/base-styles": "file:packages/base-styles", "@wordpress/browserslist-config": "file:packages/browserslist-config", "@wordpress/create-block": "file:packages/create-block", "@wordpress/custom-templated-path-webpack-plugin": "file:packages/custom-templated-path-webpack-plugin", "@wordpress/dependency-extraction-webpack-plugin": "file:packages/dependency-extraction-webpack-plugin", "@wordpress/docgen": "file:packages/docgen", "@wordpress/e2e-test-utils": "file:packages/e2e-test-utils", "@wordpress/e2e-tests": "file:packages/e2e-tests", "@wordpress/env": "file:packages/env", "@wordpress/eslint-plugin": "file:packages/eslint-plugin", "@wordpress/jest-console": "file:packages/jest-console", "@wordpress/jest-preset-default": "file:packages/jest-preset-default", "@wordpress/jest-puppeteer-axe": "file:packages/jest-puppeteer-axe", "@wordpress/lazy-import": "file:packages/lazy-import", "@wordpress/library-export-default-webpack-plugin": "file:packages/library-export-default-webpack-plugin", "@wordpress/npm-package-json-lint-config": "file:packages/npm-package-json-lint-config", "@wordpress/postcss-plugins-preset": "file:packages/postcss-plugins-preset", "@wordpress/postcss-themes": "file:packages/postcss-themes", "@wordpress/prettier-config": "file:packages/prettier-config", "@wordpress/project-management-automation": "file:packages/project-management-automation", "@wordpress/scripts": "file:packages/scripts", "appium": "1.17.1", "babel-jest": "25.3.0", "babel-loader": "8.1.0", "babel-plugin-emotion": "10.0.33", "babel-plugin-inline-json-import": "0.3.2", "babel-plugin-react-native-classname-to-style": "1.2.2", "babel-plugin-react-native-platform-specific-extensions": "1.1.1", "babel-plugin-require-context-hook": "1.0.0", "benchmark": "2.1.4", "browserslist": "4.14.0", "chalk": "4.0.0", "commander": "4.1.0", "concurrently": "3.5.0", "copy-webpack-plugin": "4.5.2", "cross-env": "3.2.4", "css-loader": "3.5.2", "cssnano": "4.1.10", "deep-freeze": "0.0.1", "enzyme": "3.11.0", "equivalent-key-map": "0.2.2", "eslint-plugin-eslint-comments": "3.1.2", "eslint-plugin-import": "2.20.2", "execa": "4.0.2", "fast-glob": "2.2.7", "glob": "7.1.2", "husky": "3.0.5", "inquirer": "7.1.0", "jest": "25.3.0", "jest-emotion": "10.0.32", "jest-junit": "10.0.0", "jest-serializer-enzyme": "1.0.0", "jest-watch-typeahead": "0.6.0", "jsdom": "15.2.1", "lerna": "3.18.2", "lint-staged": "9.2.5", "lodash": "4.17.19", "make-dir": "3.0.0", "metro-react-native-babel-preset": "0.57.0", "metro-react-native-babel-transformer": "0.56.0", "mkdirp": "0.5.1", "nock": "12.0.3", "node-sass": "4.13.1", "node-watch": "0.6.0", "patch-package": "6.2.2", "postcss": "7.0.32", "postcss-loader": "3.0.0", "prettier": "npm:[email protected]", "progress": "2.0.3", "puppeteer": "npm:[email protected]", "react": "16.13.1", "react-dom": "16.13.1", "react-native": "0.61.5", "react-test-renderer": "16.13.1", "rimraf": "3.0.2", "rtlcss": "2.4.0", "sass-loader": "8.0.2", "semver": "7.3.2", "simple-git": "1.113.0", "source-map-loader": "0.2.4", "sprintf-js": "1.1.1", "style-loader": "1.0.0", "stylelint-config-wordpress": "17.0.0", "terser-webpack-plugin": "3.0.3", "typescript": "3.8.3", "uuid": "7.0.2", "wd": "1.12.1", "webpack": "4.42.0", "worker-farm": "1.7.0" }, "scripts": { "analyze-bundles": "npm run build -- --webpack-bundle-analyzer", "clean:packages": "rimraf \"./packages/*/@(build|build-module|build-style)\"", "clean:package-types": "tsc --build --clean", "prebuild:packages": "npm run clean:packages && lerna run build", "build:packages": "npm run build:package-types && node ./bin/packages/build.js", "build:package-types": "node ./bin/packages/validate-typescript-version.js && tsc --build", "build:plugin-zip": "./bin/build-plugin-zip.sh", "build": "npm run build:packages && wp-scripts build", "changelog": "./bin/plugin/cli.js changelog", "check-licenses": "concurrently \"wp-scripts check-licenses --prod --gpl2 --ignore=@react-native-community/cli,@react-native-community/cli-platform-ios\" \"wp-scripts check-licenses --dev\"", "precheck-local-changes": "npm run docs:build", "check-local-changes": "( git diff -U0 | xargs -0 node bin/process-git-diff ) || ( echo \"There are local uncommitted changes after one or both of 'npm install' or 'npm run docs:build'!\" && git diff --exit-code && exit 1 );", "dev": "npm run build:packages && concurrently \"wp-scripts start\" \"npm run dev:packages\"", "dev:packages": "node ./bin/packages/watch.js", "docs:build": "node ./docs/tool/index.js && node ./bin/api-docs/update-api-docs.js", "fixtures:clean": "rimraf \"packages/e2e-tests/fixtures/blocks/*.+(json|serialized.html)\"", "fixtures:generate": "cross-env GENERATE_MISSING_FIXTURES=y npm run test-unit", "fixtures:regenerate": "npm run fixtures:clean && npm run fixtures:generate", "format-js": "wp-scripts format-js", "lint": "concurrently \"npm run lint-lockfile\" \"npm run lint-js\" \"npm run lint-pkg-json\" \"npm run lint-css\"", "lint-js": "wp-scripts lint-js", "lint-js:fix": "npm run lint-js -- --fix", "prelint-php": "wp-env run composer 'install --no-interaction'", "lint-php": "wp-env run composer run-script lint", "lint-pkg-json": "wp-scripts lint-pkg-json . 'packages/*/package.json'", "lint-lockfile": "node ./bin/validate-package-lock.js", "lint-css": "wp-scripts lint-style '**/*.scss'", "lint-css:fix": "npm run lint-css -- --fix", "lint:md-js": "wp-scripts lint-md-js", "lint:md-docs": "wp-scripts lint-md-docs", "native": "npm run --prefix packages/react-native-editor", "pot-to-php": "./bin/pot-to-php.js", "postinstall": "patch-package", "publish:check": "lerna updated", "publish:dev": "npm run clean:package-types && npm run build:packages && lerna publish prerelease --preid rc --dist-tag next", "publish:patch": "npm run clean:package-types && npm run build:packages && lerna publish --dist-tag patch", "publish:prod": "npm run clean:package-types && npm run build:packages && lerna publish", "test": "npm run lint && npm run test-unit", "test:create-block": "./bin/test-create-block.sh", "test-e2e": "wp-scripts test-e2e --config packages/e2e-tests/jest.config.js", "test-e2e:debug": "wp-scripts --inspect-brk test-e2e --config packages/e2e-tests/jest.config.js --puppeteer-devtools", "test-e2e:watch": "npm run test-e2e -- --watch", "test-performance": "wp-scripts test-e2e --config packages/e2e-tests/jest.performance.config.js", "test-php": "npm run lint-php && npm run test-unit-php", "test-unit": "wp-scripts test-unit-js --config test/unit/jest.config.js", "test-unit:debug": "wp-scripts --inspect-brk test-unit-js --runInBand --no-cache --verbose --config test/unit/jest.config.js ", "test-unit:update": "npm run test-unit -- --updateSnapshot", "test-unit:watch": "npm run test-unit -- --watch", "pretest-unit-php": "wp-env start", "test-unit-php": "wp-env run phpunit 'phpunit -c /var/www/html/wp-content/plugins/gutenberg/phpunit.xml.dist --verbose'", "pretest-unit-php-multisite": "wp-env start", "test-unit-php-multisite": "wp-env run phpunit 'WP_MULTISITE=1 phpunit -c /var/www/html/wp-content/plugins/gutenberg/phpunit/multisite.xml --verbose'", "test-unit:native": "cd test/native/ && cross-env NODE_ENV=test jest --config ./jest.config.js", "test-unit:native:debug": "cd test/native/ && node --inspect ../../node_modules/.bin/jest --runInBand --config ./jest.config.js", "prestorybook:build": "npm run build:packages", "storybook:build": "build-storybook -c ./storybook -o ./playground/dist", "prestorybook:dev": "npm run build:packages", "storybook:dev": "concurrently \"npm run dev:packages\" \"start-storybook -c ./storybook -p 50240\"", "design-system:build": "echo \"Please use storybook:build instead.\"", "design-system:dev": "echo \"Please use storybook:dev instead.\"", "playground:build": "npm run storybook:build", "playground:dev": "echo \"Please use storybook:dev instead.\"", "env": "wp-scripts env", "wp-env": "packages/env/bin/wp-env" }, "husky": { "hooks": { "pre-commit": "lint-staged" } }, "lint-staged": { "package-lock.json": [ "npm run lint-lockfile", "node ./bin/check-latest-npm.js" ], "packages/*/package.json": [ "wp-scripts lint-pkg-json" ], "*.scss": [ "wp-scripts lint-style" ], "*.js": [ "wp-scripts format-js", "wp-scripts lint-js" ], "{docs/{toc.json,tool/*.js},packages/{*/README.md,components/src/*/**/README.md}}": [ "node ./docs/tool/index.js" ], "packages/**/*.js": [ "node ./bin/api-docs/update-api-docs.js", "node ./bin/api-docs/are-api-docs-unstaged.js", "node ./bin/packages/lint-staged-typecheck.js" ] }, "wp-env": { "plugin-dir": "gutenberg", "plugin-name": "Gutenberg", "docker-template": "./bin/docker-compose.override.yml.template", "welcome-logo": [ ",⁻⁻⁻· . |", "| ،⁓’. . |--- ,---. ,---. |---. ,---. ,---. ,---.", "| | | | | |---' | | | | |---' | | |", "`---' `---' `---’ `---’ ' ` `---' `---’ ` `---|", " `---'" ], "welcome-build-command": "npm run dev" } }
{ "pile_set_name": "Github" }
[ { "outputFile": "E:\\AndroidStudioProjects\\WoChat\\easeui\\build\\intermediates\\res\\merged\\androidTest\\debug\\values-v11\\values-v11.xml", "map": [ { "to": { "startLine": 2, "startColumn": 4, "startOffset": 55, "endLine": 4, "endColumn": 12, "endOffset": 219 }, "from": { "file": "E:\\AndroidStudioProjects\\WoChat\\easeui\\build\\intermediates\\bundles\\debug\\res\\values-v11\\values-v11.xml", "position": { "startLine": 2, "startColumn": 4, "startOffset": 55, "endLine": 4, "endColumn": 12, "endOffset": 219 } } }, { "to": { "startLine": 5, "startColumn": 4, "startOffset": 224, "endLine": 7, "endColumn": 12, "endOffset": 394 }, "from": { "file": "E:\\AndroidStudioProjects\\WoChat\\easeui\\build\\intermediates\\bundles\\debug\\res\\values-v11\\values-v11.xml", "position": { "startLine": 5, "startColumn": 4, "startOffset": 224, "endLine": 7, "endColumn": 12, "endOffset": 394 } } }, { "to": { "startLine": 8, "startColumn": 4, "startOffset": 399, "endColumn": 84, "endOffset": 479 }, "from": { "file": "E:\\AndroidStudioProjects\\WoChat\\easeui\\build\\intermediates\\bundles\\debug\\res\\values-v11\\values-v11.xml", "position": { "startLine": 8, "startColumn": 4, "startOffset": 399, "endColumn": 84, "endOffset": 479 } } } ] } ]
{ "pile_set_name": "Github" }
optimal_raid=1 default_actions=1 bfa.worldvein_allies=5 T25_Death_Knight_Blood.simc T25_Death_Knight_Frost.simc T25_Death_Knight_Unholy.simc T25_Demon_Hunter_Havoc.simc T25_Demon_Hunter_Vengeance.simc T25_Druid_Balance.simc T25_Druid_Feral.simc # T25_Druid_Restoration.simc T25_Druid_Guardian.simc T25_Hunter_Beast_Mastery.simc T25_Hunter_Marksmanship.simc T25_Hunter_Survival.simc T25_Mage_Fire.simc T25_Mage_Frost.simc T25_Mage_Arcane.simc T25_Monk_Brewmaster.simc T25_Monk_Windwalker.simc T25_Monk_Windwalker_Serenity.simc T25_Paladin_Protection.simc T25_Paladin_Retribution.simc T25_Priest_Shadow.simc T25_Rogue_Assassination.simc T25_Rogue_Outlaw.simc T25_Rogue_Subtlety.simc T25_Shaman_Elemental.simc T25_Shaman_Enhancement.simc T25_Shaman_Restoration.simc T25_Warlock_Affliction.simc T25_Warlock_Demonology.simc T25_Warlock_Destruction.simc T25_Warrior_Arms.simc T25_Warrior_Fury.simc T25_Warrior_Protection.simc
{ "pile_set_name": "Github" }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import com.adobe.test.Assert; import com.adobe.test.Utils; var CODE = 1074; // Illegal write to read-only property _ on _. //----------------------------------------------------------- //----------------------------------------------------------- try { var z = "no error"; Object = new Object(); Object.valueOf = Number.prototype.valueOf; } catch (err) { z = err.toString(); } finally { Assert.expectEq("Runtime Error", Utils.REFERENCEERROR + CODE, Utils.referenceError(z)); } //----------------------------------------------------------- //-----------------------------------------------------------
{ "pile_set_name": "Github" }
#include "alsa.h" /******************************************************** Audio Tools, a module and set of tools for manipulating audio data Copyright (C) 2007-2016 Brian Langenberger further modified by Brian Langenberger for use in Python Audio Tools 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 *******************************************************/ static int play_8_bps(output_ALSAAudio *self, pcm_FrameList *framelist); static int play_16_bps(output_ALSAAudio *self, pcm_FrameList *framelist); static int play_24_bps(output_ALSAAudio *self, pcm_FrameList *framelist); static PyObject* ALSAAudio_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { output_ALSAAudio *self; self = (output_ALSAAudio *)type->tp_alloc(type, 0); return (PyObject *)self; } int ALSAAudio_init(output_ALSAAudio *self, PyObject *args, PyObject *kwds) { PyObject *audiotools_pcm = NULL; char *device; int sample_rate = 44100; int channels = 2; int bits_per_sample = 16; int error; snd_pcm_format_t output_format = SND_PCM_FORMAT_S16_LE; self->framelist_type = NULL; self->output = NULL; self->mixer = NULL; self->mixer_elem = NULL; self->buffer_size = 0; /*get FrameList type for comparison during .play() operation*/ if ((audiotools_pcm = open_audiotools_pcm()) != NULL) { self->framelist_type = PyObject_GetAttrString(audiotools_pcm, "FrameList"); Py_DECREF(audiotools_pcm); if (self->framelist_type == NULL) { /*unable to get audiotools.pcm.FrameList type*/ return -1; } } else { /*unable to open audiotools.pcm module*/ return -1; } if (!PyArg_ParseTuple(args, "siii", &device, &sample_rate, &channels, &bits_per_sample)) return -1; /*sanity check output parameters*/ if (sample_rate > 0) { self->sample_rate = sample_rate; } else { PyErr_SetString( PyExc_ValueError, "sample rate must be a postive value"); return -1; } if (channels > 0) { self->channels = channels; } else { PyErr_SetString( PyExc_ValueError, "channels must be a positive value"); return -1; } switch (bits_per_sample) { case 8: self->bits_per_sample = bits_per_sample; self->buffer.int8 = NULL; self->play = play_8_bps; output_format = SND_PCM_FORMAT_S8; break; case 16: self->bits_per_sample = bits_per_sample; self->buffer.int16 = NULL; self->play = play_16_bps; output_format = SND_PCM_FORMAT_S16; break; case 24: self->bits_per_sample = bits_per_sample; self->buffer.int32 = NULL; self->play = play_24_bps; output_format = SND_PCM_FORMAT_S32; //output_format = SND_PCM_FORMAT_FLOAT; break; default: PyErr_SetString( PyExc_ValueError, "bits-per-sample must be 8, 16 or 24"); return -1; } if ((error = snd_pcm_open(&self->output, device, SND_PCM_STREAM_PLAYBACK, 0)) < 0) { PyErr_SetString(PyExc_IOError, "unable to open ALSA output handle"); return -1; } if ((error = snd_pcm_set_params(self->output, output_format, SND_PCM_ACCESS_RW_INTERLEAVED, channels, sample_rate, 1, 500000)) < 0) { PyErr_SetString(PyExc_IOError, "unable to set ALSA stream parameters"); return -1; } if ((error = snd_mixer_open(&self->mixer, 0)) < 0) { /*unable to open ALSA mixer*/ self->mixer = NULL; return 0; } else if ((error = snd_mixer_attach(self->mixer, device)) < 0) { /*unable to attach mixer to card*/ snd_mixer_close(self->mixer); self->mixer = NULL; return 0; } else if ((error = snd_mixer_selem_register(self->mixer, NULL, NULL)) < 0) { /*unable to register mixer*/ snd_mixer_close(self->mixer); self->mixer = NULL; return 0; } else if ((error = snd_mixer_load(self->mixer)) < 0) { /*unable to load mixer*/ snd_mixer_close(self->mixer); self->mixer = NULL; return 0; } /*walk through mixer elements to find Master or PCM*/ self->mixer_elem = find_playback_mixer_element(self->mixer, "Master"); if (self->mixer_elem == NULL) { /*this may be NULL if no Master or PCM found*/ self->mixer_elem = find_playback_mixer_element(self->mixer, "PCM"); } if (self->mixer_elem != NULL) { snd_mixer_selem_get_playback_volume_range(self->mixer_elem, &self->volume_min, &self->volume_max); } return 0; } static snd_mixer_elem_t* find_playback_mixer_element(snd_mixer_t *mixer, const char *name) { snd_mixer_elem_t *mixer_elem; for (mixer_elem = snd_mixer_first_elem(mixer); mixer_elem != NULL; mixer_elem = snd_mixer_elem_next(mixer_elem)) { const char *elem_name = snd_mixer_selem_get_name(mixer_elem); if ((elem_name != NULL) && snd_mixer_selem_has_playback_volume(mixer_elem) && (!strcmp(name, elem_name))) { return mixer_elem; } } return NULL; } void ALSAAudio_dealloc(output_ALSAAudio *self) { Py_XDECREF(self->framelist_type); if (self->output != NULL) snd_pcm_close(self->output); if (self->mixer != NULL) snd_mixer_close(self->mixer); switch (self->bits_per_sample) { case 8: free(self->buffer.int8); break; case 16: free(self->buffer.int16); break; case 24: free(self->buffer.int32); break; } Py_TYPE(self)->tp_free((PyObject*)self); } static PyObject* ALSAAudio_play(output_ALSAAudio *self, PyObject *args) { pcm_FrameList *framelist; PyThreadState *state; int status; if (!PyArg_ParseTuple(args, "O!", self->framelist_type, &framelist)) return NULL; if (framelist->bits_per_sample != self->bits_per_sample) { PyErr_SetString(PyExc_ValueError, "FrameList has different bits_per_sample than stream"); return NULL; } if (framelist->channels != self->channels) { PyErr_SetString(PyExc_ValueError, "FrameList has different channels than stream"); return NULL; } state = PyEval_SaveThread(); if ((status = self->play(self, framelist)) != 0) { switch (status) { case EBADFD: PyEval_RestoreThread(state); PyErr_SetString(PyExc_IOError, "PCM not in correct state"); return NULL; case EPIPE: PyEval_RestoreThread(state); PyErr_SetString(PyExc_IOError, "buffer underrun occurred"); return NULL; case ESTRPIPE: PyEval_RestoreThread(state); PyErr_SetString(PyExc_IOError, "suspend event occurred"); return NULL; default: PyEval_RestoreThread(state); PyErr_SetString(PyExc_IOError, "unknown ALSA write error"); return NULL; } } else { PyEval_RestoreThread(state); Py_INCREF(Py_None); return Py_None; } } static int play_8_bps(output_ALSAAudio *self, pcm_FrameList *framelist) { unsigned i; const unsigned samples_length = FrameList_samples_length(framelist); snd_pcm_uframes_t to_write = framelist->frames; snd_pcm_sframes_t frames_written; /*resize internal buffer if needed*/ if (self->buffer_size < samples_length) { self->buffer_size = samples_length; self->buffer.int8 = realloc(self->buffer.int8, self->buffer_size * sizeof(int8_t)); } /*transfer framelist data to buffer*/ for (i = 0; i < samples_length; i++) { self->buffer.int8[i] = framelist->samples[i]; } /*output data to ALSA*/ while (to_write > 0) { frames_written = snd_pcm_writei(self->output, self->buffer.int8, to_write); if (frames_written < 0) { /*try to recover a single time*/ frames_written = snd_pcm_recover(self->output, frames_written, 1); } if (frames_written >= 0) { to_write -= frames_written; } else { return -frames_written; } } return 0; } static int play_16_bps(output_ALSAAudio *self, pcm_FrameList *framelist) { const unsigned samples_length = FrameList_samples_length(framelist); unsigned i; snd_pcm_uframes_t to_write = framelist->frames; snd_pcm_sframes_t frames_written; /*resize internal buffer if needed*/ if (self->buffer_size < samples_length) { self->buffer_size = samples_length; self->buffer.int16 = realloc(self->buffer.int16, self->buffer_size * sizeof(int16_t)); } /*transfer framelist data to buffer*/ for (i = 0; i < samples_length; i++) { self->buffer.int16[i] = framelist->samples[i]; } /*output data to ALSA*/ while (to_write > 0) { frames_written = snd_pcm_writei(self->output, self->buffer.int16, to_write); if (frames_written < 0) { /*try to recover a single time*/ frames_written = snd_pcm_recover(self->output, frames_written, 1); } if (frames_written >= 0) { to_write -= frames_written; } else { return -frames_written; } } return 0; } static int play_24_bps(output_ALSAAudio *self, pcm_FrameList *framelist) { const unsigned samples_length = FrameList_samples_length(framelist); unsigned i; snd_pcm_uframes_t to_write = framelist->frames; snd_pcm_sframes_t frames_written; /*resize internal buffer if needed*/ if (self->buffer_size < samples_length) { self->buffer_size = samples_length; self->buffer.int32 = realloc(self->buffer.int32, self->buffer_size * sizeof(int32_t)); } /*transfer framelist data to buffer*/ for (i = 0; i < samples_length; i++) { self->buffer.int32[i] = (framelist->samples[i] << 8); } /*output data to ALSA*/ while (to_write > 0) { frames_written = snd_pcm_writei(self->output, self->buffer.int32, to_write); if (frames_written < 0) { /*try to recover a single time*/ frames_written = snd_pcm_recover(self->output, frames_written, 1); } if (frames_written >= 0) { to_write -= frames_written; } else { return -frames_written; } } return 0; } static PyObject* ALSAAudio_pause(output_ALSAAudio *self, PyObject *args) { snd_pcm_pause(self->output, 1); Py_INCREF(Py_None); return Py_None; } static PyObject* ALSAAudio_resume(output_ALSAAudio *self, PyObject *args) { snd_pcm_pause(self->output, 0); Py_INCREF(Py_None); return Py_None; } static PyObject* ALSAAudio_flush(output_ALSAAudio *self, PyObject *args) { /*FIXME*/ Py_INCREF(Py_None); return Py_None; } static PyObject* ALSAAudio_get_volume(output_ALSAAudio *self, PyObject *args) { if (self->mixer_elem) { /*get the average volume from all supported output channels*/ const snd_mixer_selem_channel_id_t channels[] = { SND_MIXER_SCHN_FRONT_LEFT, SND_MIXER_SCHN_FRONT_RIGHT, SND_MIXER_SCHN_REAR_LEFT, SND_MIXER_SCHN_REAR_RIGHT, SND_MIXER_SCHN_FRONT_CENTER, SND_MIXER_SCHN_WOOFER, SND_MIXER_SCHN_SIDE_LEFT, SND_MIXER_SCHN_SIDE_RIGHT, SND_MIXER_SCHN_REAR_CENTER}; const size_t channel_count = sizeof(channels) / sizeof(snd_mixer_selem_channel_id_t); size_t i; double total_volume = 0.0; unsigned total_channels = 0; for (i = 0; i < channel_count; i++) { long channel_volume; if (snd_mixer_selem_has_playback_channel(self->mixer_elem, channels[i]) && (snd_mixer_selem_get_playback_volume(self->mixer_elem, channels[i], &channel_volume) == 0)) { total_volume += channel_volume; total_channels++; } } if (total_channels > 0) { const double average_volume = total_volume / total_channels; /*convert to range min_volume->max_volume*/ return PyFloat_FromDouble(average_volume / self->volume_max); } else { return PyFloat_FromDouble(0.0); } } else { return PyFloat_FromDouble(0.0); } } static PyObject* ALSAAudio_set_volume(output_ALSAAudio *self, PyObject *args) { double new_volume_d; long new_volume; if (!PyArg_ParseTuple(args, "d", &new_volume_d)) return NULL; if (self->mixer_elem) { new_volume = round(new_volume_d * self->volume_max); snd_mixer_selem_set_playback_volume_all(self->mixer_elem, new_volume); } Py_INCREF(Py_None); return Py_None; } static PyObject* ALSAAudio_close(output_ALSAAudio *self, PyObject *args) { /*FIXME*/ Py_INCREF(Py_None); return Py_None; }
{ "pile_set_name": "Github" }
/* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package generators import ( "io" "k8s.io/gengo/generator" "k8s.io/gengo/namer" "k8s.io/gengo/types" "github.com/golang/glog" ) // factoryInterfaceGenerator produces a file of interfaces used to break a dependency cycle for // informer registration type factoryInterfaceGenerator struct { generator.DefaultGen outputPackage string imports namer.ImportTracker clientSetPackage string filtered bool } var _ generator.Generator = &factoryInterfaceGenerator{} func (g *factoryInterfaceGenerator) Filter(c *generator.Context, t *types.Type) bool { if !g.filtered { g.filtered = true return true } return false } func (g *factoryInterfaceGenerator) Namers(c *generator.Context) namer.NameSystems { return namer.NameSystems{ "raw": namer.NewRawNamer(g.outputPackage, g.imports), } } func (g *factoryInterfaceGenerator) Imports(c *generator.Context) (imports []string) { imports = append(imports, g.imports.ImportLines()...) return } func (g *factoryInterfaceGenerator) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error { sw := generator.NewSnippetWriter(w, c, "{{", "}}") glog.V(5).Infof("processing type %v", t) m := map[string]interface{}{ "cacheSharedIndexInformer": c.Universe.Type(cacheSharedIndexInformer), "clientSetPackage": c.Universe.Type(types.Name{Package: g.clientSetPackage, Name: "Interface"}), "runtimeObject": c.Universe.Type(runtimeObject), "timeDuration": c.Universe.Type(timeDuration), "v1ListOptions": c.Universe.Type(v1ListOptions), } sw.Do(externalSharedInformerFactoryInterface, m) return sw.Error() } var externalSharedInformerFactoryInterface = ` type NewInformerFunc func({{.clientSetPackage|raw}}, {{.timeDuration|raw}}) cache.SharedIndexInformer // SharedInformerFactory a small interface to allow for adding an informer without an import cycle type SharedInformerFactory interface { Start(stopCh <-chan struct{}) InformerFor(obj {{.runtimeObject|raw}}, newFunc NewInformerFunc) {{.cacheSharedIndexInformer|raw}} } type TweakListOptionsFunc func(*{{.v1ListOptions|raw}}) `
{ "pile_set_name": "Github" }
color = { 124 212 121 } graphical_culture = ZuluGC party = { name = "ZUL_conservative" start_date = 1800.1.1 end_date = 2000.1.1 ideology = conservative economic_policy = state_capitalism trade_policy = protectionism religious_policy = moralism citizenship_policy = residency war_policy = pro_military } party = { name = "ZUL_liberal" start_date = 1820.1.1 end_date = 1936.1.1 ideology = liberal economic_policy = laissez_faire trade_policy = protectionism religious_policy = pluralism citizenship_policy = full_citizenship war_policy = pacifism } party = { name = "ZUL_reactionary" start_date = 1820.1.1 end_date = 2000.1.1 ideology = reactionary economic_policy = interventionism trade_policy = protectionism religious_policy = moralism citizenship_policy = residency war_policy = jingoism } party = { name = "ZUL_anarcho_liberal" start_date = 1830.1.1 end_date = 2000.1.1 ideology = anarcho_liberal economic_policy = laissez_faire trade_policy = free_trade religious_policy = pro_atheism citizenship_policy = full_citizenship war_policy = pro_military } party = { name = "ZUL_socialist" start_date = 1848.1.1 end_date = 2000.1.1 ideology = socialist economic_policy = planned_economy trade_policy = protectionism religious_policy = secularized citizenship_policy = full_citizenship war_policy = anti_military } party = { name = "ZUL_communist" start_date = 1848.1.1 end_date = 2000.1.1 ideology = communist economic_policy = planned_economy trade_policy = protectionism religious_policy = pro_atheism citizenship_policy = full_citizenship war_policy = pro_military } party = { name = "ZUL_fascist" start_date = 1905.1.1 end_date = 2000.1.1 ideology = fascist economic_policy = state_capitalism trade_policy = protectionism religious_policy = moralism citizenship_policy = residency war_policy = jingoism } unit_names = { dreadnought = { "Shaka Zulu" KwaZulu Assegai Dingane Dziva Mwari Dzivaguru Mulungu Mbonga Svikiro Mazendere "Mai Vedu" Musikavanhu Mutorwa } ironclad = { "Shaka Zulu" KwaZulu Assegai Dingane Dziva Mwari Dzivaguru Mulungu Mbonga Svikiro Mazendere "Mai Vedu" Musikavanhu Mutorwa } manowar = { "Shaka Zulu" KwaZulu Assegai Dingane Dziva Mwari Dzivaguru Mulungu Mbonga Svikiro Mazendere "Mai Vedu" Musikavanhu Mutorwa } cruiser = { "Shaka Zulu" KwaZulu Assegai Dingane Dziva Mwari Dzivaguru Mulungu Mbonga Svikiro Mazendere "Mai Vedu" Musikavanhu Mutorwa } frigate = { "Shaka Zulu" KwaZulu Assegai Dingane Dziva Mwari Dzivaguru Mulungu Mbonga Svikiro Mazendere "Mai Vedu" Musikavanhu Mutorwa } monitor = { "Shaka Zulu" KwaZulu Assegai Dingane Dziva Mwari Dzivaguru Mulungu Mbonga Svikiro Mazendere "Mai Vedu" Musikavanhu Mutorwa } clipper_transport = { } steam_transport = { } commerce_raider = { "Shaka Zulu" KwaZulu Assegai Dingane Dziva Mwari Dzivaguru Mulungu Mbonga Svikiro Mazendere "Mai Vedu" Musikavanhu Mutorwa } }
{ "pile_set_name": "Github" }
//! Tests auto-converted from "sass-spec/spec/libsass-closed-issues/issue_1169/error" #[allow(unused)] use super::rsass; // From "sass-spec/spec/libsass-closed-issues/issue_1169/error/color.hrx" // Ignoring "color", error tests are not supported yet. // From "sass-spec/spec/libsass-closed-issues/issue_1169/error/functioncall.hrx" // Ignoring "functioncall", error tests are not supported yet. // From "sass-spec/spec/libsass-closed-issues/issue_1169/error/interpolate.hrx" // Ignoring "interpolate", error tests are not supported yet. // From "sass-spec/spec/libsass-closed-issues/issue_1169/error/simple.hrx" #[test] #[ignore] // wrong result fn simple() { assert_eq!( rsass( "$map: (\r\ \n red: \'bar\',\r\ \n #{red}: \'baz\',\r\ \n);\r\ \n\r\ \n.foo {\r\ \n content: inspect($map);\r\ \n}" ) .unwrap(), ".foo {\ \n content: (red: \"bar\", red: \"baz\");\ \n}\ \n" ); }
{ "pile_set_name": "Github" }
<?php /** * This file is part of PHPWord - A pure PHP library for reading and writing * word processing documents. * * PHPWord is free software distributed under the terms of the GNU Lesser * General Public License version 3 as published by the Free Software Foundation. * * For the full copyright and license information, please read the LICENSE * file that was distributed with this source code. For the full list of * contributors, visit https://github.com/PHPOffice/PHPWord/contributors. * * @see https://github.com/PHPOffice/PHPWord * @copyright 2010-2018 PHPWord contributors * @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3 */ namespace PhpOffice\PhpWord\Writer\HTML\Element; /** * ListItem element HTML writer * * @since 0.10.0 */ class ListItemRun extends TextRun { /** * Write list item * * @return string */ public function write() { if (!$this->element instanceof \PhpOffice\PhpWord\Element\ListItemRun) { return ''; } $writer = new Container($this->parentWriter, $this->element); $content = $writer->write() . PHP_EOL; return $content; } }
{ "pile_set_name": "Github" }
/* Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package v1 import ( "k8s.io/apimachinery/pkg/runtime" ) // Where possible, json tags match the cli argument names. // Top level config objects and all values required for proper functioning are not "omitempty". Any truly optional piece of config is allowed to be omitted. // Config holds the information needed to build connect to remote kubernetes clusters as a given user // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object type Config struct { // Legacy field from pkg/api/types.go TypeMeta. // TODO(jlowdermilk): remove this after eliminating downstream dependencies. // +k8s:conversion-gen=false // +optional Kind string `json:"kind,omitempty"` // Legacy field from pkg/api/types.go TypeMeta. // TODO(jlowdermilk): remove this after eliminating downstream dependencies. // +k8s:conversion-gen=false // +optional APIVersion string `json:"apiVersion,omitempty"` // Preferences holds general information to be use for cli interactions Preferences Preferences `json:"preferences"` // Clusters is a map of referencable names to cluster configs Clusters []NamedCluster `json:"clusters"` // AuthInfos is a map of referencable names to user configs AuthInfos []NamedAuthInfo `json:"users"` // Contexts is a map of referencable names to context configs Contexts []NamedContext `json:"contexts"` // CurrentContext is the name of the context that you would like to use by default CurrentContext string `json:"current-context"` // Extensions holds additional information. This is useful for extenders so that reads and writes don't clobber unknown fields // +optional Extensions []NamedExtension `json:"extensions,omitempty"` } type Preferences struct { // +optional Colors bool `json:"colors,omitempty"` // Extensions holds additional information. This is useful for extenders so that reads and writes don't clobber unknown fields // +optional Extensions []NamedExtension `json:"extensions,omitempty"` } // Cluster contains information about how to communicate with a kubernetes cluster type Cluster struct { // Server is the address of the kubernetes cluster (https://hostname:port). Server string `json:"server"` // TLSServerName is used to check server certificate. If TLSServerName is empty, the hostname used to contact the server is used. // +optional TLSServerName string `json:"tls-server-name,omitempty"` // InsecureSkipTLSVerify skips the validity check for the server's certificate. This will make your HTTPS connections insecure. // +optional InsecureSkipTLSVerify bool `json:"insecure-skip-tls-verify,omitempty"` // CertificateAuthority is the path to a cert file for the certificate authority. // +optional CertificateAuthority string `json:"certificate-authority,omitempty"` // CertificateAuthorityData contains PEM-encoded certificate authority certificates. Overrides CertificateAuthority // +optional CertificateAuthorityData []byte `json:"certificate-authority-data,omitempty"` // Extensions holds additional information. This is useful for extenders so that reads and writes don't clobber unknown fields // +optional Extensions []NamedExtension `json:"extensions,omitempty"` } // AuthInfo contains information that describes identity information. This is use to tell the kubernetes cluster who you are. type AuthInfo struct { // ClientCertificate is the path to a client cert file for TLS. // +optional ClientCertificate string `json:"client-certificate,omitempty"` // ClientCertificateData contains PEM-encoded data from a client cert file for TLS. Overrides ClientCertificate // +optional ClientCertificateData []byte `json:"client-certificate-data,omitempty"` // ClientKey is the path to a client key file for TLS. // +optional ClientKey string `json:"client-key,omitempty"` // ClientKeyData contains PEM-encoded data from a client key file for TLS. Overrides ClientKey // +optional ClientKeyData []byte `json:"client-key-data,omitempty"` // Token is the bearer token for authentication to the kubernetes cluster. // +optional Token string `json:"token,omitempty"` // TokenFile is a pointer to a file that contains a bearer token (as described above). If both Token and TokenFile are present, Token takes precedence. // +optional TokenFile string `json:"tokenFile,omitempty"` // Impersonate is the username to imperonate. The name matches the flag. // +optional Impersonate string `json:"as,omitempty"` // ImpersonateGroups is the groups to imperonate. // +optional ImpersonateGroups []string `json:"as-groups,omitempty"` // ImpersonateUserExtra contains additional information for impersonated user. // +optional ImpersonateUserExtra map[string][]string `json:"as-user-extra,omitempty"` // Username is the username for basic authentication to the kubernetes cluster. // +optional Username string `json:"username,omitempty"` // Password is the password for basic authentication to the kubernetes cluster. // +optional Password string `json:"password,omitempty"` // AuthProvider specifies a custom authentication plugin for the kubernetes cluster. // +optional AuthProvider *AuthProviderConfig `json:"auth-provider,omitempty"` // Exec specifies a custom exec-based authentication plugin for the kubernetes cluster. // +optional Exec *ExecConfig `json:"exec,omitempty"` // Extensions holds additional information. This is useful for extenders so that reads and writes don't clobber unknown fields // +optional Extensions []NamedExtension `json:"extensions,omitempty"` } // Context is a tuple of references to a cluster (how do I communicate with a kubernetes cluster), a user (how do I identify myself), and a namespace (what subset of resources do I want to work with) type Context struct { // Cluster is the name of the cluster for this context Cluster string `json:"cluster"` // AuthInfo is the name of the authInfo for this context AuthInfo string `json:"user"` // Namespace is the default namespace to use on unspecified requests // +optional Namespace string `json:"namespace,omitempty"` // Extensions holds additional information. This is useful for extenders so that reads and writes don't clobber unknown fields // +optional Extensions []NamedExtension `json:"extensions,omitempty"` } // NamedCluster relates nicknames to cluster information type NamedCluster struct { // Name is the nickname for this Cluster Name string `json:"name"` // Cluster holds the cluster information Cluster Cluster `json:"cluster"` } // NamedContext relates nicknames to context information type NamedContext struct { // Name is the nickname for this Context Name string `json:"name"` // Context holds the context information Context Context `json:"context"` } // NamedAuthInfo relates nicknames to auth information type NamedAuthInfo struct { // Name is the nickname for this AuthInfo Name string `json:"name"` // AuthInfo holds the auth information AuthInfo AuthInfo `json:"user"` } // NamedExtension relates nicknames to extension information type NamedExtension struct { // Name is the nickname for this Extension Name string `json:"name"` // Extension holds the extension information Extension runtime.RawExtension `json:"extension"` } // AuthProviderConfig holds the configuration for a specified auth provider. type AuthProviderConfig struct { Name string `json:"name"` Config map[string]string `json:"config"` } // ExecConfig specifies a command to provide client credentials. The command is exec'd // and outputs structured stdout holding credentials. // // See the client.authentiction.k8s.io API group for specifications of the exact input // and output format type ExecConfig struct { // Command to execute. Command string `json:"command"` // Arguments to pass to the command when executing it. // +optional Args []string `json:"args"` // Env defines additional environment variables to expose to the process. These // are unioned with the host's environment, as well as variables client-go uses // to pass argument to the plugin. // +optional Env []ExecEnvVar `json:"env"` // Preferred input version of the ExecInfo. The returned ExecCredentials MUST use // the same encoding version as the input. APIVersion string `json:"apiVersion,omitempty"` } // ExecEnvVar is used for setting environment variables when executing an exec-based // credential plugin. type ExecEnvVar struct { Name string `json:"name"` Value string `json:"value"` }
{ "pile_set_name": "Github" }
# make sure that your dns has a cname set for prometheus and that your prometheus container is not using a base url server { listen 443 ssl; listen [::]:443 ssl; server_name prometheus.*; include /config/nginx/ssl.conf; client_max_body_size 0; # enable for ldap auth, fill in ldap details in ldap.conf #include /config/nginx/ldap.conf; # enable for Authelia #include /config/nginx/authelia-server.conf; location / { # enable the next two lines for http auth #auth_basic "Restricted"; #auth_basic_user_file /config/nginx/.htpasswd; # enable the next two lines for ldap auth #auth_request /auth; #error_page 401 =200 /ldaplogin; # enable for Authelia #include /config/nginx/authelia-location.conf; include /config/nginx/proxy.conf; resolver 127.0.0.11 valid=30s; set $upstream_app prometheus; set $upstream_port 9090; set $upstream_proto http; proxy_pass $upstream_proto://$upstream_app:$upstream_port; } }
{ "pile_set_name": "Github" }
--- name: Bug report about: Create a report to help us improve --- **What version of protobuf and what language are you using?** Version: (e.g., `v1.1.0`, `89a0c16f`, etc) **What did you do?** If possible, provide a recipe for reproducing the error. A complete runnable program is good with `.proto` and `.go` source code. **What did you expect to see?** **What did you see instead?** Make sure you include information that can help us debug (full error message, exception listing, stack trace, logs). **Anything else we should know about your project / environment?**
{ "pile_set_name": "Github" }
#usda 1.0 class "_class_Sarah" { custom color3d displayColor = (1, 1, 1) } def "Sarah" ( add references = @test.usda@</Sarah_Defaults> add variantSets = ["displayColor", "standin"] add inherits = </_class_Sarah> variants = { string displayColor = "red" string lod = "full" } ) { custom color3d displayColor = (0.1, 0.2, 0.3) variantSet "displayColor" = { "green" { custom color3d displayColor = (0, 1, 0) } "red" { custom color3d displayColor = (1, 0, 0) } } variantSet "standin" = { "anim" { } "render" ( add variantSets = ["lod"] ) { variantSet "lod" = { "full" { def Scope "Geom" { def Cone "Cone" { } } } "lite" { def Scope "Geom" { def Sphere "Sphere" { } } } } } } } def "Sarah_Defaults" ( add references = @test.usda@</Sarah_Base> ) { custom color3d displayColor = (0, 0, 1) } def Scope "Sarah_Base" ( add variantSets = "displayColor" variants = { string displayColor = "red" } ) { variantSet "displayColor" = { "green" { custom color3d displayColor = (0, 0.8, 0) } "red" { custom color3d displayColor = (0.8, 0, 0) } } }
{ "pile_set_name": "Github" }
using System; /* */ namespace Heijden.DNS { public class RecordRRSIG : Record { public byte[] RDATA; public RecordRRSIG(RecordReader rr) { // re-read length ushort RDLENGTH = rr.ReadUInt16(-2); RDATA = rr.ReadBytes(RDLENGTH); } public override string ToString() { return string.Format("not-used"); } } }
{ "pile_set_name": "Github" }
------------------------------------------------------------------------------- -- AddOn namespace. ------------------------------------------------------------------------------- local FOLDER_NAME, private = ... private.ACHIEVEMENT_ZONE_IDS = { [104] = { 1312 }; --Shadowmoon valley (BC) [109] = { 1312 }; --Netherstorm (BC) [100] = { 1312 }; --Hellfire peninsula (BC) [105] = { 1312 }; --Blades edge mountains (BC) [102] = { 1312 }; --Zangarmarsh (BC) [108] = { 1312 }; --Terokkar forest (BC) [107] = { 1312 }; --Nagrand (BC) [119] = { 2257 }; --Sholazar basin (WOLK) [120] = { 2257 }; --The storm peaks (WOLK) [114] = { 2257 }; --Borean tundra (WOLK) [117] = { 2257 }; --Howling fjord (WOLK) [121] = { 2257 }; --Zul drak (WOLK) [115] = { 2257 }; --Dragonblight (WOLK) [118] = { 2257 }; --Icecrown (WOLK) [116] = { 2257 }; --Grizzly hills (WOLK) [554] = { 8714 }; --Timeless isle (Pandaria) [555] = { 8714 }; --Cavern of lost spirits (Pandaria) [504] = { 8103 }; --Isle of thunder (Pandaria) [505] = { 8103 }; --Lightning vein mine (Pandaria) [371] = { 7439 }; --The jade forest (Pandaria) [379] = { 7439 }; --Kun lai summit (Pandaria) [422] = { 7439 }; --Dread wastes (Pandaria) [390] = { 7439 }; --Vale of eternal blossoms (Pandaria) [418] = { 7439 }; --Krasarang wilds (Pandaria) [376] = { 7439 }; --Valley of the four winds (Pandaria) [388] = { 7439 }; --Townlong steppes (Pandaria) [534] = { 10070 }; --Tanaan jungle (WOD) [630] = { 11261 }; --Azsuna (Legion) [650] = { 11264 }; --Highmountain (Legion) [658] = { 11264 }; --Highmountain30 (Legion) [641] = { 11262 }; --Val sharah (Legion) [680] = { 11265 }; --Suramar (Legion) [634] = { 11263 }; --Stormheim (Legion) [646] = { 11841 }; --Broken shore (Legion) [885] = { 12078 }; --Antoran wastes (Legion) [882] = { 12078 }; --Mac aree (Legion) [830] = { 12078 }; --Krokuun (Legion) [833] = { 12078 }; --Krokuun7 (Legion) [1165] = { 12851, 12944 }; --Zuldazar - Dazar'alor (BFA) [862] = { 12851, 12944 }; --Zuldazar (BFA) [863] = { 12771, 12942 }; --Nazmir (BFA) [864] = { 12849, 12943 }; --Vol'dun (BFA) [1161] = { 12852, 12939 }; --Tiragarde Sound - Boralus (BFA) [895] = { 12852, 12939 }; --Tiragarde Sound (BFA) [896] = { 12995, 12941 }; --Drustvar (BFA) [942] = { 12853, 12940 }; --Stormsong Valley (BFA) [1355] = { 13549, 13691 }; --Nazjatar (BFA) [1462] = { 13470 }; --Mechagon (BFA) } private.ACHIEVEMENT_TARGET_IDS = { [2257] = { 32517, 32495, 32358, 32377, 32398, 32409, 32422, 32438, 32471, 32481, 32630, 32487, 32501, 32357, 32361, 32386, 32400, 32417, 32429, 32447, 32475, 32485, 32500 }; --Frostbitten (Wrath of the Lich king) [1312] = { 18695, 18697, 18694, 18686, 18678, 18692, 18680, 18690, 18685, 18683, 18682, 18681, 18689, 18698, 17144, 18696, 18677, 20932, 18693, 18679 }; --Bloody Rare (Burning Crusade) [8714] = { 73158, 73161, 72245, 72193, 71864, 72048, 73277, 73282, 73166, 73704, 73170, 73171, 73173, 73167, 73279, 73174, 73666, 73160, 72909, 71919, 72045, 73854, 72769, 72775, 72808, 73163, 73157, 73169, 73175, 73172, 72970, 73281 }; --Timeless Champion (Pandaria) [8103] = { 50358, 69996, 69998, 70000, 70002, 69664, 69997, 69999, 70001, 70003 }; --Champions of Lei Shen (Pandaria) [7439] = { 50823, 50830, 50832, 50840, 50766, 50769, 50776, 50363, 50388, 50734, 50749, 50339, 50341, 50347, 50350, 50352, 50355, 50359, 50811, 50817, 50821, 50782, 50787, 50791, 50806, 51059, 50332, 50334, 50828, 50831, 50836, 50750, 50768, 50772, 50780, 50364, 50733, 50739, 50338, 50340, 50344, 50349, 50351, 50354, 50356, 50808, 50816, 50820, 50822, 50783, 50789, 50805, 51078, 50331, 50333, 50336 }; --Glorious! (Pandaria) [10070] = { 91374, 91087, 90429, 90437, 90442, 90024, 90782, 91695, 93002, 91243, 93001, 90884, 90887, 90936, 92429, 92508, 92465, 92552, 92627, 92694, 93028, 93125, 92766, 92819, 93279, 91871, 90094, 92647, 92408, 93264, 91093, 91098, 90438, 90434, 90519, 92451, 92274, 92887, 91232, 93057, 92977, 90885, 90888, 92197, 92495, 92517, 92574, 92606, 92636, 92941, 93076, 93168, 92817, 92657, 91727, 90122, 93236, 91009, 92411, 89675 }; --Jungle Stalker (WOD) [11261] = { 89650, 89846, 89865, 90057, 90217, 90505, 90901, 91187, 91579, 106990, 109504, 107657, 107269, 89816, 89850, 89884, 90164, 90244, 90803, 91115, 91100, 105938, 107127, 112637, 112636, 107113, 89016 }; --Adventurer of Azsuna (Legion) [11264] = { 101077, 97933, 96590, 95872, 97203, 96410, 97593, 97102, 96621, 98024, 98311, 97653, 97345, 97326, 100302, 109498, 100303, 109501, 109500, 97220, 97449, 98299, 100232, 100230, 100231, 100495, 97093, 98890 }; --Adventurer of Highmountain (Legion) [11262] = { 92117, 92423, 93030, 92334, 94414, 95123, 95318, 97517, 109708, 92180, 92965, 93205, 94485, 95221, 97504, 98241, 110562, 93679 }; --Adventurer of Val'sharah (Legion) [11265] = { 99610, 100864, 103214, 103575, 105547, 107846, 109954, 110340, 110577, 110726, 110832, 110944, 111197, 111649, 111653, 112802, 99792, 103183, 103223, 103841, 106351, 109054, 110024, 110438, 110656, 110824, 110870, 111007, 111329, 111651, 112497, 102303 }; --Adventurer of Suramar (Legion) [11263] = { 91529, 91803, 91892, 92152, 92604, 92613, 92609, 92611, 92631, 92634, 92626, 92633, 92751, 93166, 93401, 97630, 98268, 98503, 110363, 91795, 91874, 92040, 92599, 92685, 92763, 93371, 94413, 98188, 98421, 107926, 90139 }; --Adventurer of Stormheim (Legion) [11841] = { 120583, 120665, 120681, 120641, 120675, 120686 }; --Naxt Victim (Legion) [12078] = { 127705, 127376, 123689, 122958, 120393, 127700, 127706, 125388, 125820, 126115, 125824, 122912, 124775, 126815, 126860, 126864, 126866, 126868, 126885, 126889, 126898, 124440, 125498, 126908, 126912, 126338, 127300, 126254, 127084, 126946, 127118, 122838, 122999, 122947, 127581, 127703, 124804, 125479, 126199, 126040, 126419, 122911, 123464, 126852, 126862, 126865, 126867, 126869, 126887, 126896, 126899, 125497, 126900, 126910, 126913, 127288, 127291, 127090, 127096, 126208 }; --Commander of Argus (Legion) [13027] = { 143316, 143313, 143314, 143311 }; --Mushroom Harvest (BFA) [12851] = { 276735, 279609, 277561, 284454, 288596, 281092, 281655, 281898, 284455, 290725 }; --Treasures of Zuldazar (BFA) [12944] = { 129961, 136428, 131476, 129343, 127939, 120899, 122004, 134738, 133842, 133190, 132244, 131687, 129954, 136413, 131233, 128699, 126637, 124185, 134760, 134048, 134049, 134782, 133155, 131718 }; --Adventurer of Zuldazar (BFA) [12771] = { 280504, 279253, 277715, 279689, 278436, 280522, 279260, 278437, 279299, 277885 }; --Treasures of Nazmir (BFA) [12942] = { 125250, 134293, 128965, 134296, 125232, 121242, 128974, 133373, 124397, 134295, 134294, 127820, 126460, 126907, 129657, 133539, 134298, 126635, 129005, 126187, 127001, 128426, 124399, 133527, 125214, 126142, 127873, 126056, 126926, 133531, 133812, 128935, 128930 }; --Adventurer of Nazmir (BFA) [12849] = { 280951, 287304, 287320, 287326, 294317, 287318, 287324, 294316, 294319, 287239 }; --Treasures of Vol'dun (BFA) [12943] = { 135852, 128553, 129476, 136346, 136335, 130443, 136341, 137681, 136340, 136336, 134571, 136304, 129180, 134625, 130439, 128497, 136393, 136390, 124722, 128674, 129283, 128686, 128951, 127776, 136338, 134745, 130401, 134638, 129411 }; --Adventurer of Vol'dun (BFA) [12852] = { 293962, 293965, 281397, 293964, 293881, 130350, 131453, 293852, 293884, 293880, 292686, 292673, 292674, 292675, 292676, 292677 }; --Treasures of Tiragarde Sound (BFA) [12939] = { 132182, 132068, 139145, 132088, 132211, 139233, 134106, 139205, 132179, 127289, 139285, 139135, 133356, 131389, 132076, 129181, 132086, 130508, 139152, 132127, 131520, 139290, 131252, 131262, 139278, 139287, 132280, 139280, 139289, 139235, 131984, 137180 }; --Adventurer of Tiragarde Sound (BFA) [12995] = { 297825, 297891, 297893, 297828, 297892, 297879, 297878, 297881, 298920, 297880 }; --Treasures of Drustvar (BFA) [12941] = { 124548, 127333, 127765, 127844, 128973, 127129, 129805, 129995, 130143, 134213, 135796, 137824, 138618, 138863, 139321, 125453, 127651, 126621, 127877, 127901, 129904, 128707, 129835, 129950, 130138, 132319, 134754, 137529, 137825, 138675, 138871, 138870, 138866, 139322, 134706 }; --Adventurer of Drustvar (BFA) [12853] = { 289647, 281494, 284448, 293349, 294173, 280619, 282153, 279042, 293350, 294174 }; --Treasures of Stormsong Valley (BFA) [12940] = { 141175, 138938, 136189, 139319, 132007, 141029, 141286, 141059, 140938, 136183, 135939, 141226, 141039, 129803, 130079, 141239, 139980, 140997, 139328, 134884, 137025, 142088, 131404, 139298, 139385, 134897, 135947, 141088, 130897, 141143, 138963, 139988, 140925, 139515 }; --Adventurer of Stormsong Valley (BFA) [13549] = { 306409, 326394, 326401, 326402, 326403, 326404, 326405, 326406, 326407, 326408, 326419, 326417, 326416, 326415, 326414, 326413, 326412, 326411, 326410, 326409, 326418, 326400, 326399, 326398, 326397, 326396, 326395, 329783, 332220 }; -- Trove Tracker (BFA) [13691] = { 152415, 152794, 150191, 152712, 152464, 152756, 152414, 152553, 152567, 144644, 152397, 152682, 151870, 152548, 152542, 153658, 152290, 153928, 152360, 151719, 152416, 152566, 152361, 149653, 152556, 152291, 152555, 152448, 152323, 152465, 152681, 150583, 152795, 152545, 152552, 152359, 153898, 154148, 152568, 150468 }; -- I Thought You Said They'd Be Rare? (BFA) [13470] = { 151124, 151672, 151702, 151934, 151884, 151569, 152001, 151940, 153000, 151933, 150342, 153205, 153200, 153226, 151627, 152764, 154225, 154739, 151625, 151684, 150575, 152007, 151202, 151296, 151308, 150937, 152182, 152569, 153206, 152764, 152113, 153228, 150394, 154153, 154701, 135497, 149847, 152570 }; --Rest In Pistons (BFA) }
{ "pile_set_name": "Github" }
"""The test for the data filter sensor platform.""" from datetime import timedelta from os import path import unittest from homeassistant import config as hass_config from homeassistant.components.filter.sensor import ( DOMAIN, LowPassFilter, OutlierFilter, RangeFilter, ThrottleFilter, TimeSMAFilter, TimeThrottleFilter, ) from homeassistant.const import SERVICE_RELOAD import homeassistant.core as ha from homeassistant.setup import async_setup_component, setup_component import homeassistant.util.dt as dt_util from tests.async_mock import patch from tests.common import ( assert_setup_component, get_test_home_assistant, init_recorder_component, ) class TestFilterSensor(unittest.TestCase): """Test the Data Filter sensor.""" def setup_method(self, method): """Set up things to be run when tests are started.""" self.hass = get_test_home_assistant() self.hass.config.components.add("history") raw_values = [20, 19, 18, 21, 22, 0] self.values = [] timestamp = dt_util.utcnow() for val in raw_values: self.values.append( ha.State("sensor.test_monitored", val, last_updated=timestamp) ) timestamp += timedelta(minutes=1) def teardown_method(self, method): """Stop everything that was started.""" self.hass.stop() def init_recorder(self): """Initialize the recorder.""" init_recorder_component(self.hass) self.hass.start() def test_setup_fail(self): """Test if filter doesn't exist.""" config = { "sensor": { "platform": "filter", "entity_id": "sensor.test_monitored", "filters": [{"filter": "nonexisting"}], } } with assert_setup_component(0): assert setup_component(self.hass, "sensor", config) self.hass.block_till_done() def test_chain(self): """Test if filter chaining works.""" config = { "sensor": { "platform": "filter", "name": "test", "entity_id": "sensor.test_monitored", "filters": [ {"filter": "outlier", "window_size": 10, "radius": 4.0}, {"filter": "lowpass", "time_constant": 10, "precision": 2}, {"filter": "throttle", "window_size": 1}, ], } } with assert_setup_component(1, "sensor"): assert setup_component(self.hass, "sensor", config) self.hass.block_till_done() for value in self.values: self.hass.states.set(config["sensor"]["entity_id"], value.state) self.hass.block_till_done() state = self.hass.states.get("sensor.test") assert "18.05" == state.state def test_chain_history(self, missing=False): """Test if filter chaining works.""" self.init_recorder() config = { "history": {}, "sensor": { "platform": "filter", "name": "test", "entity_id": "sensor.test_monitored", "filters": [ {"filter": "outlier", "window_size": 10, "radius": 4.0}, {"filter": "lowpass", "time_constant": 10, "precision": 2}, {"filter": "throttle", "window_size": 1}, ], }, } t_0 = dt_util.utcnow() - timedelta(minutes=1) t_1 = dt_util.utcnow() - timedelta(minutes=2) t_2 = dt_util.utcnow() - timedelta(minutes=3) t_3 = dt_util.utcnow() - timedelta(minutes=4) if missing: fake_states = {} else: fake_states = { "sensor.test_monitored": [ ha.State("sensor.test_monitored", 18.0, last_changed=t_0), ha.State("sensor.test_monitored", "unknown", last_changed=t_1), ha.State("sensor.test_monitored", 19.0, last_changed=t_2), ha.State("sensor.test_monitored", 18.2, last_changed=t_3), ] } with patch( "homeassistant.components.history.state_changes_during_period", return_value=fake_states, ): with patch( "homeassistant.components.history.get_last_state_changes", return_value=fake_states, ): with assert_setup_component(1, "sensor"): assert setup_component(self.hass, "sensor", config) self.hass.block_till_done() for value in self.values: self.hass.states.set(config["sensor"]["entity_id"], value.state) self.hass.block_till_done() state = self.hass.states.get("sensor.test") if missing: assert "18.05" == state.state else: assert "17.05" == state.state def test_chain_history_missing(self): """Test if filter chaining works when recorder is enabled but the source is not recorded.""" return self.test_chain_history(missing=True) def test_history_time(self): """Test loading from history based on a time window.""" self.init_recorder() config = { "history": {}, "sensor": { "platform": "filter", "name": "test", "entity_id": "sensor.test_monitored", "filters": [{"filter": "time_throttle", "window_size": "00:01"}], }, } t_0 = dt_util.utcnow() - timedelta(minutes=1) t_1 = dt_util.utcnow() - timedelta(minutes=2) t_2 = dt_util.utcnow() - timedelta(minutes=3) fake_states = { "sensor.test_monitored": [ ha.State("sensor.test_monitored", 18.0, last_changed=t_0), ha.State("sensor.test_monitored", 19.0, last_changed=t_1), ha.State("sensor.test_monitored", 18.2, last_changed=t_2), ] } with patch( "homeassistant.components.history.state_changes_during_period", return_value=fake_states, ): with patch( "homeassistant.components.history.get_last_state_changes", return_value=fake_states, ): with assert_setup_component(1, "sensor"): assert setup_component(self.hass, "sensor", config) self.hass.block_till_done() self.hass.block_till_done() state = self.hass.states.get("sensor.test") assert "18.0" == state.state def test_outlier(self): """Test if outlier filter works.""" filt = OutlierFilter(window_size=3, precision=2, entity=None, radius=4.0) for state in self.values: filtered = filt.filter_state(state) assert 21 == filtered.state def test_outlier_step(self): """ Test step-change handling in outlier. Test if outlier filter handles long-running step-changes correctly. It should converge to no longer filter once just over half the window_size is occupied by the new post step-change values. """ filt = OutlierFilter(window_size=3, precision=2, entity=None, radius=1.1) self.values[-1].state = 22 for state in self.values: filtered = filt.filter_state(state) assert 22 == filtered.state def test_initial_outlier(self): """Test issue #13363.""" filt = OutlierFilter(window_size=3, precision=2, entity=None, radius=4.0) out = ha.State("sensor.test_monitored", 4000) for state in [out] + self.values: filtered = filt.filter_state(state) assert 21 == filtered.state def test_unknown_state_outlier(self): """Test issue #32395.""" filt = OutlierFilter(window_size=3, precision=2, entity=None, radius=4.0) out = ha.State("sensor.test_monitored", "unknown") for state in [out] + self.values + [out]: try: filtered = filt.filter_state(state) except ValueError: assert state.state == "unknown" assert 21 == filtered.state def test_precision_zero(self): """Test if precision of zero returns an integer.""" filt = LowPassFilter(window_size=10, precision=0, entity=None, time_constant=10) for state in self.values: filtered = filt.filter_state(state) assert isinstance(filtered.state, int) def test_lowpass(self): """Test if lowpass filter works.""" filt = LowPassFilter(window_size=10, precision=2, entity=None, time_constant=10) out = ha.State("sensor.test_monitored", "unknown") for state in [out] + self.values + [out]: try: filtered = filt.filter_state(state) except ValueError: assert state.state == "unknown" assert 18.05 == filtered.state def test_range(self): """Test if range filter works.""" lower = 10 upper = 20 filt = RangeFilter( entity=None, precision=2, lower_bound=lower, upper_bound=upper ) for unf_state in self.values: unf = float(unf_state.state) filtered = filt.filter_state(unf_state) if unf < lower: assert lower == filtered.state elif unf > upper: assert upper == filtered.state else: assert unf == filtered.state def test_range_zero(self): """Test if range filter works with zeroes as bounds.""" lower = 0 upper = 0 filt = RangeFilter( entity=None, precision=2, lower_bound=lower, upper_bound=upper ) for unf_state in self.values: unf = float(unf_state.state) filtered = filt.filter_state(unf_state) if unf < lower: assert lower == filtered.state elif unf > upper: assert upper == filtered.state else: assert unf == filtered.state def test_throttle(self): """Test if lowpass filter works.""" filt = ThrottleFilter(window_size=3, precision=2, entity=None) filtered = [] for state in self.values: new_state = filt.filter_state(state) if not filt.skip_processing: filtered.append(new_state) assert [20, 21] == [f.state for f in filtered] def test_time_throttle(self): """Test if lowpass filter works.""" filt = TimeThrottleFilter( window_size=timedelta(minutes=2), precision=2, entity=None ) filtered = [] for state in self.values: new_state = filt.filter_state(state) if not filt.skip_processing: filtered.append(new_state) assert [20, 18, 22] == [f.state for f in filtered] def test_time_sma(self): """Test if time_sma filter works.""" filt = TimeSMAFilter( window_size=timedelta(minutes=2), precision=2, entity=None, type="last" ) for state in self.values: filtered = filt.filter_state(state) assert 21.5 == filtered.state async def test_reload(hass): """Verify we can reload filter sensors.""" await hass.async_add_executor_job( init_recorder_component, hass ) # force in memory db hass.states.async_set("sensor.test_monitored", 12345) await async_setup_component( hass, "sensor", { "sensor": { "platform": "filter", "name": "test", "entity_id": "sensor.test_monitored", "filters": [ {"filter": "outlier", "window_size": 10, "radius": 4.0}, {"filter": "lowpass", "time_constant": 10, "precision": 2}, {"filter": "throttle", "window_size": 1}, ], } }, ) await hass.async_block_till_done() await hass.async_start() await hass.async_block_till_done() assert len(hass.states.async_all()) == 2 assert hass.states.get("sensor.test") yaml_path = path.join( _get_fixtures_base_path(), "fixtures", "filter/configuration.yaml", ) with patch.object(hass_config, "YAML_CONFIG_FILE", yaml_path): await hass.services.async_call( DOMAIN, SERVICE_RELOAD, {}, blocking=True, ) await hass.async_block_till_done() assert len(hass.states.async_all()) == 2 assert hass.states.get("sensor.test") is None assert hass.states.get("sensor.filtered_realistic_humidity") def _get_fixtures_base_path(): return path.dirname(path.dirname(path.dirname(__file__)))
{ "pile_set_name": "Github" }
/* * _______ _ _ _____ ____ * |__ __| | | | |/ ____| _ \ * | | ___ ___ _ __ _ _| | | | (___ | |_) | * | |/ _ \/ _ \ '_ \| | | | | | |\___ \| _ < * | | __/ __/ | | | |_| | |__| |____) | |_) | * |_|\___|\___|_| |_|\__, |\____/|_____/|____/ * __/ | * |___/ * * TeenyUSB - light weight usb stack for STM32 micro controllers * * Copyright (c) 2019 XToolBox - [email protected] * www.tusb.org * * 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. */ #ifndef __TEENY_USB_HOST_H__ #define __TEENY_USB_HOST_H__ #include "teeny_usb.h" #endif
{ "pile_set_name": "Github" }
29 27 27 27 27 25 25 25 27 23 27 25 27 25 25 27 25 24 25 24 24 23 27 28 25 30 27 29 22 27 27 28 25 25 25 27 24 24 30 25 31 23 24 28 26 25 27 27 23 18 25 25 27 27 25 28 25 27 27 27 25 25 29 18 31 25 26 23 29 18 24 27 31 23 26 27 27 29 27 21 23 27 24 27 25 29 27 31 27 25 25 25 24 24 29 27 27 23 29 19 27 27 25 25 23 25 23 25 24 24 25 26 27 25 29 25 27 25 23 25 25 23 29 26 26 26 27 27 23 27 27 25 26 27 22 23 23 25 27 21 21 25 23 27 25 26 27 31 25 27 24 23 30 26 28 26 27 27 25 25 25 27 25 25 24 25 22 25 23 26 23 26 29 27 25 25 27 27 25 23 29 25 25 27 26 25 24 23 23 24 29 24 26 25 27 27 23 25 19 23 23 32 29 25 25 27 24 23 23 27 29 28 23 25 23 25 23 23 26 23 25 27 25 29 23 25 23 27 25 25 23 23 29 23 29 25 29 25 27 25 29 27 23 27 23 27 25 27 27 27 31 26 25 25 25 31 25 25 28 27 27 25 20 25 25 23 25 25 25 25 29 23 26 25 25 25 23 29 25 29 25 21 25 28 24 25 26 25
{ "pile_set_name": "Github" }
/** * Load all we.js features and start node.js console. * see: https://nodejs.org/api/repl.html */ module.exports = function consoleCommand(program) { const repl = require('repl'), helpers = require('../helpers'); let we; program .command('console') .alias('c') .description('Bootstrap we.js and start node.js console. see: https://nodejs.org/api/repl.html') .option('-S, --server', 'Start server on run') .action(function run(opts) { we = helpers.getWe(); we.utils.async.series([ function (done) { we.bootstrap( done ); }, function (done) { if (!opts.server) return done(); we.startServer(done); } ], (err)=> { if (err) { return doneAll(err); } console.log('Starting we.js console, We.js object is avaible as we variable\n'); const r = repl.start({ prompt: 'We.js ;> ', input: process.stdin, output: process.stdout }); // set we object r.context.we = we; // one exit ... r.on('exit', ()=> { console.log('Exit from we.js console.'); doneAll(); }); }); function doneAll(err) { if ( err ) { we.log.error('Error in we.js CLI:', err); } we.exit( ()=> { // end / exit process.exit(); }); } }); };
{ "pile_set_name": "Github" }
<mods xmlns="http://www.loc.gov/mods/v3" xmlns:exslt="http://exslt.org/common" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xlink="http://www.w3.org/1999/xlink" xsi:schemaLocation="http://www.loc.gov/mods/v3 http://www.loc.gov/standards/mods/v3/mods-3-3.xsd" version="3.3" ID="P0b002ee1818f170d"> <name type="corporate"> <namePart>United States Government Printing Office</namePart> <role> <roleTerm type="text" authority="marcrelator">printer</roleTerm> <roleTerm type="code" authority="marcrelator">prt</roleTerm> </role> <role> <roleTerm type="text" authority="marcrelator">distributor</roleTerm> <roleTerm type="code" authority="marcrelator">dst</roleTerm> </role> </name> <name type="corporate"> <namePart>United States</namePart> <namePart>United States District Court Eastern District of Michigan</namePart> <role> <roleTerm type="text" authority="marcrelator">author</roleTerm> <roleTerm type="code" authority="marcrelator">aut</roleTerm> </role> <description>Government Organization</description> </name> <typeOfResource>text</typeOfResource> <genre authority="marcgt">government publication</genre> <language> <languageTerm authority="iso639-2b" type="code">eng</languageTerm> </language> <extension> <collectionCode>USCOURTS</collectionCode> <category>Judicial Publications</category> <branch>judicial</branch> <dateIngested>2012-01-17</dateIngested> </extension> <originInfo> <publisher>Administrative Office of the United States Courts</publisher> <dateIssued encoding="w3cdtf">2008-01-23</dateIssued> <issuance>monographic</issuance> </originInfo> <physicalDescription> <note type="source content type">deposited</note> <digitalOrigin>born digital</digitalOrigin> </physicalDescription> <classification authority="sudocs">JU 4.15</classification> <identifier type="uri">http://www.gpo.gov/fdsys/pkg/USCOURTS-mied-2_07-mc-51010</identifier> <identifier type="local">P0b002ee1818f170d</identifier> <recordInfo> <recordContentSource authority="marcorg">DGPO</recordContentSource> <recordCreationDate encoding="w3cdtf">2012-01-17</recordCreationDate> <recordChangeDate encoding="w3cdtf">2012-01-18</recordChangeDate> <recordIdentifier source="DGPO">USCOURTS-mied-2_07-mc-51010</recordIdentifier> <recordOrigin>machine generated</recordOrigin> <languageOfCataloging> <languageTerm authority="iso639-2b" type="code">eng</languageTerm> </languageOfCataloging> </recordInfo> <accessCondition type="GPO scope determination">fdlp</accessCondition> <extension> <docClass>USCOURTS</docClass> <accessId>USCOURTS-mied-2_07-mc-51010</accessId> <courtType>District</courtType> <courtCode>mied</courtCode> <courtCircuit>6th</courtCircuit> <courtState>Michigan</courtState> <courtSortOrder>2251</courtSortOrder> <caseNumber>2:07-mc-51010</caseNumber> <caseOffice>Detroit</caseOffice> <caseType></caseType> <natureSuitCode>890</natureSuitCode> <natureSuit>Other Statutory Actions</natureSuit> <party firstName="Amir" fullName="Amir Denha" lastName="Denha" role="Respondent"></party> <party fullName="United States of America" lastName="United States of America" role="Petitioner"></party> </extension> <titleInfo> <title>United States of America v. Denha</title> <partNumber>2:07-mc-51010</partNumber> </titleInfo> <location> <url access="object in context" displayLabel="Content Detail">http://www.gpo.gov/fdsys/pkg/USCOURTS-mied-2_07-mc-51010/content-detail.html</url> </location> <classification authority="sudocs">JU 4.15</classification> <identifier type="preferred citation">2:07-mc-51010;07-51010</identifier> <name type="corporate"> <namePart>United States District Court Eastern District of Michigan</namePart> <namePart>6th Circuit</namePart> <namePart>Detroit</namePart> <affiliation>U.S. Courts</affiliation> <role> <roleTerm authority="marcrelator" type="text">author</roleTerm> <roleTerm authority="marcrelator" type="code">aut</roleTerm> </role> </name> <name type="personal"> <displayForm>Amir Denha</displayForm> <namePart type="family">Denha</namePart> <namePart type="given">Amir</namePart> <namePart type="termsOfAddress"></namePart> <description>Respondent</description> </name> <name type="personal"> <displayForm>United States of America</displayForm> <namePart type="family">United States of America</namePart> <namePart type="given"></namePart> <namePart type="termsOfAddress"></namePart> <description>Petitioner</description> </name> <extension> <docClass>USCOURTS</docClass> <accessId>USCOURTS-mied-2_07-mc-51010</accessId> <courtType>District</courtType> <courtCode>mied</courtCode> <courtCircuit>6th</courtCircuit> <courtState>Michigan</courtState> <courtSortOrder>2251</courtSortOrder> <caseNumber>2:07-mc-51010</caseNumber> <caseOffice>Detroit</caseOffice> <caseType></caseType> <natureSuitCode>890</natureSuitCode> <natureSuit>Other Statutory Actions</natureSuit> <party firstName="Amir" fullName="Amir Denha" lastName="Denha" role="Respondent"></party> <party fullName="United States of America" lastName="United States of America" role="Petitioner"></party> <state>Michigan</state> </extension> <relatedItem type="constituent" ID="id-USCOURTS-mied-2_07-mc-51010-0" xlink:href="http://www.gpo.gov/fdsys/granule/USCOURTS-mied-2_07-mc-51010/USCOURTS-mied-2_07-mc-51010-0/mods.xml"> <titleInfo> <title>United States of America v. Denha</title> <subTitle>ORDER DISMISSING re 1 Petition to Enforce IRS Summons filed by United States of America. Signed by Honorable Paul D Borman. (DGoo)</subTitle> <partNumber>0</partNumber> </titleInfo> <originInfo> <dateIssued>2008-01-23</dateIssued> </originInfo> <relatedItem xlink:href="http://www.gpo.gov/fdsys/pkg/pdf/USCOURTS-mied-2_07-mc-51010-0.pdf" type="otherFormat"> <identifier type="FDsys Unique ID">D09002ee181936b87</identifier> </relatedItem> <identifier type="uri">http://www.gpo.gov/fdsys/granule/USCOURTS-mied-2_07-mc-51010/USCOURTS-mied-2_07-mc-51010-0</identifier> <identifier type="former granule identifier">mied-2_07-mc-51010_0.pdf</identifier> <location> <url access="object in context" displayLabel="Content Detail">http://www.gpo.gov/fdsys/granule/USCOURTS-mied-2_07-mc-51010/USCOURTS-mied-2_07-mc-51010-0/content-detail.html</url> <url access="raw object" displayLabel="PDF rendition">http://www.gpo.gov/fdsys/pkg/USCOURTS-mied-2_07-mc-51010/pdf/USCOURTS-mied-2_07-mc-51010-0.pdf</url> </location> <extension> <searchTitle>USCOURTS 2:07-mc-51010; United States of America v. Denha; </searchTitle> <courtName>United States District Court Eastern District of Michigan</courtName> <state>Michigan</state> <accessId>USCOURTS-mied-2_07-mc-51010-0</accessId> <sequenceNumber>0</sequenceNumber> <dateIssued>2008-01-23</dateIssued> <docketText>ORDER DISMISSING re 1 Petition to Enforce IRS Summons filed by United States of America. Signed by Honorable Paul D Borman. (DGoo)</docketText> </extension> </relatedItem> </mods>
{ "pile_set_name": "Github" }
/* * Copyright 2020 ConsenSys AG. * * 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 tech.pegasys.teku.storage.server.rocksdb.core; import io.prometheus.client.Collector; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.function.Supplier; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.hyperledger.besu.metrics.prometheus.PrometheusMetricsSystem; import org.hyperledger.besu.plugin.services.MetricsSystem; import org.hyperledger.besu.plugin.services.metrics.MetricCategory; import org.rocksdb.HistogramData; import org.rocksdb.HistogramType; import org.rocksdb.RocksDB; import org.rocksdb.RocksDBException; import org.rocksdb.Statistics; import org.rocksdb.TickerType; /** * Taken from * https://github.com/hyperledger/besu/blob/3d867532deb893fd267fcd5d4e6bf0d42a76e59b/metrics/rocksdb/src/main/java/org/hyperledger/besu/metrics/rocksdb/RocksDBStats.java#L137 */ public class RocksDbStats implements AutoCloseable { private static final Logger LOG = LogManager.getLogger(); static final List<String> LABELS = Collections.singletonList("quantile"); static final List<String> LABEL_50 = Collections.singletonList("0.5"); static final List<String> LABEL_95 = Collections.singletonList("0.95"); static final List<String> LABEL_99 = Collections.singletonList("0.99"); // Tickers - RocksDB equivalent of counters static final TickerType[] TICKERS = { TickerType.BLOCK_CACHE_ADD, TickerType.BLOCK_CACHE_HIT, TickerType.BLOCK_CACHE_ADD_FAILURES, TickerType.BLOCK_CACHE_INDEX_MISS, TickerType.BLOCK_CACHE_INDEX_HIT, TickerType.BLOCK_CACHE_INDEX_ADD, TickerType.BLOCK_CACHE_INDEX_BYTES_INSERT, TickerType.BLOCK_CACHE_INDEX_BYTES_EVICT, TickerType.BLOCK_CACHE_FILTER_MISS, TickerType.BLOCK_CACHE_FILTER_HIT, TickerType.BLOCK_CACHE_FILTER_ADD, TickerType.BLOCK_CACHE_FILTER_BYTES_INSERT, TickerType.BLOCK_CACHE_FILTER_BYTES_EVICT, TickerType.BLOCK_CACHE_DATA_MISS, TickerType.BLOCK_CACHE_DATA_HIT, TickerType.BLOCK_CACHE_DATA_ADD, TickerType.BLOCK_CACHE_DATA_BYTES_INSERT, TickerType.BLOCK_CACHE_BYTES_READ, TickerType.BLOCK_CACHE_BYTES_WRITE, TickerType.BLOOM_FILTER_USEFUL, TickerType.PERSISTENT_CACHE_HIT, TickerType.PERSISTENT_CACHE_MISS, TickerType.SIM_BLOCK_CACHE_HIT, TickerType.SIM_BLOCK_CACHE_MISS, TickerType.MEMTABLE_HIT, TickerType.MEMTABLE_MISS, TickerType.GET_HIT_L0, TickerType.GET_HIT_L1, TickerType.GET_HIT_L2_AND_UP, TickerType.COMPACTION_KEY_DROP_NEWER_ENTRY, TickerType.COMPACTION_KEY_DROP_OBSOLETE, TickerType.COMPACTION_KEY_DROP_RANGE_DEL, TickerType.COMPACTION_KEY_DROP_USER, TickerType.COMPACTION_RANGE_DEL_DROP_OBSOLETE, TickerType.NUMBER_KEYS_WRITTEN, TickerType.NUMBER_KEYS_READ, TickerType.NUMBER_KEYS_UPDATED, TickerType.BYTES_WRITTEN, TickerType.BYTES_READ, TickerType.NUMBER_DB_SEEK, TickerType.NUMBER_DB_NEXT, TickerType.NUMBER_DB_PREV, TickerType.NUMBER_DB_SEEK_FOUND, TickerType.NUMBER_DB_NEXT_FOUND, TickerType.NUMBER_DB_PREV_FOUND, TickerType.ITER_BYTES_READ, TickerType.NO_FILE_CLOSES, TickerType.NO_FILE_OPENS, TickerType.NO_FILE_ERRORS, // TickerType.STALL_L0_SLOWDOWN_MICROS, // TickerType.STALL_MEMTABLE_COMPACTION_MICROS, // TickerType.STALL_L0_NUM_FILES_MICROS, TickerType.STALL_MICROS, TickerType.DB_MUTEX_WAIT_MICROS, TickerType.RATE_LIMIT_DELAY_MILLIS, TickerType.NO_ITERATORS, TickerType.NUMBER_MULTIGET_BYTES_READ, TickerType.NUMBER_MULTIGET_KEYS_READ, TickerType.NUMBER_MULTIGET_CALLS, TickerType.NUMBER_FILTERED_DELETES, TickerType.NUMBER_MERGE_FAILURES, TickerType.BLOOM_FILTER_PREFIX_CHECKED, TickerType.BLOOM_FILTER_PREFIX_USEFUL, TickerType.NUMBER_OF_RESEEKS_IN_ITERATION, TickerType.GET_UPDATES_SINCE_CALLS, TickerType.BLOCK_CACHE_COMPRESSED_MISS, TickerType.BLOCK_CACHE_COMPRESSED_HIT, TickerType.BLOCK_CACHE_COMPRESSED_ADD, TickerType.BLOCK_CACHE_COMPRESSED_ADD_FAILURES, TickerType.WAL_FILE_SYNCED, TickerType.WAL_FILE_BYTES, TickerType.WRITE_DONE_BY_SELF, TickerType.WRITE_DONE_BY_OTHER, TickerType.WRITE_TIMEDOUT, TickerType.WRITE_WITH_WAL, TickerType.COMPACT_READ_BYTES, TickerType.COMPACT_WRITE_BYTES, TickerType.FLUSH_WRITE_BYTES, TickerType.NUMBER_DIRECT_LOAD_TABLE_PROPERTIES, TickerType.NUMBER_SUPERVERSION_ACQUIRES, TickerType.NUMBER_SUPERVERSION_RELEASES, TickerType.NUMBER_SUPERVERSION_CLEANUPS, TickerType.NUMBER_BLOCK_COMPRESSED, TickerType.NUMBER_BLOCK_DECOMPRESSED, TickerType.NUMBER_BLOCK_NOT_COMPRESSED, TickerType.MERGE_OPERATION_TOTAL_TIME, TickerType.FILTER_OPERATION_TOTAL_TIME, TickerType.ROW_CACHE_HIT, TickerType.ROW_CACHE_MISS, TickerType.READ_AMP_ESTIMATE_USEFUL_BYTES, TickerType.READ_AMP_TOTAL_READ_BYTES, TickerType.NUMBER_RATE_LIMITER_DRAINS, TickerType.NUMBER_ITER_SKIP, TickerType.NUMBER_MULTIGET_KEYS_FOUND, }; // Histograms - treated as prometheus summaries static final HistogramType[] HISTOGRAMS = { HistogramType.DB_GET, HistogramType.DB_WRITE, HistogramType.COMPACTION_TIME, HistogramType.SUBCOMPACTION_SETUP_TIME, HistogramType.TABLE_SYNC_MICROS, HistogramType.COMPACTION_OUTFILE_SYNC_MICROS, HistogramType.WAL_FILE_SYNC_MICROS, HistogramType.MANIFEST_FILE_SYNC_MICROS, HistogramType.TABLE_OPEN_IO_MICROS, HistogramType.DB_MULTIGET, HistogramType.READ_BLOCK_COMPACTION_MICROS, HistogramType.READ_BLOCK_GET_MICROS, HistogramType.WRITE_RAW_BLOCK_MICROS, HistogramType.STALL_L0_SLOWDOWN_COUNT, HistogramType.STALL_MEMTABLE_COMPACTION_COUNT, HistogramType.STALL_L0_NUM_FILES_COUNT, HistogramType.HARD_RATE_LIMIT_DELAY_COUNT, HistogramType.SOFT_RATE_LIMIT_DELAY_COUNT, HistogramType.NUM_FILES_IN_SINGLE_COMPACTION, HistogramType.DB_SEEK, HistogramType.WRITE_STALL, HistogramType.SST_READ_MICROS, HistogramType.NUM_SUBCOMPACTIONS_SCHEDULED, HistogramType.BYTES_PER_READ, HistogramType.BYTES_PER_WRITE, HistogramType.BYTES_PER_MULTIGET, HistogramType.BYTES_COMPRESSED, HistogramType.BYTES_DECOMPRESSED, HistogramType.COMPRESSION_TIMES_NANOS, HistogramType.DECOMPRESSION_TIMES_NANOS, HistogramType.READ_NUM_MERGE_OPERANDS, }; private boolean closed = false; private final Statistics stats; private final MetricsSystem metricsSystem; private final MetricCategory category; public RocksDbStats(final MetricsSystem metricsSystem, final MetricCategory category) { this.stats = new Statistics(); this.metricsSystem = metricsSystem; this.category = category; } public Statistics getStats() { return stats; } public void registerMetrics(final RocksDB database) { metricsSystem.createLongGauge( category, "estimated_table_readers_memory", "Estimated memory used by index and filter blocks", () -> getLongProperty(database, "rocksdb.estimate-table-readers-mem")); metricsSystem.createLongGauge( category, "current_size_all_mem_tables", "Current size of all RocksDB mem tables combined", () -> getLongProperty(database, "rocksdb.cur-size-all-mem-tables")); for (final TickerType ticker : TICKERS) { final String promCounterName = ticker.name().toLowerCase(); metricsSystem.createLongGauge( category, promCounterName, "RocksDB reported statistics for " + ticker.name(), () -> ifOpen(() -> stats.getTickerCount(ticker), 0L)); } if (metricsSystem instanceof PrometheusMetricsSystem) { for (final HistogramType histogram : HISTOGRAMS) { ((PrometheusMetricsSystem) metricsSystem) .addCollector(category, histogramToCollector(category, stats, histogram)); } } } private long getLongProperty(final RocksDB database, final String name) { return ifOpen( () -> { try { return database.getLongProperty(name); } catch (RocksDBException e) { LOG.warn("Failed to load " + name + " property for RocksDB metrics"); return 0L; } }, 0L); } private Collector histogramToCollector( final MetricCategory metricCategory, final Statistics stats, final HistogramType histogram) { return new Collector() { final String metricName = metricCategory.getApplicationPrefix().orElse("") + metricCategory.getName() + "_" + histogram.name().toLowerCase(); @Override public List<MetricFamilySamples> collect() { return ifOpen( () -> { final HistogramData data = stats.getHistogramData(histogram); return Collections.singletonList( new MetricFamilySamples( metricName, Type.SUMMARY, "RocksDB histogram for " + metricName, Arrays.asList( new MetricFamilySamples.Sample( metricName, LABELS, LABEL_50, data.getMedian()), new MetricFamilySamples.Sample( metricName, LABELS, LABEL_95, data.getPercentile95()), new MetricFamilySamples.Sample( metricName, LABELS, LABEL_99, data.getPercentile99())))); }, Collections.emptyList()); } }; } @Override public synchronized void close() { if (closed) { return; } closed = true; stats.close(); } private synchronized <T> T ifOpen(final Supplier<T> supplier, final T defaultValue) { if (closed) { return defaultValue; } return supplier.get(); } }
{ "pile_set_name": "Github" }
using BenchmarkDotNet.Configs; using System; namespace BenchmarkDotNet.Diagnostics.Windows.Configs { [AttributeUsage(AttributeTargets.Class)] public class TailCallDiagnoserAttribute : Attribute, IConfigSource { public IConfig Config { get; } /// <param name="logFailuresOnly">only the methods that failed to get tail called. True by default.</param> /// <param name="filterByNamespace">only the methods from declaring type's namespace. Set to false if you want to see all Jit tail events. True by default.</param> public TailCallDiagnoserAttribute(bool logFailuresOnly = true, bool filterByNamespace = true) { Config = ManualConfig.CreateEmpty().AddDiagnoser(new TailCallDiagnoser(logFailuresOnly, filterByNamespace)); } } }
{ "pile_set_name": "Github" }
/* Copyright (C) 1996-1997 Id Software, Inc. 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // vid_null.c -- null video driver to aid porting efforts #include "quakedef.h" #include "d_local.h" viddef_t vid; // global video state #define BASEWIDTH 320 #define BASEHEIGHT 200 byte vid_buffer[BASEWIDTH*BASEHEIGHT]; short zbuffer[BASEWIDTH*BASEHEIGHT]; byte surfcache[256*1024]; unsigned short d_8to16table[256]; unsigned d_8to24table[256]; void VID_SetPalette (unsigned char *palette) { } void VID_ShiftPalette (unsigned char *palette) { } void VID_Init (unsigned char *palette) { vid.maxwarpwidth = vid.width = vid.conwidth = BASEWIDTH; vid.maxwarpheight = vid.height = vid.conheight = BASEHEIGHT; vid.aspect = 1.0; vid.numpages = 1; vid.colormap = host_colormap; vid.fullbright = 256 - LittleLong (*((int *)vid.colormap + 2048)); vid.buffer = vid.conbuffer = vid_buffer; vid.rowbytes = vid.conrowbytes = BASEWIDTH; d_pzbuffer = zbuffer; D_InitCaches (surfcache, sizeof(surfcache)); } void VID_Shutdown (void) { } void VID_Update (vrect_t *rects) { } /* ================ D_BeginDirectRect ================ */ void D_BeginDirectRect (int x, int y, byte *pbitmap, int width, int height) { } /* ================ D_EndDirectRect ================ */ void D_EndDirectRect (int x, int y, int width, int height) { }
{ "pile_set_name": "Github" }
<?xml version="1.0"?> <xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2"> <file source-language="en" datatype="plaintext" original="file.ext"> <body> <trans-unit id="1"> <source>An authentication exception occurred.</source> <target>Uma exceção ocorreu durante a autenticação.</target> </trans-unit> <trans-unit id="2"> <source>Authentication credentials could not be found.</source> <target>As credenciais de autenticação não foram encontradas.</target> </trans-unit> <trans-unit id="3"> <source>Authentication request could not be processed due to a system problem.</source> <target>A autenticação não pôde ser concluída devido a um problema no sistema.</target> </trans-unit> <trans-unit id="4"> <source>Invalid credentials.</source> <target>Credenciais inválidas.</target> </trans-unit> <trans-unit id="5"> <source>Cookie has already been used by someone else.</source> <target>Este cookie já esta em uso.</target> </trans-unit> <trans-unit id="6"> <source>Not privileged to request the resource.</source> <target>Não possui privilégios o bastante para requisitar este recurso.</target> </trans-unit> <trans-unit id="7"> <source>Invalid CSRF token.</source> <target>Token CSRF inválido.</target> </trans-unit> <trans-unit id="8"> <source>Digest nonce has expired.</source> <target>Digest nonce expirado.</target> </trans-unit> <trans-unit id="9"> <source>No authentication provider found to support the authentication token.</source> <target>Nenhum provedor de autenticação encontrado para suportar o token de autenticação.</target> </trans-unit> <trans-unit id="10"> <source>No session available, it either timed out or cookies are not enabled.</source> <target>Nenhuma sessão disponível, ela expirou ou cookies estão desativados.</target> </trans-unit> <trans-unit id="11"> <source>No token could be found.</source> <target>Nenhum token foi encontrado.</target> </trans-unit> <trans-unit id="12"> <source>Username could not be found.</source> <target>Nome de usuário não encontrado.</target> </trans-unit> <trans-unit id="13"> <source>Account has expired.</source> <target>A conta esta expirada.</target> </trans-unit> <trans-unit id="14"> <source>Credentials have expired.</source> <target>As credenciais estão expiradas.</target> </trans-unit> <trans-unit id="15"> <source>Account is disabled.</source> <target>Conta desativada.</target> </trans-unit> <trans-unit id="16"> <source>Account is locked.</source> <target>A conta esta travada.</target> </trans-unit> </body> </file> </xliff>
{ "pile_set_name": "Github" }
#!/usr/bin/python # Copyright (C) Vladimir Prus 2005. # Distributed under the Boost Software License, Version 1.0. (See # accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) import BoostBuild t = BoostBuild.Tester(use_test_config=False) t.write("jamroot.jam", "using some_tool ;") t.write("some_tool.jam", """\ import project ; project.initialize $(__name__) ; rule init ( ) { } """) t.write("some_tool.py", """\ from b2.manager import get_manager get_manager().projects().initialize(__name__) def init(): pass """) t.write("sub/a.cpp", "int main() {}\n") t.write("sub/jamfile.jam", "exe a : a.cpp ;") t.run_build_system(subdir="sub") t.expect_addition("sub/bin/$toolset/debug/a.exe") t.cleanup()
{ "pile_set_name": "Github" }
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the Qt3D module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:GPL-EXCEPT$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 as published by the Free Software ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtTest/QTest> #include <qbackendnodetester.h> #include <Qt3DRender/qgeometryrenderer.h> #include <Qt3DCore/qbuffer.h> #include <private/trianglesvisitor_p.h> #include <private/nodemanagers_p.h> #include <private/managers_p.h> #include <private/geometryrenderer_p.h> #include <private/geometryrenderermanager_p.h> #include <private/buffermanager_p.h> #include "testrenderer.h" using namespace Qt3DRender::Render; class TestVisitor : public TrianglesVisitor { public: TestVisitor(NodeManagers *manager) : TrianglesVisitor(manager) { } void visit(uint andx, const Vector3D &a, uint bndx, const Vector3D &b, uint cndx, const Vector3D &c) override { m_triangles.push_back(TestTriangle(andx, a, bndx, b, cndx, c)); } NodeManagers *nodeManagers() const { return m_manager; } Qt3DCore::QNodeId nodeId() const { return m_nodeId; } uint triangleCount() const { return m_triangles.size(); } bool verifyTriangle(uint triangle, uint andx, uint bndx, uint cndx, Vector3D a, Vector3D b, Vector3D c) const { if (triangle >= uint(m_triangles.size())) return false; if (andx != m_triangles[triangle].abcndx[0] || bndx != m_triangles[triangle].abcndx[1] || cndx != m_triangles[triangle].abcndx[2]) return false; if (!qFuzzyCompare(a, m_triangles[triangle].abc[0]) || !qFuzzyCompare(b, m_triangles[triangle].abc[1]) || !qFuzzyCompare(c, m_triangles[triangle].abc[2])) return false; return true; } private: struct TestTriangle { uint abcndx[3]; Vector3D abc[3]; TestTriangle() { abcndx[0] = abcndx[1] = abcndx[2] = uint(-1); } TestTriangle(uint andx, const Vector3D &a, uint bndx, const Vector3D &b, uint cndx, const Vector3D &c) { abcndx[0] = andx; abcndx[1] = bndx; abcndx[2] = cndx; abc[0] = a; abc[1] = b; abc[2] = c; } }; QList<TestTriangle> m_triangles; }; class tst_TriangleVisitor : public Qt3DCore::QBackendNodeTester { Q_OBJECT private Q_SLOTS: void checkInitialize() { // WHEN QScopedPointer<NodeManagers> nodeManagers(new NodeManagers()); TestVisitor visitor(nodeManagers.data()); // THEN QCOMPARE(visitor.nodeManagers(), nodeManagers.data()); } void checkApplyEntity() { QScopedPointer<NodeManagers> nodeManagers(new NodeManagers()); QScopedPointer<Qt3DCore::QEntity> entity(new Qt3DCore::QEntity()); TestVisitor visitor(nodeManagers.data()); // WHEN visitor.apply(entity.data()); // THEN QCOMPARE(visitor.nodeId(), entity->id()); QVERIFY(visitor.triangleCount() == 0); } void checkApplyGeometryRenderer() { QScopedPointer<NodeManagers> nodeManagers(new NodeManagers()); QScopedPointer<GeometryRenderer> geometryRenderer(new GeometryRenderer()); TestVisitor visitor(nodeManagers.data()); // WHEN visitor.apply(geometryRenderer.data(), Qt3DCore::QNodeId()); // THEN // tadaa, nothing should happen } void testVisitTriangles() { QScopedPointer<NodeManagers> nodeManagers(new NodeManagers()); Qt3DCore::QGeometry *geometry = new Qt3DCore::QGeometry(); QScopedPointer<Qt3DRender::QGeometryRenderer> geometryRenderer(new Qt3DRender::QGeometryRenderer()); QScopedPointer<Qt3DCore::QAttribute> positionAttribute(new Qt3DCore::QAttribute()); QScopedPointer<Qt3DCore::QBuffer> dataBuffer(new Qt3DCore::QBuffer()); TestVisitor visitor(nodeManagers.data()); TestRenderer renderer; QByteArray data; data.resize(sizeof(float) * 3 * 3 * 2); float *dataPtr = reinterpret_cast<float *>(data.data()); dataPtr[0] = 0; dataPtr[1] = 0; dataPtr[2] = 1.0f; dataPtr[3] = 1.0f; dataPtr[4] = 0; dataPtr[5] = 0; dataPtr[6] = 0; dataPtr[7] = 1.0f; dataPtr[8] = 0; dataPtr[9] = 0; dataPtr[10] = 0; dataPtr[11] = 1.0f; dataPtr[12] = 1.0f; dataPtr[13] = 0; dataPtr[14] = 0; dataPtr[15] = 0; dataPtr[16] = 1.0f; dataPtr[17] = 0; dataBuffer->setData(data); Buffer *backendBuffer = nodeManagers->bufferManager()->getOrCreateResource(dataBuffer->id()); backendBuffer->setRenderer(&renderer); backendBuffer->setManager(nodeManagers->bufferManager()); simulateInitializationSync(dataBuffer.data(), backendBuffer); positionAttribute->setBuffer(dataBuffer.data()); positionAttribute->setName(Qt3DCore::QAttribute::defaultPositionAttributeName()); positionAttribute->setVertexBaseType(Qt3DCore::QAttribute::Float); positionAttribute->setVertexSize(3); positionAttribute->setCount(6); positionAttribute->setByteStride(0); positionAttribute->setByteOffset(0); positionAttribute->setAttributeType(Qt3DCore::QAttribute::VertexAttribute); geometry->addAttribute(positionAttribute.data()); geometryRenderer->setGeometry(geometry); geometryRenderer->setPrimitiveType(Qt3DRender::QGeometryRenderer::Triangles); Attribute *backendAttribute = nodeManagers->attributeManager()->getOrCreateResource(positionAttribute->id()); backendAttribute->setRenderer(&renderer); simulateInitializationSync(positionAttribute.data(), backendAttribute); Geometry *backendGeometry = nodeManagers->geometryManager()->getOrCreateResource(geometry->id()); backendGeometry->setRenderer(&renderer); simulateInitializationSync(geometry, backendGeometry); GeometryRenderer *backendRenderer = nodeManagers->geometryRendererManager()->getOrCreateResource(geometryRenderer->id()); backendRenderer->setRenderer(&renderer); backendRenderer->setManager(nodeManagers->geometryRendererManager()); simulateInitializationSync(geometryRenderer.data(), backendRenderer); // WHEN visitor.apply(backendRenderer, Qt3DCore::QNodeId()); // THEN QVERIFY(visitor.triangleCount() == 2); QVERIFY(visitor.verifyTriangle(0, 2,1,0, Vector3D(0,1,0), Vector3D(1,0,0), Vector3D(0,0,1))); QVERIFY(visitor.verifyTriangle(1, 5,4,3, Vector3D(0,1,0), Vector3D(1,0,0), Vector3D(0,0,1))); } void testVisitTrianglesIndexed() { QScopedPointer<NodeManagers> nodeManagers(new NodeManagers()); Qt3DCore::QGeometry *geometry = new Qt3DCore::QGeometry(); QScopedPointer<Qt3DRender::QGeometryRenderer> geometryRenderer(new Qt3DRender::QGeometryRenderer()); QScopedPointer<Qt3DCore::QAttribute> positionAttribute(new Qt3DCore::QAttribute()); QScopedPointer<Qt3DCore::QAttribute> indexAttribute(new Qt3DCore::QAttribute()); QScopedPointer<Qt3DCore::QBuffer> dataBuffer(new Qt3DCore::QBuffer()); QScopedPointer<Qt3DCore::QBuffer> indexDataBuffer(new Qt3DCore::QBuffer()); TestVisitor visitor(nodeManagers.data()); TestRenderer renderer; QByteArray data; data.resize(sizeof(float) * 3 * 3 * 2); float *dataPtr = reinterpret_cast<float *>(data.data()); dataPtr[0] = 0; dataPtr[1] = 0; dataPtr[2] = 1.0f; dataPtr[3] = 1.0f; dataPtr[4] = 0; dataPtr[5] = 0; dataPtr[6] = 0; dataPtr[7] = 1.0f; dataPtr[8] = 0; dataPtr[9] = 0; dataPtr[10] = 0; dataPtr[11] = 1.0f; dataPtr[12] = 1.0f; dataPtr[13] = 0; dataPtr[14] = 0; dataPtr[15] = 0; dataPtr[16] = 1.0f; dataPtr[17] = 0; dataBuffer->setData(data); Buffer *backendBuffer = nodeManagers->bufferManager()->getOrCreateResource(dataBuffer->id()); backendBuffer->setRenderer(&renderer); backendBuffer->setManager(nodeManagers->bufferManager()); simulateInitializationSync(dataBuffer.data(), backendBuffer); QByteArray indexData; indexData.resize(sizeof(uint) * 3 * 5); uint *iDataPtr = reinterpret_cast<uint *>(indexData.data()); iDataPtr[0] = 0; iDataPtr[1] = 1; iDataPtr[2] = 2; iDataPtr[3] = 3; iDataPtr[4] = 4; iDataPtr[5] = 5; iDataPtr[6] = 5; iDataPtr[7] = 1; iDataPtr[8] = 0; iDataPtr[9] = 4; iDataPtr[10] = 3; iDataPtr[11] = 2; iDataPtr[12] = 0; iDataPtr[13] = 2; iDataPtr[14] = 4; indexDataBuffer->setData(indexData); Buffer *backendIndexBuffer = nodeManagers->bufferManager()->getOrCreateResource(indexDataBuffer->id()); backendIndexBuffer->setRenderer(&renderer); backendIndexBuffer->setManager(nodeManagers->bufferManager()); simulateInitializationSync(indexDataBuffer.data(), backendIndexBuffer); positionAttribute->setBuffer(dataBuffer.data()); positionAttribute->setName(Qt3DCore::QAttribute::defaultPositionAttributeName()); positionAttribute->setVertexBaseType(Qt3DCore::QAttribute::Float); positionAttribute->setVertexSize(3); positionAttribute->setCount(6); positionAttribute->setByteStride(3*sizeof(float)); positionAttribute->setByteOffset(0); positionAttribute->setAttributeType(Qt3DCore::QAttribute::VertexAttribute); indexAttribute->setBuffer(indexDataBuffer.data()); indexAttribute->setVertexBaseType(Qt3DCore::QAttribute::UnsignedInt); indexAttribute->setCount(3*5); indexAttribute->setAttributeType(Qt3DCore::QAttribute::IndexAttribute); geometry->addAttribute(positionAttribute.data()); geometry->addAttribute(indexAttribute.data()); geometryRenderer->setGeometry(geometry); geometryRenderer->setPrimitiveType(Qt3DRender::QGeometryRenderer::Triangles); Attribute *backendAttribute = nodeManagers->attributeManager()->getOrCreateResource(positionAttribute->id()); backendAttribute->setRenderer(&renderer); simulateInitializationSync(positionAttribute.data(), backendAttribute); Attribute *backendIndexAttribute = nodeManagers->attributeManager()->getOrCreateResource(indexAttribute->id()); backendIndexAttribute->setRenderer(&renderer); simulateInitializationSync(indexAttribute.data(), backendIndexAttribute); Geometry *backendGeometry = nodeManagers->geometryManager()->getOrCreateResource(geometry->id()); backendGeometry->setRenderer(&renderer); simulateInitializationSync(geometry, backendGeometry); GeometryRenderer *backendRenderer = nodeManagers->geometryRendererManager()->getOrCreateResource(geometryRenderer->id()); backendRenderer->setRenderer(&renderer); backendRenderer->setManager(nodeManagers->geometryRendererManager()); simulateInitializationSync(geometryRenderer.data(), backendRenderer); // WHEN visitor.apply(backendRenderer, Qt3DCore::QNodeId()); // THEN QVERIFY(visitor.triangleCount() == 5); QVERIFY(visitor.verifyTriangle(0, 2,1,0, Vector3D(0,1,0), Vector3D(1,0,0), Vector3D(0,0,1))); QVERIFY(visitor.verifyTriangle(1, 5,4,3, Vector3D(0,1,0), Vector3D(1,0,0), Vector3D(0,0,1))); QVERIFY(visitor.verifyTriangle(2, 0,1,5, Vector3D(0,0,1), Vector3D(1,0,0), Vector3D(0,1,0))); QVERIFY(visitor.verifyTriangle(3, 2,3,4, Vector3D(0,1,0), Vector3D(0,0,1), Vector3D(1,0,0))); QVERIFY(visitor.verifyTriangle(4, 4,2,0, Vector3D(1,0,0), Vector3D(0,1,0), Vector3D(0,0,1))); } void testVisitTriangleStrip() { QScopedPointer<NodeManagers> nodeManagers(new NodeManagers()); Qt3DCore::QGeometry *geometry = new Qt3DCore::QGeometry(); QScopedPointer<Qt3DRender::QGeometryRenderer> geometryRenderer(new Qt3DRender::QGeometryRenderer()); QScopedPointer<Qt3DCore::QAttribute> positionAttribute(new Qt3DCore::QAttribute()); QScopedPointer<Qt3DCore::QBuffer> dataBuffer(new Qt3DCore::QBuffer()); TestVisitor visitor(nodeManagers.data()); TestRenderer renderer; QByteArray data; data.resize(sizeof(float) * 3 * 3 * 2); float *dataPtr = reinterpret_cast<float *>(data.data()); dataPtr[0] = 0; dataPtr[1] = 0; dataPtr[2] = 1.0f; dataPtr[3] = 1.0f; dataPtr[4] = 0; dataPtr[5] = 0; dataPtr[6] = 0; dataPtr[7] = 1.0f; dataPtr[8] = 0; dataPtr[9] = 0; dataPtr[10] = 0; dataPtr[11] = 1.0f; dataPtr[12] = 1.0f; dataPtr[13] = 0; dataPtr[14] = 0; dataPtr[15] = 0; dataPtr[16] = 1.0f; dataPtr[17] = 0; dataBuffer->setData(data); Buffer *backendBuffer = nodeManagers->bufferManager()->getOrCreateResource(dataBuffer->id()); backendBuffer->setRenderer(&renderer); backendBuffer->setManager(nodeManagers->bufferManager()); simulateInitializationSync(dataBuffer.data(), backendBuffer); positionAttribute->setBuffer(dataBuffer.data()); positionAttribute->setName(Qt3DCore::QAttribute::defaultPositionAttributeName()); positionAttribute->setVertexBaseType(Qt3DCore::QAttribute::Float); positionAttribute->setVertexSize(3); positionAttribute->setCount(6); positionAttribute->setByteStride(3*4); positionAttribute->setByteOffset(0); positionAttribute->setAttributeType(Qt3DCore::QAttribute::VertexAttribute); geometry->addAttribute(positionAttribute.data()); geometryRenderer->setGeometry(geometry); geometryRenderer->setPrimitiveType(Qt3DRender::QGeometryRenderer::TriangleStrip); Attribute *backendAttribute = nodeManagers->attributeManager()->getOrCreateResource(positionAttribute->id()); backendAttribute->setRenderer(&renderer); simulateInitializationSync(positionAttribute.data(), backendAttribute); Geometry *backendGeometry = nodeManagers->geometryManager()->getOrCreateResource(geometry->id()); backendGeometry->setRenderer(&renderer); simulateInitializationSync(geometry, backendGeometry); GeometryRenderer *backendRenderer = nodeManagers->geometryRendererManager()->getOrCreateResource(geometryRenderer->id()); backendRenderer->setRenderer(&renderer); backendRenderer->setManager(nodeManagers->geometryRendererManager()); simulateInitializationSync(geometryRenderer.data(), backendRenderer); // WHEN visitor.apply(backendRenderer, Qt3DCore::QNodeId()); // THEN QVERIFY(visitor.triangleCount() == 4); QVERIFY(visitor.verifyTriangle(0, 2,1,0, Vector3D(0,1,0), Vector3D(1,0,0), Vector3D(0,0,1))); QVERIFY(visitor.verifyTriangle(1, 3,2,1, Vector3D(0,0,1), Vector3D(0,1,0), Vector3D(1,0,0))); QVERIFY(visitor.verifyTriangle(2, 4,3,2, Vector3D(1,0,0), Vector3D(0,0,1), Vector3D(0,1,0))); QVERIFY(visitor.verifyTriangle(3, 5,4,3, Vector3D(0,1,0), Vector3D(1,0,0), Vector3D(0,0,1))); } void testVisitTriangleStripIndexed() { QScopedPointer<NodeManagers> nodeManagers(new NodeManagers()); Qt3DCore::QGeometry *geometry = new Qt3DCore::QGeometry(); QScopedPointer<Qt3DRender::QGeometryRenderer> geometryRenderer(new Qt3DRender::QGeometryRenderer()); QScopedPointer<Qt3DCore::QAttribute> positionAttribute(new Qt3DCore::QAttribute()); QScopedPointer<Qt3DCore::QAttribute> indexAttribute(new Qt3DCore::QAttribute()); QScopedPointer<Qt3DCore::QBuffer> dataBuffer(new Qt3DCore::QBuffer()); QScopedPointer<Qt3DCore::QBuffer> indexDataBuffer(new Qt3DCore::QBuffer()); TestVisitor visitor(nodeManagers.data()); TestRenderer renderer; QByteArray data; data.resize(sizeof(float) * 3 * 3 * 2); float *dataPtr = reinterpret_cast<float *>(data.data()); dataPtr[0] = 0; dataPtr[1] = 0; dataPtr[2] = 1.0f; dataPtr[3] = 1.0f; dataPtr[4] = 0; dataPtr[5] = 0; dataPtr[6] = 0; dataPtr[7] = 1.0f; dataPtr[8] = 0; dataPtr[9] = 0; dataPtr[10] = 0; dataPtr[11] = 1.0f; dataPtr[12] = 1.0f; dataPtr[13] = 0; dataPtr[14] = 0; dataPtr[15] = 0; dataPtr[16] = 1.0f; dataPtr[17] = 0; dataBuffer->setData(data); Buffer *backendBuffer = nodeManagers->bufferManager()->getOrCreateResource(dataBuffer->id()); backendBuffer->setRenderer(&renderer); backendBuffer->setManager(nodeManagers->bufferManager()); simulateInitializationSync(dataBuffer.data(), backendBuffer); QByteArray indexData; indexData.resize(sizeof(uint) * 4 * 4); uint *iDataPtr = reinterpret_cast<uint *>(indexData.data()); iDataPtr[0] = 0; iDataPtr[1] = 1; iDataPtr[2] = 2; iDataPtr[3] = 3; iDataPtr[4] = 4; iDataPtr[5] = 5; iDataPtr[6] = 5; iDataPtr[7] = 1; iDataPtr[8] = 0; iDataPtr[9] = 4; iDataPtr[10] = 3; iDataPtr[11] = 2; iDataPtr[12] = static_cast<uint>(-1); iDataPtr[13] = 0; iDataPtr[14] = 1; iDataPtr[15] = 2; indexDataBuffer->setData(indexData); Buffer *backendIndexBuffer = nodeManagers->bufferManager()->getOrCreateResource(indexDataBuffer->id()); backendIndexBuffer->setRenderer(&renderer); backendIndexBuffer->setManager(nodeManagers->bufferManager()); simulateInitializationSync(indexDataBuffer.data(), backendIndexBuffer); positionAttribute->setBuffer(dataBuffer.data()); positionAttribute->setName(Qt3DCore::QAttribute::defaultPositionAttributeName()); positionAttribute->setVertexBaseType(Qt3DCore::QAttribute::Float); positionAttribute->setVertexSize(3); positionAttribute->setCount(6); positionAttribute->setByteStride(3*sizeof(float)); positionAttribute->setByteOffset(0); positionAttribute->setAttributeType(Qt3DCore::QAttribute::VertexAttribute); indexAttribute->setBuffer(indexDataBuffer.data()); indexAttribute->setVertexBaseType(Qt3DCore::QAttribute::UnsignedInt); indexAttribute->setCount(4*4); indexAttribute->setAttributeType(Qt3DCore::QAttribute::IndexAttribute); geometry->addAttribute(positionAttribute.data()); geometry->addAttribute(indexAttribute.data()); geometryRenderer->setGeometry(geometry); geometryRenderer->setPrimitiveType(Qt3DRender::QGeometryRenderer::TriangleStrip); geometryRenderer->setPrimitiveRestartEnabled(true); geometryRenderer->setRestartIndexValue(-1); Attribute *backendAttribute = nodeManagers->attributeManager()->getOrCreateResource(positionAttribute->id()); backendAttribute->setRenderer(&renderer); simulateInitializationSync(positionAttribute.data(), backendAttribute); Attribute *backendIndexAttribute = nodeManagers->attributeManager()->getOrCreateResource(indexAttribute->id()); backendIndexAttribute->setRenderer(&renderer); simulateInitializationSync(indexAttribute.data(), backendIndexAttribute); Geometry *backendGeometry = nodeManagers->geometryManager()->getOrCreateResource(geometry->id()); backendGeometry->setRenderer(&renderer); simulateInitializationSync(geometry, backendGeometry); GeometryRenderer *backendRenderer = nodeManagers->geometryRendererManager()->getOrCreateResource(geometryRenderer->id()); backendRenderer->setRenderer(&renderer); backendRenderer->setManager(nodeManagers->geometryRendererManager()); simulateInitializationSync(geometryRenderer.data(), backendRenderer); // WHEN visitor.apply(backendRenderer, Qt3DCore::QNodeId()); // THEN QCOMPARE(visitor.triangleCount(), 9U); QVERIFY(visitor.verifyTriangle(0, 2,1,0, Vector3D(0,1,0), Vector3D(1,0,0), Vector3D(0,0,1))); QVERIFY(visitor.verifyTriangle(1, 3,2,1, Vector3D(0,0,1), Vector3D(0,1,0), Vector3D(1,0,0))); QVERIFY(visitor.verifyTriangle(2, 4,3,2, Vector3D(1,0,0), Vector3D(0,0,1), Vector3D(0,1,0))); QVERIFY(visitor.verifyTriangle(3, 5,4,3, Vector3D(0,1,0), Vector3D(1,0,0), Vector3D(0,0,1))); QVERIFY(visitor.verifyTriangle(4, 0,1,5, Vector3D(0,0,1), Vector3D(1,0,0), Vector3D(0,1,0))); QVERIFY(visitor.verifyTriangle(5, 4,0,1, Vector3D(1,0,0), Vector3D(0,0,1), Vector3D(1,0,0))); QVERIFY(visitor.verifyTriangle(6, 3,4,0, Vector3D(0,0,1), Vector3D(1,0,0), Vector3D(0,0,1))); QVERIFY(visitor.verifyTriangle(7, 2,3,4, Vector3D(0,1,0), Vector3D(0,0,1), Vector3D(1,0,0))); QVERIFY(visitor.verifyTriangle(8, 2,1,0, Vector3D(0,1,0), Vector3D(1,0,0), Vector3D(0,0,1))); } void testVisitTriangleFan() { QScopedPointer<NodeManagers> nodeManagers(new NodeManagers()); Qt3DCore::QGeometry *geometry = new Qt3DCore::QGeometry(); QScopedPointer<Qt3DRender::QGeometryRenderer> geometryRenderer(new Qt3DRender::QGeometryRenderer()); QScopedPointer<Qt3DCore::QAttribute> positionAttribute(new Qt3DCore::QAttribute()); QScopedPointer<Qt3DCore::QBuffer> dataBuffer(new Qt3DCore::QBuffer()); TestVisitor visitor(nodeManagers.data()); TestRenderer renderer; QByteArray data; data.resize(sizeof(float) * 3 * 3 * 2); float *dataPtr = reinterpret_cast<float *>(data.data()); dataPtr[0] = 0; dataPtr[1] = 0; dataPtr[2] = 1.0f; dataPtr[3] = 1.0f; dataPtr[4] = 0; dataPtr[5] = 0; dataPtr[6] = 0; dataPtr[7] = 1.0f; dataPtr[8] = 0; dataPtr[9] = 0; dataPtr[10] = 0; dataPtr[11] = 1.0f; dataPtr[12] = 1.0f; dataPtr[13] = 0; dataPtr[14] = 0; dataPtr[15] = 0; dataPtr[16] = 1.0f; dataPtr[17] = 0; dataBuffer->setData(data); Buffer *backendBuffer = nodeManagers->bufferManager()->getOrCreateResource(dataBuffer->id()); backendBuffer->setRenderer(&renderer); backendBuffer->setManager(nodeManagers->bufferManager()); simulateInitializationSync(dataBuffer.data(), backendBuffer); positionAttribute->setBuffer(dataBuffer.data()); positionAttribute->setName(Qt3DCore::QAttribute::defaultPositionAttributeName()); positionAttribute->setVertexBaseType(Qt3DCore::QAttribute::Float); positionAttribute->setVertexSize(3); positionAttribute->setCount(6); positionAttribute->setByteStride(3*4); positionAttribute->setByteOffset(0); positionAttribute->setAttributeType(Qt3DCore::QAttribute::VertexAttribute); geometry->addAttribute(positionAttribute.data()); geometryRenderer->setGeometry(geometry); geometryRenderer->setPrimitiveType(Qt3DRender::QGeometryRenderer::TriangleFan); Attribute *backendAttribute = nodeManagers->attributeManager()->getOrCreateResource(positionAttribute->id()); backendAttribute->setRenderer(&renderer); simulateInitializationSync(positionAttribute.data(), backendAttribute); Geometry *backendGeometry = nodeManagers->geometryManager()->getOrCreateResource(geometry->id()); backendGeometry->setRenderer(&renderer); simulateInitializationSync(geometry, backendGeometry); GeometryRenderer *backendRenderer = nodeManagers->geometryRendererManager()->getOrCreateResource(geometryRenderer->id()); backendRenderer->setRenderer(&renderer); backendRenderer->setManager(nodeManagers->geometryRendererManager()); simulateInitializationSync(geometryRenderer.data(), backendRenderer); // WHEN visitor.apply(backendRenderer, Qt3DCore::QNodeId()); // THEN QVERIFY(visitor.triangleCount() == 4); QVERIFY(visitor.verifyTriangle(0, 2,1,0, Vector3D(0,1,0), Vector3D(1,0,0), Vector3D(0,0,1))); QVERIFY(visitor.verifyTriangle(1, 3,2,0, Vector3D(0,0,1), Vector3D(0,1,0), Vector3D(0,0,1))); QVERIFY(visitor.verifyTriangle(2, 4,3,0, Vector3D(1,0,0), Vector3D(0,0,1), Vector3D(0,0,1))); QVERIFY(visitor.verifyTriangle(3, 5,4,0, Vector3D(0,1,0), Vector3D(1,0,0), Vector3D(0,0,1))); } void testVisitTriangleFanIndexed() { QScopedPointer<NodeManagers> nodeManagers(new NodeManagers()); Qt3DCore::QGeometry *geometry = new Qt3DCore::QGeometry(); QScopedPointer<Qt3DRender::QGeometryRenderer> geometryRenderer(new Qt3DRender::QGeometryRenderer()); QScopedPointer<Qt3DCore::QAttribute> positionAttribute(new Qt3DCore::QAttribute()); QScopedPointer<Qt3DCore::QAttribute> indexAttribute(new Qt3DCore::QAttribute()); QScopedPointer<Qt3DCore::QBuffer> dataBuffer(new Qt3DCore::QBuffer()); QScopedPointer<Qt3DCore::QBuffer> indexDataBuffer(new Qt3DCore::QBuffer()); TestVisitor visitor(nodeManagers.data()); TestRenderer renderer; QByteArray data; data.resize(sizeof(float) * 3 * 3 * 2); float *dataPtr = reinterpret_cast<float *>(data.data()); dataPtr[0] = 0; dataPtr[1] = 0; dataPtr[2] = 1.0f; dataPtr[3] = 1.0f; dataPtr[4] = 0; dataPtr[5] = 0; dataPtr[6] = 0; dataPtr[7] = 1.0f; dataPtr[8] = 0; dataPtr[9] = 0; dataPtr[10] = 0; dataPtr[11] = 1.0f; dataPtr[12] = 1.0f; dataPtr[13] = 0; dataPtr[14] = 0; dataPtr[15] = 0; dataPtr[16] = 1.0f; dataPtr[17] = 0; dataBuffer->setData(data); Buffer *backendBuffer = nodeManagers->bufferManager()->getOrCreateResource(dataBuffer->id()); backendBuffer->setRenderer(&renderer); backendBuffer->setManager(nodeManagers->bufferManager()); simulateInitializationSync(dataBuffer.data(), backendBuffer); QByteArray indexData; indexData.resize(sizeof(uint) * 10); uint *iDataPtr = reinterpret_cast<uint *>(indexData.data()); iDataPtr[0] = 0; iDataPtr[1] = 1; iDataPtr[2] = 2; iDataPtr[3] = 3; iDataPtr[4] = 4; iDataPtr[5] = 5; iDataPtr[6] = static_cast<uint>(-1); iDataPtr[7] = 0; iDataPtr[8] = 1; iDataPtr[9] = 2; indexDataBuffer->setData(indexData); Buffer *backendIndexBuffer = nodeManagers->bufferManager()->getOrCreateResource(indexDataBuffer->id()); backendIndexBuffer->setRenderer(&renderer); backendIndexBuffer->setManager(nodeManagers->bufferManager()); simulateInitializationSync(indexDataBuffer.data(), backendIndexBuffer); positionAttribute->setBuffer(dataBuffer.data()); positionAttribute->setName(Qt3DCore::QAttribute::defaultPositionAttributeName()); positionAttribute->setVertexBaseType(Qt3DCore::QAttribute::Float); positionAttribute->setVertexSize(3); positionAttribute->setCount(6); positionAttribute->setByteStride(3*sizeof(float)); positionAttribute->setByteOffset(0); positionAttribute->setAttributeType(Qt3DCore::QAttribute::VertexAttribute); indexAttribute->setBuffer(indexDataBuffer.data()); indexAttribute->setVertexBaseType(Qt3DCore::QAttribute::UnsignedInt); indexAttribute->setCount(10); indexAttribute->setAttributeType(Qt3DCore::QAttribute::IndexAttribute); geometry->addAttribute(positionAttribute.data()); geometry->addAttribute(indexAttribute.data()); geometryRenderer->setGeometry(geometry); geometryRenderer->setPrimitiveType(Qt3DRender::QGeometryRenderer::TriangleFan); geometryRenderer->setPrimitiveRestartEnabled(true); geometryRenderer->setRestartIndexValue(-1); Attribute *backendAttribute = nodeManagers->attributeManager()->getOrCreateResource(positionAttribute->id()); backendAttribute->setRenderer(&renderer); simulateInitializationSync(positionAttribute.data(), backendAttribute); Attribute *backendIndexAttribute = nodeManagers->attributeManager()->getOrCreateResource(indexAttribute->id()); backendIndexAttribute->setRenderer(&renderer); simulateInitializationSync(indexAttribute.data(), backendIndexAttribute); Geometry *backendGeometry = nodeManagers->geometryManager()->getOrCreateResource(geometry->id()); backendGeometry->setRenderer(&renderer); simulateInitializationSync(geometry, backendGeometry); GeometryRenderer *backendRenderer = nodeManagers->geometryRendererManager()->getOrCreateResource(geometryRenderer->id()); backendRenderer->setRenderer(&renderer); backendRenderer->setManager(nodeManagers->geometryRendererManager()); simulateInitializationSync(geometryRenderer.data(), backendRenderer); // WHEN visitor.apply(backendRenderer, Qt3DCore::QNodeId()); // THEN QCOMPARE(visitor.triangleCount(), 5U); QVERIFY(visitor.verifyTriangle(0, 2,1,0, Vector3D(0,1,0), Vector3D(1,0,0), Vector3D(0,0,1))); QVERIFY(visitor.verifyTriangle(1, 3,2,0, Vector3D(0,0,1), Vector3D(0,1,0), Vector3D(0,0,1))); QVERIFY(visitor.verifyTriangle(2, 4,3,0, Vector3D(1,0,0), Vector3D(0,0,1), Vector3D(0,0,1))); QVERIFY(visitor.verifyTriangle(3, 5,4,0, Vector3D(0,1,0), Vector3D(1,0,0), Vector3D(0,0,1))); QVERIFY(visitor.verifyTriangle(4, 2,1,0, Vector3D(0,1,0), Vector3D(1,0,0), Vector3D(0,0,1))); } void testVisitTrianglesAdjacency() { QScopedPointer<NodeManagers> nodeManagers(new NodeManagers()); Qt3DCore::QGeometry *geometry = new Qt3DCore::QGeometry(); QScopedPointer<Qt3DRender::QGeometryRenderer> geometryRenderer(new Qt3DRender::QGeometryRenderer()); QScopedPointer<Qt3DCore::QAttribute> positionAttribute(new Qt3DCore::QAttribute()); QScopedPointer<Qt3DCore::QBuffer> dataBuffer(new Qt3DCore::QBuffer()); TestVisitor visitor(nodeManagers.data()); TestRenderer renderer; QByteArray data; data.resize(sizeof(float) * 3 * 3 * 2); float *dataPtr = reinterpret_cast<float *>(data.data()); dataPtr[0] = 0; dataPtr[1] = 0; dataPtr[2] = 1.0f; dataPtr[3] = 1.0f; dataPtr[4] = 0; dataPtr[5] = 0; dataPtr[6] = 0; dataPtr[7] = 1.0f; dataPtr[8] = 0; dataPtr[9] = 0; dataPtr[10] = 0; dataPtr[11] = 1.0f; dataPtr[12] = 1.0f; dataPtr[13] = 0; dataPtr[14] = 0; dataPtr[15] = 0; dataPtr[16] = 1.0f; dataPtr[17] = 0; dataBuffer->setData(data); Buffer *backendBuffer = nodeManagers->bufferManager()->getOrCreateResource(dataBuffer->id()); backendBuffer->setRenderer(&renderer); backendBuffer->setManager(nodeManagers->bufferManager()); simulateInitializationSync(dataBuffer.data(), backendBuffer); positionAttribute->setBuffer(dataBuffer.data()); positionAttribute->setName(Qt3DCore::QAttribute::defaultPositionAttributeName()); positionAttribute->setVertexBaseType(Qt3DCore::QAttribute::Float); positionAttribute->setVertexSize(3); positionAttribute->setCount(6); positionAttribute->setByteStride(3*4); positionAttribute->setByteOffset(0); positionAttribute->setAttributeType(Qt3DCore::QAttribute::VertexAttribute); geometry->addAttribute(positionAttribute.data()); geometryRenderer->setGeometry(geometry); geometryRenderer->setPrimitiveType(Qt3DRender::QGeometryRenderer::TrianglesAdjacency); Attribute *backendAttribute = nodeManagers->attributeManager()->getOrCreateResource(positionAttribute->id()); backendAttribute->setRenderer(&renderer); simulateInitializationSync(positionAttribute.data(), backendAttribute); Geometry *backendGeometry = nodeManagers->geometryManager()->getOrCreateResource(geometry->id()); backendGeometry->setRenderer(&renderer); simulateInitializationSync(geometry, backendGeometry); GeometryRenderer *backendRenderer = nodeManagers->geometryRendererManager()->getOrCreateResource(geometryRenderer->id()); backendRenderer->setRenderer(&renderer); backendRenderer->setManager(nodeManagers->geometryRendererManager()); simulateInitializationSync(geometryRenderer.data(), backendRenderer); // WHEN visitor.apply(backendRenderer, Qt3DCore::QNodeId()); // THEN QVERIFY(visitor.triangleCount() == 1); QVERIFY(visitor.verifyTriangle(0, 4,2,0, Vector3D(1,0,0), Vector3D(0,1,0), Vector3D(0,0,1))); } void testVisitTrianglesAdjacencyIndexed() { QScopedPointer<NodeManagers> nodeManagers(new NodeManagers()); Qt3DCore::QGeometry *geometry = new Qt3DCore::QGeometry(); QScopedPointer<Qt3DRender::QGeometryRenderer> geometryRenderer(new Qt3DRender::QGeometryRenderer()); QScopedPointer<Qt3DCore::QAttribute> positionAttribute(new Qt3DCore::QAttribute()); QScopedPointer<Qt3DCore::QAttribute> indexAttribute(new Qt3DCore::QAttribute()); QScopedPointer<Qt3DCore::QBuffer> dataBuffer(new Qt3DCore::QBuffer()); QScopedPointer<Qt3DCore::QBuffer> indexDataBuffer(new Qt3DCore::QBuffer()); TestVisitor visitor(nodeManagers.data()); TestRenderer renderer; QByteArray data; data.resize(sizeof(float) * 3 * 3 * 2); float *dataPtr = reinterpret_cast<float *>(data.data()); dataPtr[0] = 0; dataPtr[1] = 0; dataPtr[2] = 1.0f; dataPtr[3] = 1.0f; dataPtr[4] = 0; dataPtr[5] = 0; dataPtr[6] = 0; dataPtr[7] = 1.0f; dataPtr[8] = 0; dataPtr[9] = 0; dataPtr[10] = 0; dataPtr[11] = 1.0f; dataPtr[12] = 1.0f; dataPtr[13] = 0; dataPtr[14] = 0; dataPtr[15] = 0; dataPtr[16] = 1.0f; dataPtr[17] = 0; dataBuffer->setData(data); Buffer *backendBuffer = nodeManagers->bufferManager()->getOrCreateResource(dataBuffer->id()); backendBuffer->setRenderer(&renderer); backendBuffer->setManager(nodeManagers->bufferManager()); simulateInitializationSync(dataBuffer.data(), backendBuffer); QByteArray indexData; indexData.resize(sizeof(uint) * 3 * 4); uint *iDataPtr = reinterpret_cast<uint *>(indexData.data()); iDataPtr[0] = 0; iDataPtr[1] = 1; iDataPtr[2] = 2; iDataPtr[3] = 3; iDataPtr[4] = 4; iDataPtr[5] = 5; iDataPtr[6] = 5; iDataPtr[7] = 1; iDataPtr[8] = 0; iDataPtr[9] = 4; iDataPtr[10] = 3; iDataPtr[11] = 2; indexDataBuffer->setData(indexData); Buffer *backendIndexBuffer = nodeManagers->bufferManager()->getOrCreateResource(indexDataBuffer->id()); backendIndexBuffer->setRenderer(&renderer); backendIndexBuffer->setManager(nodeManagers->bufferManager()); simulateInitializationSync(indexDataBuffer.data(), backendIndexBuffer); positionAttribute->setBuffer(dataBuffer.data()); positionAttribute->setName(Qt3DCore::QAttribute::defaultPositionAttributeName()); positionAttribute->setVertexBaseType(Qt3DCore::QAttribute::Float); positionAttribute->setVertexSize(3); positionAttribute->setCount(6); positionAttribute->setByteStride(3*sizeof(float)); positionAttribute->setByteOffset(0); positionAttribute->setAttributeType(Qt3DCore::QAttribute::VertexAttribute); indexAttribute->setBuffer(indexDataBuffer.data()); indexAttribute->setVertexBaseType(Qt3DCore::QAttribute::UnsignedInt); indexAttribute->setCount(3*4); indexAttribute->setAttributeType(Qt3DCore::QAttribute::IndexAttribute); geometry->addAttribute(positionAttribute.data()); geometry->addAttribute(indexAttribute.data()); geometryRenderer->setGeometry(geometry); geometryRenderer->setPrimitiveType(Qt3DRender::QGeometryRenderer::TrianglesAdjacency); Attribute *backendAttribute = nodeManagers->attributeManager()->getOrCreateResource(positionAttribute->id()); backendAttribute->setRenderer(&renderer); simulateInitializationSync(positionAttribute.data(), backendAttribute); Attribute *backendIndexAttribute = nodeManagers->attributeManager()->getOrCreateResource(indexAttribute->id()); backendIndexAttribute->setRenderer(&renderer); simulateInitializationSync(indexAttribute.data(), backendIndexAttribute); Geometry *backendGeometry = nodeManagers->geometryManager()->getOrCreateResource(geometry->id()); backendGeometry->setRenderer(&renderer); simulateInitializationSync(geometry, backendGeometry); GeometryRenderer *backendRenderer = nodeManagers->geometryRendererManager()->getOrCreateResource(geometryRenderer->id()); backendRenderer->setRenderer(&renderer); backendRenderer->setManager(nodeManagers->geometryRendererManager()); simulateInitializationSync(geometryRenderer.data(), backendRenderer); // WHEN visitor.apply(backendRenderer, Qt3DCore::QNodeId()); // THEN QVERIFY(visitor.triangleCount() == 2); QVERIFY(visitor.verifyTriangle(0, 4,2,0, Vector3D(1,0,0), Vector3D(0,1,0), Vector3D(0,0,1))); QVERIFY(visitor.verifyTriangle(1, 3,0,5, Vector3D(0,0,1), Vector3D(0,0,1), Vector3D(0,1,0))); } void testVisitTriangleStripAdjacency() { QSKIP("TriangleStripAdjacency not implemented"); QScopedPointer<NodeManagers> nodeManagers(new NodeManagers()); Qt3DCore::QGeometry *geometry = new Qt3DCore::QGeometry(); QScopedPointer<Qt3DRender::QGeometryRenderer> geometryRenderer(new Qt3DRender::QGeometryRenderer()); QScopedPointer<Qt3DCore::QAttribute> positionAttribute(new Qt3DCore::QAttribute()); QScopedPointer<Qt3DCore::QBuffer> dataBuffer(new Qt3DCore::QBuffer()); TestVisitor visitor(nodeManagers.data()); TestRenderer renderer; QByteArray data; data.resize(sizeof(float) * 3 * 8); float *dataPtr = reinterpret_cast<float *>(data.data()); dataPtr[0] = 0; dataPtr[1] = 0; dataPtr[2] = 1.0f; dataPtr[3] = 1.0f; dataPtr[4] = 0; dataPtr[5] = 0; dataPtr[6] = 0; dataPtr[7] = 1.0f; dataPtr[8] = 0; dataPtr[9] = 0; dataPtr[10] = 0; dataPtr[11] = 1.0f; dataPtr[12] = 1.0f; dataPtr[13] = 0; dataPtr[14] = 0; dataPtr[15] = 0; dataPtr[16] = 1.0f; dataPtr[17] = 0; dataPtr[18] = 1.0f; dataPtr[19] = 1.0f; dataPtr[20] = 1.0f; dataPtr[21] = 0; dataPtr[22] = 0; dataPtr[22] = 0; dataBuffer->setData(data); Buffer *backendBuffer = nodeManagers->bufferManager()->getOrCreateResource(dataBuffer->id()); backendBuffer->setRenderer(&renderer); backendBuffer->setManager(nodeManagers->bufferManager()); simulateInitializationSync(dataBuffer.data(), backendBuffer); positionAttribute->setBuffer(dataBuffer.data()); positionAttribute->setName(Qt3DCore::QAttribute::defaultPositionAttributeName()); positionAttribute->setVertexBaseType(Qt3DCore::QAttribute::Float); positionAttribute->setVertexSize(3); positionAttribute->setCount(8); positionAttribute->setByteStride(3*4); positionAttribute->setByteOffset(0); positionAttribute->setAttributeType(Qt3DCore::QAttribute::VertexAttribute); geometry->addAttribute(positionAttribute.data()); geometryRenderer->setGeometry(geometry); geometryRenderer->setPrimitiveType(Qt3DRender::QGeometryRenderer::TriangleStripAdjacency); Attribute *backendAttribute = nodeManagers->attributeManager()->getOrCreateResource(positionAttribute->id()); backendAttribute->setRenderer(&renderer); simulateInitializationSync(positionAttribute.data(), backendAttribute); Geometry *backendGeometry = nodeManagers->geometryManager()->getOrCreateResource(geometry->id()); backendGeometry->setRenderer(&renderer); simulateInitializationSync(geometry, backendGeometry); GeometryRenderer *backendRenderer = nodeManagers->geometryRendererManager()->getOrCreateResource(geometryRenderer->id()); backendRenderer->setRenderer(&renderer); backendRenderer->setManager(nodeManagers->geometryRendererManager()); simulateInitializationSync(geometryRenderer.data(), backendRenderer); // WHEN visitor.apply(backendRenderer, Qt3DCore::QNodeId()); // THEN QVERIFY(visitor.triangleCount() == 2); QVERIFY(visitor.verifyTriangle(0, 4,2,0, Vector3D(1,0,0), Vector3D(0,1,0), Vector3D(0,0,1))); QVERIFY(visitor.verifyTriangle(1, 6,4,2, Vector3D(1,1,1), Vector3D(1,0,0), Vector3D(0,1,0))); } void testVisitTriangleStripAdjacencyIndexed() { QSKIP("TriangleStripAdjacency not implemented"); QScopedPointer<NodeManagers> nodeManagers(new NodeManagers()); Qt3DCore::QGeometry *geometry = new Qt3DCore::QGeometry(); QScopedPointer<Qt3DRender::QGeometryRenderer> geometryRenderer(new Qt3DRender::QGeometryRenderer()); QScopedPointer<Qt3DCore::QAttribute> positionAttribute(new Qt3DCore::QAttribute()); QScopedPointer<Qt3DCore::QAttribute> indexAttribute(new Qt3DCore::QAttribute()); QScopedPointer<Qt3DCore::QBuffer> dataBuffer(new Qt3DCore::QBuffer()); QScopedPointer<Qt3DCore::QBuffer> indexDataBuffer(new Qt3DCore::QBuffer()); TestVisitor visitor(nodeManagers.data()); TestRenderer renderer; QByteArray data; data.resize(sizeof(float) * 3 * 3 * 2); float *dataPtr = reinterpret_cast<float *>(data.data()); dataPtr[0] = 0; dataPtr[1] = 0; dataPtr[2] = 1.0f; dataPtr[3] = 1.0f; dataPtr[4] = 0; dataPtr[5] = 0; dataPtr[6] = 0; dataPtr[7] = 1.0f; dataPtr[8] = 0; dataPtr[9] = 0; dataPtr[10] = 0; dataPtr[11] = 1.0f; dataPtr[12] = 1.0f; dataPtr[13] = 0; dataPtr[14] = 0; dataPtr[15] = 0; dataPtr[16] = 1.0f; dataPtr[17] = 0; dataBuffer->setData(data); Buffer *backendBuffer = nodeManagers->bufferManager()->getOrCreateResource(dataBuffer->id()); backendBuffer->setRenderer(&renderer); backendBuffer->setManager(nodeManagers->bufferManager()); simulateInitializationSync(dataBuffer.data(), backendBuffer); QByteArray indexData; indexData.resize(sizeof(uint) * 8); uint *iDataPtr = reinterpret_cast<uint *>(indexData.data()); iDataPtr[0] = 0; iDataPtr[1] = 1; iDataPtr[2] = 2; iDataPtr[3] = 3; iDataPtr[4] = 4; iDataPtr[5] = 5; iDataPtr[6] = 5; iDataPtr[7] = 1; indexDataBuffer->setData(indexData); Buffer *backendIndexBuffer = nodeManagers->bufferManager()->getOrCreateResource(indexDataBuffer->id()); backendIndexBuffer->setRenderer(&renderer); backendIndexBuffer->setManager(nodeManagers->bufferManager()); simulateInitializationSync(indexDataBuffer.data(), backendIndexBuffer); positionAttribute->setBuffer(dataBuffer.data()); positionAttribute->setName(Qt3DCore::QAttribute::defaultPositionAttributeName()); positionAttribute->setVertexBaseType(Qt3DCore::QAttribute::Float); positionAttribute->setVertexSize(3); positionAttribute->setCount(6); positionAttribute->setByteStride(3*sizeof(float)); positionAttribute->setByteOffset(0); positionAttribute->setAttributeType(Qt3DCore::QAttribute::VertexAttribute); indexAttribute->setBuffer(indexDataBuffer.data()); indexAttribute->setVertexBaseType(Qt3DCore::QAttribute::UnsignedInt); indexAttribute->setCount(8); indexAttribute->setAttributeType(Qt3DCore::QAttribute::IndexAttribute); geometry->addAttribute(positionAttribute.data()); geometry->addAttribute(indexAttribute.data()); geometryRenderer->setGeometry(geometry); geometryRenderer->setPrimitiveType(Qt3DRender::QGeometryRenderer::TriangleStrip); Attribute *backendAttribute = nodeManagers->attributeManager()->getOrCreateResource(positionAttribute->id()); backendAttribute->setRenderer(&renderer); simulateInitializationSync(positionAttribute.data(), backendAttribute); Attribute *backendIndexAttribute = nodeManagers->attributeManager()->getOrCreateResource(indexAttribute->id()); backendIndexAttribute->setRenderer(&renderer); simulateInitializationSync(indexAttribute.data(), backendIndexAttribute); Geometry *backendGeometry = nodeManagers->geometryManager()->getOrCreateResource(geometry->id()); backendGeometry->setRenderer(&renderer); simulateInitializationSync(geometry, backendGeometry); GeometryRenderer *backendRenderer = nodeManagers->geometryRendererManager()->getOrCreateResource(geometryRenderer->id()); backendRenderer->setRenderer(&renderer); backendRenderer->setManager(nodeManagers->geometryRendererManager()); simulateInitializationSync(geometryRenderer.data(), backendRenderer); // WHEN visitor.apply(backendRenderer, Qt3DCore::QNodeId()); // THEN QVERIFY(visitor.triangleCount() == 2); QVERIFY(visitor.verifyTriangle(0, 4,2,0, Vector3D(1,0,0), Vector3D(0,1,0), Vector3D(0,0,1))); QVERIFY(visitor.verifyTriangle(1, 5,4,2, Vector3D(0,1,0), Vector3D(1,0,0), Vector3D(0,1,0))); } }; QTEST_MAIN(tst_TriangleVisitor) #include "tst_trianglevisitor.moc"
{ "pile_set_name": "Github" }
name=Metzali, Tower of Triumph image=https://magiccards.info/scans/en/rix/165b.jpg value=2.500 rarity=R type=Legendary,Land ability={T}: Add one mana of any color.;\ {1}{R}, {T}: SN deals 2 damage to each opponent.;\ {2}{W}, {T}: Choose a creature at random that attacked this turn. Destroy that creature. transform=Path of Mettle hidden timing=land oracle={T}: Add one mana of any color.\n{1}{R}, {T}: Metzali, Tower of Triumph deals 2 damage to each opponent.\n{2}{W}, {T}: Choose a creature at random that attacked this turn. Destroy that creature.
{ "pile_set_name": "Github" }
/** * The MIT License * Copyright (c) 2014-2016 Ilkka Seppälä * * 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 com.iluwatar.delegation.simple.printers; import com.iluwatar.delegation.simple.Printer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Specialised Implementation of {@link Printer} for a Canon Printer, in * this case the message to be printed is appended to "Canon Printer : " * * @see Printer */ public class CanonPrinter implements Printer { private static final Logger LOGGER = LoggerFactory.getLogger(CanonPrinter.class); /** * {@inheritDoc} */ @Override public void print(String message) { LOGGER.info("Canon Printer : {}", message); } }
{ "pile_set_name": "Github" }
within DataReconciliationSimpleTests; model ExtractionSetSTest1_corrected Real x1(uncertain=Uncertainty.refine); Real x2(uncertain=Uncertainty.refine); Real x3(uncertain=Uncertainty.refine); Real y1; Real y2; Real y3 annotation(Diagram(coordinateSystem(extent={{-148.5,-105.0},{148.5,105.0}}, preserveAspectRatio=true, initialScale=0.1, grid={10,10}))); equation x1 = 0; x1-x2 = 0; y1 = x2+2*x3; x3-y1+y2=x2; y2+y3=0; y2-2*y3=3; end ExtractionSetSTest1_corrected;
{ "pile_set_name": "Github" }