text
stringlengths
2
99k
meta
dict
/* * Copyright 2014 - 2020 Blazebit. * * 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.blazebit.persistence.view.testsuite.update.entity.creatableonly.model; import com.blazebit.persistence.testsuite.entity.Document; import com.blazebit.persistence.testsuite.entity.Person; import com.blazebit.persistence.view.CascadeType; import com.blazebit.persistence.view.EntityView; import com.blazebit.persistence.view.UpdatableEntityView; import com.blazebit.persistence.view.UpdatableMapping; import com.blazebit.persistence.view.testsuite.update.entity.model.UpdatableDocumentEntityWithMapsViewBase; import java.util.Map; /** * * @author Christian Beikov * @since 1.2.0 */ @UpdatableEntityView @EntityView(Document.class) public interface UpdatableDocumentEntityWithMapsView extends UpdatableDocumentEntityWithMapsViewBase { @UpdatableMapping(updatable = false, cascade = { CascadeType.PERSIST }) public Map<Integer, Person> getContacts(); public void setContacts(Map<Integer, Person> contacts); }
{ "pile_set_name": "Github" }
<?php /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Autoload; /** * ClassLoader implements a PSR-0, PSR-4 and classmap class loader. * * $loader = new \Composer\Autoload\ClassLoader(); * * // register classes with namespaces * $loader->add('Symfony\Component', __DIR__.'/component'); * $loader->add('Symfony', __DIR__.'/framework'); * * // activate the autoloader * $loader->register(); * * // to enable searching the include path (eg. for PEAR packages) * $loader->setUseIncludePath(true); * * In this example, if you try to use a class in the Symfony\Component * namespace or one of its children (Symfony\Component\Console for instance), * the autoloader will first look for the class under the component/ * directory, and it will then fallback to the framework/ directory if not * found before giving up. * * This class is loosely based on the Symfony UniversalClassLoader. * * @author Fabien Potencier <fabien@symfony.com> * @author Jordi Boggiano <j.boggiano@seld.be> * @see http://www.php-fig.org/psr/psr-0/ * @see http://www.php-fig.org/psr/psr-4/ */ class ClassLoader { // PSR-4 private $prefixLengthsPsr4 = array(); private $prefixDirsPsr4 = array(); private $fallbackDirsPsr4 = array(); // PSR-0 private $prefixesPsr0 = array(); private $fallbackDirsPsr0 = array(); private $useIncludePath = false; private $classMap = array(); private $classMapAuthoritative = false; private $missingClasses = array(); private $apcuPrefix; public function getPrefixes() { if (!empty($this->prefixesPsr0)) { return call_user_func_array('array_merge', $this->prefixesPsr0); } return array(); } public function getPrefixesPsr4() { return $this->prefixDirsPsr4; } public function getFallbackDirs() { return $this->fallbackDirsPsr0; } public function getFallbackDirsPsr4() { return $this->fallbackDirsPsr4; } public function getClassMap() { return $this->classMap; } /** * @param array $classMap Class to filename map */ public function addClassMap(array $classMap) { if ($this->classMap) { $this->classMap = array_merge($this->classMap, $classMap); } else { $this->classMap = $classMap; } } /** * Registers a set of PSR-0 directories for a given prefix, either * appending or prepending to the ones previously set for this prefix. * * @param string $prefix The prefix * @param array|string $paths The PSR-0 root directories * @param bool $prepend Whether to prepend the directories */ public function add($prefix, $paths, $prepend = false) { if (!$prefix) { if ($prepend) { $this->fallbackDirsPsr0 = array_merge( (array) $paths, $this->fallbackDirsPsr0 ); } else { $this->fallbackDirsPsr0 = array_merge( $this->fallbackDirsPsr0, (array) $paths ); } return; } $first = $prefix[0]; if (!isset($this->prefixesPsr0[$first][$prefix])) { $this->prefixesPsr0[$first][$prefix] = (array) $paths; return; } if ($prepend) { $this->prefixesPsr0[$first][$prefix] = array_merge( (array) $paths, $this->prefixesPsr0[$first][$prefix] ); } else { $this->prefixesPsr0[$first][$prefix] = array_merge( $this->prefixesPsr0[$first][$prefix], (array) $paths ); } } /** * Registers a set of PSR-4 directories for a given namespace, either * appending or prepending to the ones previously set for this namespace. * * @param string $prefix The prefix/namespace, with trailing '\\' * @param array|string $paths The PSR-4 base directories * @param bool $prepend Whether to prepend the directories * * @throws \InvalidArgumentException */ public function addPsr4($prefix, $paths, $prepend = false) { if (!$prefix) { // Register directories for the root namespace. if ($prepend) { $this->fallbackDirsPsr4 = array_merge( (array) $paths, $this->fallbackDirsPsr4 ); } else { $this->fallbackDirsPsr4 = array_merge( $this->fallbackDirsPsr4, (array) $paths ); } } elseif (!isset($this->prefixDirsPsr4[$prefix])) { // Register directories for a new namespace. $length = strlen($prefix); if ('\\' !== $prefix[$length - 1]) { throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); } $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; $this->prefixDirsPsr4[$prefix] = (array) $paths; } elseif ($prepend) { // Prepend directories for an already registered namespace. $this->prefixDirsPsr4[$prefix] = array_merge( (array) $paths, $this->prefixDirsPsr4[$prefix] ); } else { // Append directories for an already registered namespace. $this->prefixDirsPsr4[$prefix] = array_merge( $this->prefixDirsPsr4[$prefix], (array) $paths ); } } /** * Registers a set of PSR-0 directories for a given prefix, * replacing any others previously set for this prefix. * * @param string $prefix The prefix * @param array|string $paths The PSR-0 base directories */ public function set($prefix, $paths) { if (!$prefix) { $this->fallbackDirsPsr0 = (array) $paths; } else { $this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths; } } /** * Registers a set of PSR-4 directories for a given namespace, * replacing any others previously set for this namespace. * * @param string $prefix The prefix/namespace, with trailing '\\' * @param array|string $paths The PSR-4 base directories * * @throws \InvalidArgumentException */ public function setPsr4($prefix, $paths) { if (!$prefix) { $this->fallbackDirsPsr4 = (array) $paths; } else { $length = strlen($prefix); if ('\\' !== $prefix[$length - 1]) { throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); } $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; $this->prefixDirsPsr4[$prefix] = (array) $paths; } } /** * Turns on searching the include path for class files. * * @param bool $useIncludePath */ public function setUseIncludePath($useIncludePath) { $this->useIncludePath = $useIncludePath; } /** * Can be used to check if the autoloader uses the include path to check * for classes. * * @return bool */ public function getUseIncludePath() { return $this->useIncludePath; } /** * Turns off searching the prefix and fallback directories for classes * that have not been registered with the class map. * * @param bool $classMapAuthoritative */ public function setClassMapAuthoritative($classMapAuthoritative) { $this->classMapAuthoritative = $classMapAuthoritative; } /** * Should class lookup fail if not found in the current class map? * * @return bool */ public function isClassMapAuthoritative() { return $this->classMapAuthoritative; } /** * APCu prefix to use to cache found/not-found classes, if the extension is enabled. * * @param string|null $apcuPrefix */ public function setApcuPrefix($apcuPrefix) { $this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null; } /** * The APCu prefix in use, or null if APCu caching is not enabled. * * @return string|null */ public function getApcuPrefix() { return $this->apcuPrefix; } /** * Registers this instance as an autoloader. * * @param bool $prepend Whether to prepend the autoloader or not */ public function register($prepend = false) { spl_autoload_register(array($this, 'loadClass'), true, $prepend); } /** * Unregisters this instance as an autoloader. */ public function unregister() { spl_autoload_unregister(array($this, 'loadClass')); } /** * Loads the given class or interface. * * @param string $class The name of the class * @return bool|null True if loaded, null otherwise */ public function loadClass($class) { if ($file = $this->findFile($class)) { includeFile($file); return true; } } /** * Finds the path to the file where the class is defined. * * @param string $class The name of the class * * @return string|false The path if found, false otherwise */ public function findFile($class) { // class map lookup if (isset($this->classMap[$class])) { return $this->classMap[$class]; } if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) { return false; } if (null !== $this->apcuPrefix) { $file = apcu_fetch($this->apcuPrefix.$class, $hit); if ($hit) { return $file; } } $file = $this->findFileWithExtension($class, '.php'); // Search for Hack files if we are running on HHVM if (false === $file && defined('HHVM_VERSION')) { $file = $this->findFileWithExtension($class, '.hh'); } if (null !== $this->apcuPrefix) { apcu_add($this->apcuPrefix.$class, $file); } if (false === $file) { // Remember that this class does not exist. $this->missingClasses[$class] = true; } return $file; } private function findFileWithExtension($class, $ext) { // PSR-4 lookup $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext; $first = $class[0]; if (isset($this->prefixLengthsPsr4[$first])) { $subPath = $class; while (false !== $lastPos = strrpos($subPath, '\\')) { $subPath = substr($subPath, 0, $lastPos); $search = $subPath . '\\'; if (isset($this->prefixDirsPsr4[$search])) { $pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1); foreach ($this->prefixDirsPsr4[$search] as $dir) { if (file_exists($file = $dir . $pathEnd)) { return $file; } } } } } // PSR-4 fallback dirs foreach ($this->fallbackDirsPsr4 as $dir) { if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) { return $file; } } // PSR-0 lookup if (false !== $pos = strrpos($class, '\\')) { // namespaced class name $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1) . strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR); } else { // PEAR-like class name $logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext; } if (isset($this->prefixesPsr0[$first])) { foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) { if (0 === strpos($class, $prefix)) { foreach ($dirs as $dir) { if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { return $file; } } } } } // PSR-0 fallback dirs foreach ($this->fallbackDirsPsr0 as $dir) { if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { return $file; } } // PSR-0 include paths. if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) { return $file; } return false; } } /** * Scope isolated include. * * Prevents access to $this/self from included files. */ function includeFile($file) { include $file; }
{ "pile_set_name": "Github" }
# Translations {#translations} **Interested in translating the book?** This book is licensed under the [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License](http://creativecommons.org/licenses/by-nc-sa/4.0/). This means that you are allowed to translate it and put it online. You have to mention me as original author and you are not allowed to sell the book. If you are interested in translating the book, you can write a message and I can link your translation here. My address is christoph.molnar.ai@gmail.com . **List of translations** **Chinese**: - https://github.com/MingchaoZhu/InterpretableMLBook Complete translations by [Mingchao Zhu](https://github.com/MingchaoZhu). - https://blog.csdn.net/wizardforcel/article/details/98992150 Translation of most chapters, by CSDN, an online community of programmers. - https://zhuanlan.zhihu.com/p/63408696 Translation of some chapters by 知乎. The website also includes questions and answers from various users. **Korean**: - https://tootouch.github.io/IML/taxonomy_of_interpretability_methods/ Complete Korean translation by [TooTouch](https://tootouch.github.io/) - https://subinium.github.io/IML/ Partial Korean translation by [An Subin](https://subinium.github.io/) **Spanish** - https://fedefliguer.github.io/AAI/ First chapters translated by [Federico Fliguer](https://fedefliguer.github.io/) If you know of any other translation of the book or of individual chapters, I would be grateful to hear about it and list it here. You can reach me via email: christoph.molnar.ai@gmail.com .
{ "pile_set_name": "Github" }
# 快速上手 安装启动好whistle,打开whistle的web界面:[http://local.whistlejs.com](http://local.whistlejs.com/) ![配置whistle规则界面]() whistle功能众多,基本上覆盖抓包调试工具方方面面的功能,但每个功能的操作方式都差不多,基本上都是通过类似设置系统hosts的方式,先回顾下传统hosts配置方式: ``` 127.0.0.1 www.test.com # 注释 ``` 其中每一条规则占一行,并通过空格做分隔符,左边为IP,右边为域名,`#` 为注释。 ``` pattern operation ``` ### 设置hosts ### 本地替换
{ "pile_set_name": "Github" }
unit MouseActionDialog; {$mode objfpc}{$H+} interface uses Classes, Forms, Controls, ExtCtrls, StdCtrls, ButtonPanel, Spin, CheckLst, SynEditMouseCmds, LazarusIDEStrConsts, KeyMapping, IDECommands, types; var ButtonName: Array [TSynMouseButton] of String; ClickName: Array [TSynMAClickCount] of String; ButtonDirName: Array [TSynMAClickDir] of String; type { TMouseaActionDialog } TMouseaActionDialog = class(TForm) ActionBox: TComboBox; ActionLabel: TLabel; AltCheck: TCheckBox; BtnDefault: TButton; BtnLabel: TLabel; ButtonBox: TComboBox; ButtonPanel1: TButtonPanel; CaretCheck: TCheckBox; chkUpRestrict: TCheckListBox; ClickBox: TComboBox; DirCheck: TCheckBox; PaintBox1: TPaintBox; PriorLabel: TLabel; OptBox: TComboBox; CtrlCheck: TCheckBox; CapturePanel: TPanel; OptLabel: TLabel; Opt2Spin: TSpinEdit; Opt2Label: TLabel; ShiftCheck: TCheckBox; PriorSpin: TSpinEdit; procedure ActionBoxChange(Sender: TObject); procedure BtnDefaultClick(Sender: TObject); procedure ButtonBoxChange(Sender: TObject); procedure CapturePanelMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; {%H-}X, {%H-}Y: Integer); procedure DirCheckChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure PaintBox1MouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; {%H-}MousePos: TPoint; var {%H-}Handled: Boolean); private FKeyMap: TKeyCommandRelationList; procedure AddMouseCmd(const S: string); procedure FillListbox; public { public declarations } Procedure ResetInputs; Procedure ReadFromAction(MAct: TSynEditMouseAction); Procedure WriteToAction(MAct: TSynEditMouseAction); property KeyMap: TKeyCommandRelationList read FKeyMap write FKeyMap; end; function KeyMapIndexOfCommand(AKeyMap: TKeyCommandRelationList; ACmd: Word) : Integer; implementation uses Math; {$R *.lfm} const BtnToIndex: array [TSynMouseButton] of Integer = (0, 1, 2, 3, 4, 5, 6); ClickToIndex: array [ccSingle..ccAny] of Integer = (0, 1, 2, 3, 4); IndexToBtn: array [0..6] of TSynMouseButton = (mbXLeft, mbXRight, mbXMiddle, mbXExtra1, mbXExtra2, mbXWheelUp, mbXWheelDown); IndexToClick: array [0..4] of TSynMAClickCount = (ccSingle, ccDouble, ccTriple, ccQuad, ccAny); function KeyMapIndexOfCommand(AKeyMap: TKeyCommandRelationList; ACmd: Word): Integer; var i: Integer; begin for i := 0 to AKeyMap.RelationCount - 1 do if AKeyMap.Relations[i].Command = ACmd then exit(i); Result := -1; end; { MouseaActionDialog } procedure TMouseaActionDialog.AddMouseCmd(const S: string); var i: Integer; s2: String; begin i:=0; if IdentToSynMouseCmd(S, i) then begin s2 := MouseCommandName(i); if s2 = '' then s2 := s; ActionBox.Items.AddObject(s2, TObject(ptrint(i))); end; end; procedure TMouseaActionDialog.FillListbox; const cCheckSize=35; var r: TSynMAUpRestriction; s: string; i, Len: integer; begin for r := low(TSynMAUpRestriction) to high(TSynMAUpRestriction) do case r of crLastDownPos: chkUpRestrict.AddItem(synfMatchActionPosOfMouseDown, nil); crLastDownPosSameLine: chkUpRestrict.AddItem(synfMatchActionLineOfMouseDown, nil); crLastDownPosSearchAll: chkUpRestrict.AddItem(synfSearchAllActionOfMouseDown, nil); crLastDownButton: chkUpRestrict.AddItem(synfMatchActionButtonOfMouseDown, nil); crLastDownShift: chkUpRestrict.AddItem(synfMatchActionModifiersOfMouseDown, nil); crAllowFallback: chkUpRestrict.AddItem(synfContinueWithNextMouseUpAction, nil); else begin WriteStr(s, r); chkUpRestrict.AddItem(s, nil); end; end; // update scrollbar Len := 0; with chkUpRestrict do begin for i := 0 to Items.Count-1 do Len := Max(Len, Canvas.TextWidth(Items[i])+cCheckSize); ScrollWidth := Len; end; end; procedure TMouseaActionDialog.FormCreate(Sender: TObject); var mb: TSynMouseButton; cc: TSynMAClickCount; begin ButtonName[mbXLeft]:=dlgMouseOptBtnLeft; ButtonName[mbXRight]:=dlgMouseOptBtnRight; ButtonName[mbXMiddle]:=dlgMouseOptBtnMiddle; ButtonName[mbXExtra1]:=dlgMouseOptBtnExtra1; ButtonName[mbXExtra2]:=dlgMouseOptBtnExtra2; ButtonName[mbXWheelUp]:=dlgMouseOptBtnWheelUp; ButtonName[mbXWheelDown]:=dlgMouseOptBtnWheelDown; ClickName[ccSingle]:=dlgMouseOptBtn1; ClickName[ccDouble]:=dlgMouseOptBtn2; ClickName[ccTriple]:=dlgMouseOptBtn3; ClickName[ccQuad]:=dlgMouseOptBtn4; ClickName[ccAny]:=dlgMouseOptBtnAny; FillListbox; ButtonDirName[cdUp]:=lisUp; ButtonDirName[cdDown]:=lisDown; Caption := dlgMouseOptDlgTitle; CapturePanel.Caption := dlgMouseOptCapture; CapturePanel.ControlStyle := ControlStyle + [csTripleClicks, csQuadClicks]; CaretCheck.Caption := dlgMouseOptCaretMove; ActionBox.Clear; GetEditorMouseCommandValues(@AddMouseCmd); ButtonBox.Clear; for mb := low(TSynMouseButton) to high(TSynMouseButton) do ButtonBox.Items.add(ButtonName[mb]); ClickBox.Clear; for cc:= low(TSynMAClickCount) to high(TSynMAClickCount) do ClickBox.Items.add(ClickName[cc]); DirCheck.Caption := dlgMouseOptCheckUpDown; ShiftCheck.Caption := dlgMouseOptModShift; AltCheck.Caption := dlgMouseOptModAlt; CtrlCheck.Caption := dlgMouseOptModCtrl; ActionLabel.Caption := dlgMouseOptDescAction; BtnLabel.Caption := dlgMouseOptDescButton; BtnDefault.Caption := dlgMouseOptBtnModDef; PriorLabel.Caption := dlgMouseOptPriorLabel; Opt2Label.Caption := dlgMouseOptOpt2Label; end; procedure TMouseaActionDialog.ResetInputs; var r: TSynMAUpRestriction; begin ActionBox.ItemIndex := 0; ButtonBox.ItemIndex := 0; ClickBox.ItemIndex := 0; DirCheck.Checked := False; ShiftCheck.State := cbGrayed; AltCheck.State := cbGrayed; CtrlCheck.State := cbGrayed; for r := low(TSynMAUpRestriction) to high(TSynMAUpRestriction) do chkUpRestrict.Checked[ord(r)] := False; ActionBoxChange(nil); OptBox.ItemIndex := 0; end; procedure TMouseaActionDialog.BtnDefaultClick(Sender: TObject); begin ShiftCheck.State := cbGrayed; AltCheck.State := cbGrayed; CtrlCheck.State := cbGrayed; end; procedure TMouseaActionDialog.ButtonBoxChange(Sender: TObject); begin DirCheck.Enabled := not(IndexToBtn[ButtonBox.ItemIndex] in [mbXWheelUp, mbXWheelDown]); chkUpRestrict.Enabled := DirCheck.Enabled and DirCheck.Checked; end; procedure TMouseaActionDialog.ActionBoxChange(Sender: TObject); var ACmd: TSynEditorMouseCommand; i: Integer; begin OptBox.Items.Clear; ACmd := TSynEditorMouseCommand({%H-}PtrUInt(Pointer(ActionBox.items.Objects[ActionBox.ItemIndex]))); if ACmd = emcSynEditCommand then begin OptBox.Enabled := True; OptBox.Clear; for i := 0 to KeyMap.RelationCount - 1 do if (KeyMap.Relations[i].Category.Scope = IDECmdScopeSrcEdit) or (KeyMap.Relations[i].Category.Scope = IDECmdScopeSrcEditOnly) then OptBox.Items.AddObject(KeyMap.Relations[i].GetLocalizedName, TObject({%H-}Pointer(PtrUInt(KeyMap.Relations[i].Command)))); OptLabel.Caption := dlgMouseOptionsynCommand; OptBox.ItemIndex := 0; end else begin OptBox.Items.CommaText := MouseCommandConfigName(ACmd); if OptBox.Items.Count > 0 then begin OptLabel.Caption := OptBox.Items[0]; OptBox.Items.Delete(0); OptBox.Enabled := True; OptBox.ItemIndex := 0; end else begin OptLabel.Caption := ''; OptBox.Enabled := False end; end; end; procedure TMouseaActionDialog.CapturePanelMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin ButtonBox.ItemIndex := BtnToIndex[SynMouseButtonMap[Button]]; ClickBox.ItemIndex := 0; if ssDouble in Shift then ClickBox.ItemIndex := 1; if ssTriple in Shift then ClickBox.ItemIndex := 2; if ssQuad in Shift then ClickBox.ItemIndex := 3; ShiftCheck.Checked := ssShift in Shift; AltCheck.Checked := ssAlt in Shift; CtrlCheck.Checked := ssCtrl in Shift; end; procedure TMouseaActionDialog.DirCheckChange(Sender: TObject); begin chkUpRestrict.Enabled := DirCheck.Checked; end; procedure TMouseaActionDialog.PaintBox1MouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean); begin if WheelDelta > 0 then ButtonBox.ItemIndex := BtnToIndex[mbXWheelUp] else ButtonBox.ItemIndex := BtnToIndex[mbXWheelDown]; ClickBox.ItemIndex := 4; ShiftCheck.Checked := ssShift in Shift; AltCheck.Checked := ssAlt in Shift; CtrlCheck.Checked := ssCtrl in Shift; end; procedure TMouseaActionDialog.ReadFromAction(MAct: TSynEditMouseAction); var r: TSynMAUpRestriction; begin ActionBox.ItemIndex := ActionBox.Items.IndexOfObject(TObject({%H-}Pointer(PtrUInt(MAct.Command)))); ButtonBox.ItemIndex := BtnToIndex[MAct.Button]; ClickBox.ItemIndex := ClickToIndex[MAct.ClickCount]; DirCheck.Checked := MAct.ClickDir = cdUp; CaretCheck.Checked := MAct.MoveCaret; ShiftCheck.Checked := (ssShift in MAct.ShiftMask) and (ssShift in MAct.Shift); if not(ssShift in MAct.ShiftMask) then ShiftCheck.State := cbGrayed; AltCheck.Checked := (ssAlt in MAct.ShiftMask) and (ssAlt in MAct.Shift); if not(ssAlt in MAct.ShiftMask) then AltCheck.State := cbGrayed; CtrlCheck.Checked := (ssCtrl in MAct.ShiftMask) and (ssCtrl in MAct.Shift); if not(ssCtrl in MAct.ShiftMask) then CtrlCheck.State := cbGrayed; PriorSpin.Value := MAct.Priority; Opt2Spin.Value := MAct.Option2; for r := low(TSynMAUpRestriction) to high(TSynMAUpRestriction) do chkUpRestrict.Checked[ord(r)] := r in MAct.ButtonUpRestrictions; ActionBoxChange(nil); ButtonBoxChange(nil); if OptBox.Enabled then begin if MAct.Command = emcSynEditCommand then OptBox.ItemIndex := OptBox.Items.IndexOfObject(TObject({%H-}Pointer(PtrUInt(MAct.Option)))) else OptBox.ItemIndex := MAct.Option; end; end; procedure TMouseaActionDialog.WriteToAction(MAct: TSynEditMouseAction); var r: TSynMAUpRestriction; begin MAct.Command := TSynEditorMouseCommand({%H-}PtrUInt(Pointer(ActionBox.items.Objects[ActionBox.ItemIndex]))); MAct.Button := IndexToBtn[ButtonBox.ItemIndex]; MAct.ClickCount := IndexToClick[ClickBox.ItemIndex]; MAct.MoveCaret := CaretCheck.Checked; if DirCheck.Checked then MAct.ClickDir := cdUp else MAct.ClickDir := cdDown; MAct.Shift := []; MAct.ShiftMask := []; if ShiftCheck.State <> cbGrayed then MAct.ShiftMask := MAct.ShiftMask + [ssShift]; if AltCheck.State <> cbGrayed then MAct.ShiftMask := MAct.ShiftMask + [ssAlt]; if CtrlCheck.State <> cbGrayed then MAct.ShiftMask := MAct.ShiftMask + [ssCtrl]; if ShiftCheck.Checked then MAct.Shift := MAct.Shift + [ssShift]; if AltCheck.Checked then MAct.Shift := MAct.Shift + [ssAlt]; if CtrlCheck.Checked then MAct.Shift := MAct.Shift + [ssCtrl]; MAct.Priority := PriorSpin.Value; MAct.Option2 := Opt2Spin.Value; MAct.ButtonUpRestrictions := []; for r := low(TSynMAUpRestriction) to high(TSynMAUpRestriction) do if chkUpRestrict.Checked[ord(r)] then MAct.ButtonUpRestrictions := MAct.ButtonUpRestrictions + [r]; if OptBox.Enabled then begin if MAct.Command = emcSynEditCommand then begin MAct.Option := TSynEditorMouseCommandOpt({%H-}PtrUInt(Pointer(OptBox.Items.Objects[OptBox.ItemIndex]))); end else MAct.Option := OptBox.ItemIndex; end else MAct.Option := 0; end; end.
{ "pile_set_name": "Github" }
using System; using Org.BouncyCastle.Asn1; namespace Org.BouncyCastle.Asn1.Misc { public class IdeaCbcPar : Asn1Encodable { internal Asn1OctetString iv; public static IdeaCbcPar GetInstance( object o) { if (o is IdeaCbcPar) { return (IdeaCbcPar) o; } if (o is Asn1Sequence) { return new IdeaCbcPar((Asn1Sequence) o); } throw new ArgumentException("unknown object in IDEACBCPar factory"); } public IdeaCbcPar( byte[] iv) { this.iv = new DerOctetString(iv); } private IdeaCbcPar( Asn1Sequence seq) { if (seq.Count == 1) { iv = (Asn1OctetString) seq[0]; } } public byte[] GetIV() { return iv == null ? null : iv.GetOctets(); } /** * Produce an object suitable for an Asn1OutputStream. * <pre> * IDEA-CBCPar ::= Sequence { * iv OCTET STRING OPTIONAL -- exactly 8 octets * } * </pre> */ public override Asn1Object ToAsn1Object() { Asn1EncodableVector v = new Asn1EncodableVector(); if (iv != null) { v.Add(iv); } return new DerSequence(v); } } }
{ "pile_set_name": "Github" }
#!/bin/sh if [ -z "$TESTSUITE" ]; then CMDLINE=/proc/cmdline ALIASES=/etc/preseed_aliases else CMDLINE=user-params.in ALIASES=user-params.aliases fi # sed out multi-word quoted value settings for item in $(sed -e 's/[^ =]*="[^"]*[ ][^"]*"//g' \ -e "s/[^ =]*='[^']*[ ][^']*'//g" $CMDLINE); do var="${item%=*}" # Remove trailing '?' for debconf variables set with '?=' var="${var%\?}" if [ "$item" = "--" ] || [ "$item" = "---" ]; then inuser=1 collect="" elif [ "$inuser" ]; then # BOOT_IMAGE is added by syslinux if [ "$var" = "BOOT_IMAGE" ]; then continue fi # init is not generally useful to pass on if [ "$var" = init ]; then continue fi # suppress installer-specific parameters if [ "$var" = BOOT_DEBUG ] || [ "$var" = DEBIAN_FRONTEND ] || \ [ "$var" = INSTALL_MEDIA_DEV ] || [ "$var" = lowmem ] || \ [ "$var" = noshell ]; then continue fi # brltty settings shouldn't be passed since # they are already recorded in /etc/brltty.conf if [ "$var" = brltty ]; then continue fi # ks is only useful to kickseed in the first stage. if [ "$var" = ks ]; then continue fi # We don't believe that vga= is needed to display a console # any more now that we've switched to 640x400 by default, # and it breaks suspend/resume. People can always type it in # again at the installed boot loader if need be. if [ "$var" = vga ]; then continue fi # Sometimes used on the live CD for debugging initramfs-tools. if [ "$var" = break ]; then continue fi # Skip live-CD-specific crud if [ "${var%-ubiquity}" != "$var" ] || \ [ "$var" = noninteractive ]; then continue fi # Skip debconf variables varnoslash="${var##*/*}" if [ "$varnoslash" = "" ]; then continue fi # Skip module-specific variables # varnodot="${var##*.*}" # if [ "$varnodot" = "" ]; then # continue # fi # Skip preseed aliases if [ -e "$ALIASES" ] && \ grep -q "^$var[[:space:]]" "$ALIASES"; then continue fi if [ -z "$collect" ]; then collect="$item" else collect="$collect $item" fi fi done if [ -z "$TESTSUITE" ]; then # Include default parameters RET=`debconf-get debian-installer/add-kernel-opts || true` if [ "$RET" ]; then collect="$collect $RET" fi fi for word in $collect; do echo "$word" done
{ "pile_set_name": "Github" }
'use strict' import React from 'react' import Sortable from 'sortablejs' class Favorite extends React.PureComponent { constructor() { super() this.state = { activeKey: null } this._updateSortableKey() } _updateSortableKey() { this.sortableKey = `sortable-${Math.round(Math.random() * 10000)}` } _bindSortable() { const {reorderFavorites} = this.props this.sortable = Sortable.create(this.refs.sortable, { animation: 100, onStart: evt => { this.nextSibling = evt.item.nextElementSibling }, onAdd: () => { this._updateSortableKey() }, onUpdate: evt => { this._updateSortableKey() reorderFavorites({from: evt.oldIndex, to: evt.newIndex}) } }) } componentDidMount() { this._bindSortable() } componentDidUpdate() { this._bindSortable() } onClick(index, evt) { evt.preventDefault() this.selectIndex(index) } onDoubleClick(index, evt) { evt.preventDefault() this.selectIndex(index, true) } selectIndex(index, connect) { this.select(index === -1 ? null : this.props.favorites.get(index), connect) } select(favorite, connect) { const activeKey = favorite ? favorite.get('key') : null this.setState({activeKey}) if (connect) { this.props.onRequireConnecting(activeKey) } else { this.props.onSelect(activeKey) } } render() { return (<div style={{flex: 1, display: 'flex', flexDirection: 'column', overflowY: 'hidden'}}> <nav className="nav-group"> <h5 className="nav-group-title"/> <a className={'nav-group-item' + (this.state.activeKey ? '' : ' active')} onClick={this.onClick.bind(this, -1)} onDoubleClick={this.onDoubleClick.bind(this, -1)} > <span className="icon icon-flash"/> QUICK CONNECT </a> <h5 className="nav-group-title">FAVORITES</h5> <div ref="sortable" key={this.sortableKey}>{ this.props.favorites.map((favorite, index) => { return (<a key={favorite.get('key')} className={'nav-group-item' + (favorite.get('key') === this.state.activeKey ? ' active' : '')} onClick={this.onClick.bind(this, index)} onDoubleClick={this.onDoubleClick.bind(this, index)} > <span className="icon icon-home"/> <span>{favorite.get('name')}</span> </a>) }) }</div> </nav> <footer className="toolbar toolbar-footer"> <button onClick={() => { this.props.createFavorite() // TODO: auto select // this.select(favorite); }} >+</button> <button onClick={ () => { const key = this.state.activeKey if (!key) { return } showModal({ title: 'Delete the bookmark?', button: 'Delete', content: 'Are you sure you want to delete the selected bookmark? This action cannot be undone.' }).then(() => { const index = this.props.favorites.findIndex(favorite => key === favorite.get('key')) this.props.removeFavorite(key) this.selectIndex(index - 1) }) } } >-</button> </footer> </div>) } componentWillUnmount() { this.sortable.destroy() } } export default Favorite
{ "pile_set_name": "Github" }
#!/bin/bash # $Id: //depot/cloud/rpms/nflx-webadmin-gcviz/root/apps/apache/htdocs/AdminGCViz/index#2 $ # $DateTime: 2013/05/15 18:34:23 $ # $Author: mooreb $ # $Change: 1838706 $ cd `dirname $0` prog=`basename $0` NFENV=/etc/profile.d/netflix_environment.sh if [ -f ${NFENV} ]; then . ${NFENV} NETFLIX_VMS_EVENTS=checked else NFENV="" fi cat <<EndOfHeader Content-Type: text/html <html> <head> <title>AdminGCViz</title> </head> <body> EndOfHeader cat <<EndOfGenerate Generate a GC visualization report now <form action="generate" method="POST"> <input type="checkbox" name="jmap_histo_live" value="on" checked> jmap -histo:live<br> <input type="checkbox" name="vms_refresh_events" value="on" ${NETFLIX_VMS_EVENTS}> parse catalina logs looking for netflix VMS events<br> <input type="submit" value="Generate GCViz report"> </form> EndOfGenerate echo Look at previous reports echo "<ul>" for f in `find /mnt/logs/gc-reports -type f -name "*.png" | LANG=C sort -rn`; do u=`echo ${f} | sed 's|/mnt/logs/gc-reports/||'` echo "<li> <a href=\"/AdminGCVizImages/${u}\">${f}</a>" done echo "</ul>" cat <<EndOfFooter </body> </html> EndOfFooter
{ "pile_set_name": "Github" }
require File.expand_path(File.dirname(__FILE__) + '/spec_helper') module GovKit::FollowTheMoney describe GovKit::FollowTheMoney do before(:all) do unless FakeWeb.allow_net_connect? base_uri = GovKit::FollowTheMoneyResource.base_uri.gsub(/\./, '\.') urls = [ ['/base_level\.industries\.list\.php\?.*page=0', 'business-page0.response'], ['/base_level\.industries\.list\.php\?.*page=1', 'business-page1.response'], ['/candidates\.contributions\.php\?imsp_candidate_id=111933', 'contribution.response'], ['/candidates\.contributions\.php\?imsp_candidate_id=0', 'unauthorized.response'], ] urls.each do |u| FakeWeb.register_uri(:get, %r|#{base_uri}#{u[0]}|, :response => File.join(FIXTURES_DIR, 'follow_the_money', u[1])) end end end it "should have the base uri set properly" do [Business, Contribution].each do |klass| klass.base_uri.should == "http://api.followthemoney.org" end end it "should raise NotAuthorized if the api key is not valid" do api_key = GovKit.configuration.ftm_apikey GovKit.configuration.ftm_apikey = nil lambda do @contribution = Contribution.find(0) end.should raise_error(GovKit::NotAuthorized) @contribution.should be_nil GovKit.configuration.ftm_apikey = api_key end describe Business do it "should get a list of industries" do @businesses = Business.list @businesses.should be_an_instance_of(Array) @businesses.each do |b| b.should be_an_instance_of(Business) end end end describe Contribution do it "should get a list of campaign contributions for a given person" do pending 'This API call is restricted' @contributions = Contribution.find(111933) @contributions.should be_an_instance_of(Array) @contributions.each do |c| c.should be_an_instance_of(Contribution) end end end end end
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CFBundleDevelopmentRegion</key> <string>English</string> <key>CFBundleExecutable</key> <string>SPMySQL</string> <key>CFBundleIdentifier</key> <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundlePackageType</key> <string>FMWK</string> <key>CFBundleShortVersionString</key> <string>1.0</string> <key>CFBundleSignature</key> <string>SPDT</string> <key>CFBundleVersion</key> <string>1</string> </dict> </plist>
{ "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 cache import ( "errors" "sync" "k8s.io/apimachinery/pkg/util/sets" ) // PopProcessFunc is passed to Pop() method of Queue interface. // It is supposed to process the element popped from the queue. type PopProcessFunc func(interface{}) error // ErrRequeue may be returned by a PopProcessFunc to safely requeue // the current item. The value of Err will be returned from Pop. type ErrRequeue struct { // Err is returned by the Pop function Err error } var FIFOClosedError error = errors.New("DeltaFIFO: manipulating with closed queue") func (e ErrRequeue) Error() string { if e.Err == nil { return "the popped item should be requeued without returning an error" } return e.Err.Error() } // Queue is exactly like a Store, but has a Pop() method too. type Queue interface { Store // Pop blocks until it has something to process. // It returns the object that was process and the result of processing. // The PopProcessFunc may return an ErrRequeue{...} to indicate the item // should be requeued before releasing the lock on the queue. Pop(PopProcessFunc) (interface{}, error) // AddIfNotPresent adds a value previously // returned by Pop back into the queue as long // as nothing else (presumably more recent) // has since been added. AddIfNotPresent(interface{}) error // HasSynced returns true if the first batch of items has been popped HasSynced() bool // Close queue Close() } // Helper function for popping from Queue. // WARNING: Do NOT use this function in non-test code to avoid races // unless you really really really really know what you are doing. func Pop(queue Queue) interface{} { var result interface{} queue.Pop(func(obj interface{}) error { result = obj return nil }) return result } // FIFO receives adds and updates from a Reflector, and puts them in a queue for // FIFO order processing. If multiple adds/updates of a single item happen while // an item is in the queue before it has been processed, it will only be // processed once, and when it is processed, the most recent version will be // processed. This can't be done with a channel. // // FIFO solves this use case: // * You want to process every object (exactly) once. // * You want to process the most recent version of the object when you process it. // * You do not want to process deleted objects, they should be removed from the queue. // * You do not want to periodically reprocess objects. // Compare with DeltaFIFO for other use cases. type FIFO struct { lock sync.RWMutex cond sync.Cond // We depend on the property that items in the set are in the queue and vice versa. items map[string]interface{} queue []string // populated is true if the first batch of items inserted by Replace() has been populated // or Delete/Add/Update was called first. populated bool // initialPopulationCount is the number of items inserted by the first call of Replace() initialPopulationCount int // keyFunc is used to make the key used for queued item insertion and retrieval, and // should be deterministic. keyFunc KeyFunc // Indication the queue is closed. // Used to indicate a queue is closed so a control loop can exit when a queue is empty. // Currently, not used to gate any of CRED operations. closed bool closedLock sync.Mutex } var ( _ = Queue(&FIFO{}) // FIFO is a Queue ) // Close the queue. func (f *FIFO) Close() { f.closedLock.Lock() defer f.closedLock.Unlock() f.closed = true f.cond.Broadcast() } // Return true if an Add/Update/Delete/AddIfNotPresent are called first, // or an Update called first but the first batch of items inserted by Replace() has been popped func (f *FIFO) HasSynced() bool { f.lock.Lock() defer f.lock.Unlock() return f.populated && f.initialPopulationCount == 0 } // Add inserts an item, and puts it in the queue. The item is only enqueued // if it doesn't already exist in the set. func (f *FIFO) Add(obj interface{}) error { id, err := f.keyFunc(obj) if err != nil { return KeyError{obj, err} } f.lock.Lock() defer f.lock.Unlock() f.populated = true if _, exists := f.items[id]; !exists { f.queue = append(f.queue, id) } f.items[id] = obj f.cond.Broadcast() return nil } // AddIfNotPresent inserts an item, and puts it in the queue. If the item is already // present in the set, it is neither enqueued nor added to the set. // // This is useful in a single producer/consumer scenario so that the consumer can // safely retry items without contending with the producer and potentially enqueueing // stale items. func (f *FIFO) AddIfNotPresent(obj interface{}) error { id, err := f.keyFunc(obj) if err != nil { return KeyError{obj, err} } f.lock.Lock() defer f.lock.Unlock() f.addIfNotPresent(id, obj) return nil } // addIfNotPresent assumes the fifo lock is already held and adds the provided // item to the queue under id if it does not already exist. func (f *FIFO) addIfNotPresent(id string, obj interface{}) { f.populated = true if _, exists := f.items[id]; exists { return } f.queue = append(f.queue, id) f.items[id] = obj f.cond.Broadcast() } // Update is the same as Add in this implementation. func (f *FIFO) Update(obj interface{}) error { return f.Add(obj) } // Delete removes an item. It doesn't add it to the queue, because // this implementation assumes the consumer only cares about the objects, // not the order in which they were created/added. func (f *FIFO) Delete(obj interface{}) error { id, err := f.keyFunc(obj) if err != nil { return KeyError{obj, err} } f.lock.Lock() defer f.lock.Unlock() f.populated = true delete(f.items, id) return err } // List returns a list of all the items. func (f *FIFO) List() []interface{} { f.lock.RLock() defer f.lock.RUnlock() list := make([]interface{}, 0, len(f.items)) for _, item := range f.items { list = append(list, item) } return list } // ListKeys returns a list of all the keys of the objects currently // in the FIFO. func (f *FIFO) ListKeys() []string { f.lock.RLock() defer f.lock.RUnlock() list := make([]string, 0, len(f.items)) for key := range f.items { list = append(list, key) } return list } // Get returns the requested item, or sets exists=false. func (f *FIFO) Get(obj interface{}) (item interface{}, exists bool, err error) { key, err := f.keyFunc(obj) if err != nil { return nil, false, KeyError{obj, err} } return f.GetByKey(key) } // GetByKey returns the requested item, or sets exists=false. func (f *FIFO) GetByKey(key string) (item interface{}, exists bool, err error) { f.lock.RLock() defer f.lock.RUnlock() item, exists = f.items[key] return item, exists, nil } // Checks if the queue is closed func (f *FIFO) IsClosed() bool { f.closedLock.Lock() defer f.closedLock.Unlock() if f.closed { return true } return false } // Pop waits until an item is ready and processes it. If multiple items are // ready, they are returned in the order in which they were added/updated. // The item is removed from the queue (and the store) before it is processed, // so if you don't successfully process it, it should be added back with // AddIfNotPresent(). process function is called under lock, so it is safe // update data structures in it that need to be in sync with the queue. func (f *FIFO) Pop(process PopProcessFunc) (interface{}, error) { f.lock.Lock() defer f.lock.Unlock() for { for len(f.queue) == 0 { // When the queue is empty, invocation of Pop() is blocked until new item is enqueued. // When Close() is called, the f.closed is set and the condition is broadcasted. // Which causes this loop to continue and return from the Pop(). if f.IsClosed() { return nil, FIFOClosedError } f.cond.Wait() } id := f.queue[0] f.queue = f.queue[1:] if f.initialPopulationCount > 0 { f.initialPopulationCount-- } item, ok := f.items[id] if !ok { // Item may have been deleted subsequently. continue } delete(f.items, id) err := process(item) if e, ok := err.(ErrRequeue); ok { f.addIfNotPresent(id, item) err = e.Err } return item, err } } // Replace will delete the contents of 'f', using instead the given map. // 'f' takes ownership of the map, you should not reference the map again // after calling this function. f's queue is reset, too; upon return, it // will contain the items in the map, in no particular order. func (f *FIFO) Replace(list []interface{}, resourceVersion string) error { items := map[string]interface{}{} for _, item := range list { key, err := f.keyFunc(item) if err != nil { return KeyError{item, err} } items[key] = item } f.lock.Lock() defer f.lock.Unlock() if !f.populated { f.populated = true f.initialPopulationCount = len(items) } f.items = items f.queue = f.queue[:0] for id := range items { f.queue = append(f.queue, id) } if len(f.queue) > 0 { f.cond.Broadcast() } return nil } // Resync will touch all objects to put them into the processing queue func (f *FIFO) Resync() error { f.lock.Lock() defer f.lock.Unlock() inQueue := sets.NewString() for _, id := range f.queue { inQueue.Insert(id) } for id := range f.items { if !inQueue.Has(id) { f.queue = append(f.queue, id) } } if len(f.queue) > 0 { f.cond.Broadcast() } return nil } // NewFIFO returns a Store which can be used to queue up items to // process. func NewFIFO(keyFunc KeyFunc) *FIFO { f := &FIFO{ items: map[string]interface{}{}, queue: []string{}, keyFunc: keyFunc, } f.cond.L = &f.lock return f }
{ "pile_set_name": "Github" }
// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build arm64,darwin package unix import ( "syscall" "unsafe" ) func Getpagesize() int { return 16384 } 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 } func NsecToTimeval(nsec int64) (tv Timeval) { nsec += 999 // round up to microsecond tv.Usec = int32(nsec % 1e9 / 1e3) tv.Sec = int64(nsec / 1e9) return } //sysnb gettimeofday(tp *Timeval) (sec int64, usec int32, err error) func Gettimeofday(tv *Timeval) (err error) { // The tv passed to gettimeofday must be non-nil // but is otherwise unused. The answers come back // in the two registers. sec, usec, err := gettimeofday(tv) tv.Sec = sec tv.Usec = usec return err } func SetKevent(k *Kevent_t, fd, mode, flags int) { k.Ident = uint64(fd) k.Filter = int16(mode) k.Flags = uint16(flags) } func (iov *Iovec) SetLen(length int) { iov.Len = uint64(length) } func (msghdr *Msghdr) SetControllen(length int) { msghdr.Controllen = uint32(length) } func (cmsg *Cmsghdr) SetLen(length int) { cmsg.Len = uint32(length) } func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { var length = uint64(count) _, _, e1 := Syscall6(SYS_SENDFILE, uintptr(infd), uintptr(outfd), uintptr(*offset), uintptr(unsafe.Pointer(&length)), 0, 0) written = int(length) if e1 != 0 { err = e1 } return } func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) // sic // SYS___SYSCTL is used by syscall_bsd.go for all BSDs, but in modern versions // of darwin/arm64 the syscall is called sysctl instead of __sysctl. const SYS___SYSCTL = SYS_SYSCTL
{ "pile_set_name": "Github" }
<!DOCTYPE suite SYSTEM "http://beust.com/testng/testng-1.0.dtd" > <suite name="BigBlueButton Desktop Sharing Test Suite"> <test name="Conference tests"> <!--groups> <run> <exclude name="broken"/> </run> </groups--> <packages> <package name="org.bigbluebutton.deskshare.server.recorder"/> </packages> </test> </suite>
{ "pile_set_name": "Github" }
/* * Copyright (c) 2011, 2014, 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. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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.webkit; import java.net.URL; public interface PolicyClient { public boolean permitNavigateAction(long sourceID, URL url); public boolean permitRedirectAction(long sourceID, URL url); public boolean permitAcceptResourceAction(long sourceID, URL url); public boolean permitSubmitDataAction(long sourceID, URL url, String httpMethod); public boolean permitResubmitDataAction(long sourceID, URL url, String httpMethod); public boolean permitEnableScriptsAction(long sourceID, URL url); public boolean permitNewPageAction(long sourceID, URL url); public boolean permitClosePageAction(long sourceID); }
{ "pile_set_name": "Github" }
// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore package main // This program generates tables.go: // go run maketables.go | gofmt > tables.go // TODO: Emoji extensions? // https://www.unicode.org/faq/emoji_dingbats.html // https://www.unicode.org/Public/UNIDATA/EmojiSources.txt import ( "bufio" "fmt" "log" "net/http" "sort" "strings" ) type entry struct { jisCode, table int } func main() { fmt.Printf("// generated by go run maketables.go; DO NOT EDIT\n\n") fmt.Printf("// Package japanese provides Japanese encodings such as EUC-JP and Shift JIS.\n") fmt.Printf(`package japanese // import "golang.org/x/text/encoding/japanese"` + "\n\n") reverse := [65536]entry{} for i := range reverse { reverse[i].table = -1 } tables := []struct { url string name string }{ {"http://encoding.spec.whatwg.org/index-jis0208.txt", "0208"}, {"http://encoding.spec.whatwg.org/index-jis0212.txt", "0212"}, } for i, table := range tables { res, err := http.Get(table.url) if err != nil { log.Fatalf("%q: Get: %v", table.url, err) } defer res.Body.Close() mapping := [65536]uint16{} scanner := bufio.NewScanner(res.Body) for scanner.Scan() { s := strings.TrimSpace(scanner.Text()) if s == "" || s[0] == '#' { continue } x, y := 0, uint16(0) if _, err := fmt.Sscanf(s, "%d 0x%x", &x, &y); err != nil { log.Fatalf("%q: could not parse %q", table.url, s) } if x < 0 || 120*94 <= x { log.Fatalf("%q: JIS code %d is out of range", table.url, x) } mapping[x] = y if reverse[y].table == -1 { reverse[y] = entry{jisCode: x, table: i} } } if err := scanner.Err(); err != nil { log.Fatalf("%q: scanner error: %v", table.url, err) } fmt.Printf("// jis%sDecode is the decoding table from JIS %s code to Unicode.\n// It is defined at %s\n", table.name, table.name, table.url) fmt.Printf("var jis%sDecode = [...]uint16{\n", table.name) for i, m := range mapping { if m != 0 { fmt.Printf("\t%d: 0x%04X,\n", i, m) } } fmt.Printf("}\n\n") } // Any run of at least separation continuous zero entries in the reverse map will // be a separate encode table. const separation = 1024 intervals := []interval(nil) low, high := -1, -1 for i, v := range reverse { if v.table == -1 { continue } if low < 0 { low = i } else if i-high >= separation { if high >= 0 { intervals = append(intervals, interval{low, high}) } low = i } high = i + 1 } if high >= 0 { intervals = append(intervals, interval{low, high}) } sort.Sort(byDecreasingLength(intervals)) fmt.Printf("const (\n") fmt.Printf("\tjis0208 = 1\n") fmt.Printf("\tjis0212 = 2\n") fmt.Printf("\tcodeMask = 0x7f\n") fmt.Printf("\tcodeShift = 7\n") fmt.Printf("\ttableShift = 14\n") fmt.Printf(")\n\n") fmt.Printf("const numEncodeTables = %d\n\n", len(intervals)) fmt.Printf("// encodeX are the encoding tables from Unicode to JIS code,\n") fmt.Printf("// sorted by decreasing length.\n") for i, v := range intervals { fmt.Printf("// encode%d: %5d entries for runes in [%5d, %5d).\n", i, v.len(), v.low, v.high) } fmt.Printf("//\n") fmt.Printf("// The high two bits of the value record whether the JIS code comes from the\n") fmt.Printf("// JIS0208 table (high bits == 1) or the JIS0212 table (high bits == 2).\n") fmt.Printf("// The low 14 bits are two 7-bit unsigned integers j1 and j2 that form the\n") fmt.Printf("// JIS code (94*j1 + j2) within that table.\n") fmt.Printf("\n") for i, v := range intervals { fmt.Printf("const encode%dLow, encode%dHigh = %d, %d\n\n", i, i, v.low, v.high) fmt.Printf("var encode%d = [...]uint16{\n", i) for j := v.low; j < v.high; j++ { x := reverse[j] if x.table == -1 { continue } fmt.Printf("\t%d - %d: jis%s<<14 | 0x%02X<<7 | 0x%02X,\n", j, v.low, tables[x.table].name, x.jisCode/94, x.jisCode%94) } fmt.Printf("}\n\n") } } // interval is a half-open interval [low, high). type interval struct { low, high int } func (i interval) len() int { return i.high - i.low } // byDecreasingLength sorts intervals by decreasing length. type byDecreasingLength []interval func (b byDecreasingLength) Len() int { return len(b) } func (b byDecreasingLength) Less(i, j int) bool { return b[i].len() > b[j].len() } func (b byDecreasingLength) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
{ "pile_set_name": "Github" }
Car -1 -1 -10 626 180 684 221 1.46 1.62 4.22 1.66 1.76 28.26 -1.67 1.00 Car -1 -1 -10 793 184 1070 286 1.64 1.65 4.25 5.55 1.86 12.82 -0.11 0.99 Car -1 -1 -10 1016 196 1550 379 1.51 1.59 3.63 6.15 1.76 7.00 0.04 0.99 Car -1 -1 -10 874 184 1238 315 1.59 1.61 3.93 5.78 1.76 9.74 3.13 0.99 Car -1 -1 -10 306 180 455 232 1.52 1.61 4.10 -7.06 1.78 22.33 -3.14 0.98 Car -1 -1 -10 -29 145 313 295 2.10 1.73 4.10 -7.01 1.71 11.09 -0.06 0.98 Car -1 -1 -10 358 177 482 224 1.58 1.61 3.94 -6.71 1.77 25.57 -3.04 0.74 Car -1 -1 -10 609 177 645 204 1.54 1.60 3.72 0.96 1.82 43.14 -1.71 0.58 Car -1 -1 -10 1139 179 1347 353 1.53 1.51 3.44 7.12 1.63 8.27 2.29 0.58 Car -1 -1 -10 466 171 501 202 1.52 1.60 3.85 -6.48 1.46 37.16 -1.69 0.11 Car -1 -1 -10 483 176 517 199 1.52 1.59 3.73 -7.84 1.81 51.82 1.67 0.04
{ "pile_set_name": "Github" }
// // SerialDisposable.swift // RxSwift // // Created by Krunoslav Zaher on 3/12/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // /// Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. public final class SerialDisposable : DisposeBase, Cancelable { private var _lock = SpinLock() // state private var _current = nil as Disposable? private var _isDisposed = false /// - returns: Was resource disposed. public var isDisposed: Bool { return _isDisposed } /// Initializes a new instance of the `SerialDisposable`. override public init() { super.init() } /** Gets or sets the underlying disposable. Assigning this property disposes the previous disposable object. If the `SerialDisposable` has already been disposed, assignment to this property causes immediate disposal of the given disposable object. */ public var disposable: Disposable { get { return _lock.calculateLocked { return self.disposable } } set (newDisposable) { let disposable: Disposable? = _lock.calculateLocked { if _isDisposed { return newDisposable } else { let toDispose = _current _current = newDisposable return toDispose } } if let disposable = disposable { disposable.dispose() } } } /// Disposes the underlying disposable as well as all future replacements. public func dispose() { _dispose()?.dispose() } private func _dispose() -> Disposable? { _lock.lock(); defer { _lock.unlock() } if _isDisposed { return nil } else { _isDisposed = true let current = _current _current = nil return current } } }
{ "pile_set_name": "Github" }
<?php namespace WPGraphQL\Type\Enum; use WPGraphQL\Type\WPEnumType; class PostStatusEnum { public static function register_type() { $post_status_enum_values = [ 'name' => 'PUBLISH', 'value' => 'publish', ]; $post_stati = get_post_stati(); if ( ! empty( $post_stati ) && is_array( $post_stati ) ) { /** * Reset the array */ $post_status_enum_values = []; /** * Loop through the post_stati */ foreach ( $post_stati as $status ) { $post_status_enum_values[ WPEnumType::get_safe_name( $status ) ] = [ 'description' => sprintf( __( 'Objects with the %1$s status', 'wp-graphql' ), $status ), 'value' => $status, ]; } } register_graphql_enum_type( 'PostStatusEnum', [ 'description' => __( 'The status of the object.', 'wp-graphql' ), 'values' => $post_status_enum_values, ] ); } }
{ "pile_set_name": "Github" }
// Copyright (c) 2014-2020 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/ #ifndef TAO_PEGTL_INTERNAL_SEQ_HPP #define TAO_PEGTL_INTERNAL_SEQ_HPP #include "../config.hpp" #include "enable_control.hpp" #include "success.hpp" #include "../apply_mode.hpp" #include "../rewind_mode.hpp" #include "../type_list.hpp" namespace TAO_PEGTL_NAMESPACE::internal { template< typename... Rules > struct seq; template<> struct seq<> : success {}; template< typename... Rules > struct seq { using rule_t = seq; using subs_t = type_list< Rules... >; template< apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename ParseInput, typename... States > [[nodiscard]] static bool match( ParseInput& in, States&&... st ) { if constexpr( sizeof...( Rules ) == 1 ) { return Control< Rules... >::template match< A, M, Action, Control >( in, st... ); } else { auto m = in.template mark< M >(); using m_t = decltype( m ); return m( ( Control< Rules >::template match< A, m_t::next_rewind_mode, Action, Control >( in, st... ) && ... ) ); } } }; template< typename... Rules > inline constexpr bool enable_control< seq< Rules... > > = false; } // namespace TAO_PEGTL_NAMESPACE::internal #endif
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="PullToRefresh"> <!-- A drawable to use as the background of the Refreshable View --> <attr name="ptrRefreshableViewBackground" format="reference|color" /> <!-- A drawable to use as the background of the Header and Footer Loading Views --> <attr name="ptrHeaderBackground" format="reference|color" /> <!-- Text Color of the Header and Footer Loading Views --> <attr name="ptrHeaderTextColor" format="reference|color" /> <!-- Text Color of the Header and Footer Loading Views Sub Header --> <attr name="ptrHeaderSubTextColor" format="reference|color" /> <!-- Mode of Pull-to-Refresh that should be used --> <attr name="ptrMode"> <flag name="disabled" value="0x0" /> <flag name="pullFromStart" value="0x1" /> <flag name="pullFromEnd" value="0x2" /> <flag name="both" value="0x3" /> <flag name="manualOnly" value="0x4" /> <!-- These last two are depreacted --> <flag name="pullDownFromTop" value="0x1" /> <flag name="pullUpFromBottom" value="0x2" /> </attr> <!-- Whether the Indicator overlay(s) should be used --> <attr name="ptrShowIndicator" format="reference|boolean" /> <!-- Drawable to use as Loading Indicator. Changes both Header and Footer. --> <attr name="ptrDrawable" format="reference" /> <!-- Drawable to use as Loading Indicator in the Header View. Overrides value set in ptrDrawable. --> <attr name="ptrDrawableStart" format="reference" /> <!-- Drawable to use as Loading Indicator in the Footer View. Overrides value set in ptrDrawable. --> <attr name="ptrDrawableEnd" format="reference" /> <!-- Whether Android's built-in Over Scroll should be utilised for Pull-to-Refresh. --> <attr name="ptrOverScroll" format="reference|boolean" /> <!-- Base text color, typeface, size, and style for Header and Footer Loading Views --> <attr name="ptrHeaderTextAppearance" format="reference" /> <!-- Base text color, typeface, size, and style for Header and Footer Loading Views Sub Header --> <attr name="ptrSubHeaderTextAppearance" format="reference" /> <!-- Style of Animation should be used displayed when pulling. --> <attr name="ptrAnimationStyle"> <flag name="rotate" value="0x0" /> <flag name="flip" value="0x1" /> </attr> <!-- Whether the user can scroll while the View is Refreshing --> <attr name="ptrScrollingWhileRefreshingEnabled" format="reference|boolean" /> <!-- Whether PullToRefreshListView has it's extras enabled. This allows the user to be able to scroll while refreshing, and behaves better. It acheives this by adding Header and/or Footer Views to the ListView. --> <attr name="ptrListViewExtrasEnabled" format="reference|boolean" /> <!-- Whether the Drawable should be continually rotated as you pull. This only takes effect when using the 'Rotate' Animation Style. --> <attr name="ptrRotateDrawableWhilePulling" format="reference|boolean" /> <!-- BELOW HERE ARE DEPRECEATED. DO NOT USE. --> <attr name="ptrAdapterViewBackground" format="reference|color" /> <attr name="ptrDrawableTop" format="reference" /> <attr name="ptrDrawableBottom" format="reference" /> </declare-styleable> </resources>
{ "pile_set_name": "Github" }
module golang.org/x/lint require golang.org/x/tools v0.0.0-20190311212946-11955173bddd
{ "pile_set_name": "Github" }
/* * Copyright (C) 2017 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once namespace WTF { template<typename ContainerType, typename ForEachFunction> void forEach(ContainerType&& container, ForEachFunction forEachFunction) { for (auto& value : container) forEachFunction(value); } template<typename ContainerType, typename AnyOfFunction> bool anyOf(ContainerType&& container, AnyOfFunction anyOfFunction) { for (auto& value : container) { if (anyOfFunction(value)) return true; } return false; } template<typename ContainerType, typename AllOfFunction> bool allOf(ContainerType&& container, AllOfFunction allOfFunction) { for (auto& value : container) { if (!allOfFunction(value)) return false; } return true; } }
{ "pile_set_name": "Github" }
#!/usr/bin/perl # Copyright (C) Intel, Inc. # (C) Sergey Kandaurov # (C) Nginx, Inc. # Tests for HTTP/2 protocol with ssl. ############################################################################### use warnings; use strict; use Test::More; BEGIN { use FindBin; chdir($FindBin::Bin); } use lib 'lib'; use Test::Nginx; use Test::Nginx::HTTP2; ############################################################################### select STDERR; $| = 1; select STDOUT; $| = 1; eval { require IO::Socket::SSL; }; plan(skip_all => 'IO::Socket::SSL not installed') if $@; eval { IO::Socket::SSL::SSL_VERIFY_NONE(); }; plan(skip_all => 'IO::Socket::SSL too old') if $@; my $t = Test::Nginx->new()->has(qw/http http_ssl http_v2 rewrite/) ->has_daemon('openssl')->plan(8); $t->write_file_expand('nginx.conf', <<'EOF'); %%TEST_GLOBALS%% daemon off; events { } http { %%TEST_GLOBALS_HTTP%% server { listen 127.0.0.1:8080 http2 ssl %%SSL_ASYNCH%%; server_name localhost; ssl_certificate_key localhost.key; ssl_certificate localhost.crt; location /h2 { return 200 $http2; } location /sp { return 200 $server_protocol; } location /scheme { return 200 $scheme; } location /https { return 200 $https; } } } EOF $t->write_file('openssl.conf', <<EOF); [ req ] default_bits = 2048 encrypt_key = no distinguished_name = req_distinguished_name [ req_distinguished_name ] EOF my $d = $t->testdir(); foreach my $name ('localhost') { system('openssl req -x509 -new ' . "-config $d/openssl.conf -subj /CN=$name/ " . "-out $d/$name.crt -keyout $d/$name.key " . ">>$d/openssl.out 2>&1") == 0 or die "Can't create certificate for $name: $!\n"; } open OLDERR, ">&", \*STDERR; close STDERR; $t->run(); open STDERR, ">&", \*OLDERR; ############################################################################### my ($s, $sid, $frames, $frame); my $has_npn = eval { Test::Nginx::HTTP2::new_socket(port(8080), SSL => 1, npn => 'h2')->next_proto_negotiated() }; my $has_alpn = eval { Test::Nginx::HTTP2::new_socket(port(8080), SSL => 1, alpn => 'h2')->alpn_selected() }; # SSL/TLS connection, NPN SKIP: { skip 'OpenSSL NPN support required', 1 unless $has_npn; $s = Test::Nginx::HTTP2->new(port(8080), SSL => 1, npn => 'h2'); $sid = $s->new_stream({ path => '/h2' }); $frames = $s->read(all => [{ sid => $sid, fin => 1 }]); ($frame) = grep { $_->{type} eq "DATA" } @$frames; is($frame->{data}, 'h2', 'http variable - npn'); } # SSL/TLS connection, ALPN SKIP: { skip 'OpenSSL ALPN support required', 1 unless $has_alpn; $s = Test::Nginx::HTTP2->new(port(8080), SSL => 1, alpn => 'h2'); $sid = $s->new_stream({ path => '/h2' }); $frames = $s->read(all => [{ sid => $sid, fin => 1 }]); ($frame) = grep { $_->{type} eq "DATA" } @$frames; is($frame->{data}, 'h2', 'http variable - alpn'); } # $server_protocol - SSL/TLS connection, NPN SKIP: { skip 'OpenSSL NPN support required', 1 unless $has_npn; $s = Test::Nginx::HTTP2->new(port(8080), SSL => 1, npn => 'h2'); $sid = $s->new_stream({ path => '/sp' }); $frames = $s->read(all => [{ sid => $sid, fin => 1 }]); ($frame) = grep { $_->{type} eq "DATA" } @$frames; is($frame->{data}, 'HTTP/2.0', 'server_protocol variable - npn'); } # $server_protocol - SSL/TLS connection, ALPN SKIP: { skip 'OpenSSL ALPN support required', 1 unless $has_alpn; $s = Test::Nginx::HTTP2->new(port(8080), SSL => 1, alpn => 'h2'); $sid = $s->new_stream({ path => '/sp' }); $frames = $s->read(all => [{ sid => $sid, fin => 1 }]); ($frame) = grep { $_->{type} eq "DATA" } @$frames; is($frame->{data}, 'HTTP/2.0', 'server_protocol variable - alpn'); } # $scheme - SSL/TLS connection, NPN SKIP: { skip 'OpenSSL NPN support required', 1 unless $has_npn; $s = Test::Nginx::HTTP2->new(port(8080), SSL => 1, npn => 'h2'); $sid = $s->new_stream({ path => '/scheme' }); $frames = $s->read(all => [{ sid => $sid, fin => 1 }]); ($frame) = grep { $_->{type} eq "DATA" } @$frames; is($frame->{data}, 'https', 'scheme variable - npn'); } # $scheme - SSL/TLS connection, ALPN SKIP: { skip 'OpenSSL ALPN support required', 1 unless $has_alpn; $s = Test::Nginx::HTTP2->new(port(8080), SSL => 1, alpn => 'h2'); $sid = $s->new_stream({ path => '/scheme' }); $frames = $s->read(all => [{ sid => $sid, fin => 1 }]); ($frame) = grep { $_->{type} eq "DATA" } @$frames; is($frame->{data}, 'https', 'scheme variable - alpn'); } # $https - SSL/TLS connection, NPN SKIP: { skip 'OpenSSL NPN support required', 1 unless $has_npn; $s = Test::Nginx::HTTP2->new(port(8080), SSL => 1, npn => 'h2'); $sid = $s->new_stream({ path => '/https' }); $frames = $s->read(all => [{ sid => $sid, fin => 1 }]); ($frame) = grep { $_->{type} eq "DATA" } @$frames; is($frame->{data}, 'on', 'https variable - npn'); } # $https - SSL/TLS connection, ALPN SKIP: { skip 'OpenSSL ALPN support required', 1 unless $has_alpn; $s = Test::Nginx::HTTP2->new(port(8080), SSL => 1, alpn => 'h2'); $sid = $s->new_stream({ path => '/https' }); $frames = $s->read(all => [{ sid => $sid, fin => 1 }]); ($frame) = grep { $_->{type} eq "DATA" } @$frames; is($frame->{data}, 'on', 'https variable - alpn'); } ###############################################################################
{ "pile_set_name": "Github" }
/* // <copyright> // dotNetRDF is free and open source software licensed under the MIT License // ------------------------------------------------------------------------- // // Copyright (c) 2009-2020 dotNetRDF Project (http://dotnetrdf.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. // </copyright> */ namespace VDS.RDF.Shacl { using System; using System.Diagnostics; using System.Linq; using VDS.RDF.Nodes; internal class PrefixDeclaration : WrapperNode { [DebuggerStepThrough] internal PrefixDeclaration(INode node) : base(node) { } internal string Prefix { get { return Vocabulary.Prefix.ObjectsOf(this).Single().AsValuedNode().AsString(); } } internal Uri Namespace { get { return UriFactory.Create(((ILiteralNode)Vocabulary.Namespace.ObjectsOf(this).Single()).Value); } } } }
{ "pile_set_name": "Github" }
using Moq.Sdk; namespace Moq { /// <summary> /// Provides configuration and introspection information for a mock. /// </summary> public interface IMoq<T> : IMoq, IMock<T>, IFluentInterface where T : class { } }
{ "pile_set_name": "Github" }
/* * Copyright (c) 2007, 2012, 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.vm.jdk; import com.sun.max.annotate.*; import com.sun.max.vm.*; /** * Method substitutions for {@link java.lang.Shutdown}. */ @METHOD_SUBSTITUTIONS(className = "java.lang.Shutdown") public final class JDK_java_lang_Shutdown { @SUBSTITUTE static void halt0(int status) { MaxineVM.exit(status); } @ALIAS(declaringClassName = "java.lang.ref.Finalizer", name = "runAllFinalizers") static native void raf(); @SUBSTITUTE private static void runAllFinalizers() { raf(); } }
{ "pile_set_name": "Github" }
interactions: - request: body: '{"documents": [{"id": "1", "text": "I had a wonderful experience! The rooms were wonderful and the staff was helpful."}]}' headers: Accept: - application/json Accept-Encoding: - gzip, deflate Connection: - keep-alive Content-Length: - '121' Content-Type: - application/json; charset=utf-8 User-Agent: - python/3.7.3 (Windows-10-10.0.18362-SP0) msrest/0.6.10 azure-cognitiveservices-language-textanalytics/0.2.0 X-BingApis-SDK-Client: - Python-SDK method: POST uri: https://westus2.api.cognitive.microsoft.com/text/analytics/v2.1/languages response: body: string: '{"documents":[{"id":"1","detectedLanguages":[{"name":"English","iso6391Name":"en","score":1.0}]}],"errors":[]}' headers: apim-request-id: - cd12691f-ea4e-451a-8506-cfdb887f14a5 content-type: - application/json; charset=utf-8 csp-billing-usage: - CognitiveServices.TextAnalytics.BatchScoring=1 date: - Thu, 19 Dec 2019 00:53:18 GMT strict-transport-security: - max-age=31536000; includeSubDomains; preload transfer-encoding: - chunked x-aml-ta-request-id: - b9b62c97-9140-4031-9878-8c9354b01c31 x-content-type-options: - nosniff x-envoy-upstream-service-time: - '5' status: code: 200 message: OK version: 1
{ "pile_set_name": "Github" }
/* * Copyright 2008 Freescale Semiconductor, Inc. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * Version 2 as published by the Free Software Foundation. */ #include <common.h> #include <asm/io.h> #include <asm/fsl_ddr_sdram.h> #if (CONFIG_CHIP_SELECTS_PER_CTRL > 4) #error Invalid setting for CONFIG_CHIP_SELECTS_PER_CTRL #endif void fsl_ddr_set_memctl_regs(const fsl_ddr_cfg_regs_t *regs, unsigned int ctrl_num) { unsigned int i; volatile ccsr_ddr_t *ddr; switch (ctrl_num) { case 0: ddr = (void *)CONFIG_SYS_MPC86xx_DDR_ADDR; break; case 1: ddr = (void *)CONFIG_SYS_MPC86xx_DDR2_ADDR; break; default: printf("%s unexpected ctrl_num = %u\n", __FUNCTION__, ctrl_num); return; } for (i = 0; i < CONFIG_CHIP_SELECTS_PER_CTRL; i++) { if (i == 0) { out_be32(&ddr->cs0_bnds, regs->cs[i].bnds); out_be32(&ddr->cs0_config, regs->cs[i].config); } else if (i == 1) { out_be32(&ddr->cs1_bnds, regs->cs[i].bnds); out_be32(&ddr->cs1_config, regs->cs[i].config); } else if (i == 2) { out_be32(&ddr->cs2_bnds, regs->cs[i].bnds); out_be32(&ddr->cs2_config, regs->cs[i].config); } else if (i == 3) { out_be32(&ddr->cs3_bnds, regs->cs[i].bnds); out_be32(&ddr->cs3_config, regs->cs[i].config); } } out_be32(&ddr->timing_cfg_3, regs->timing_cfg_3); out_be32(&ddr->timing_cfg_0, regs->timing_cfg_0); out_be32(&ddr->timing_cfg_1, regs->timing_cfg_1); out_be32(&ddr->timing_cfg_2, regs->timing_cfg_2); out_be32(&ddr->sdram_cfg_2, regs->ddr_sdram_cfg_2); out_be32(&ddr->sdram_mode, regs->ddr_sdram_mode); out_be32(&ddr->sdram_mode_2, regs->ddr_sdram_mode_2); out_be32(&ddr->sdram_mode_cntl, regs->ddr_sdram_md_cntl); out_be32(&ddr->sdram_interval, regs->ddr_sdram_interval); out_be32(&ddr->sdram_data_init, regs->ddr_data_init); out_be32(&ddr->sdram_clk_cntl, regs->ddr_sdram_clk_cntl); out_be32(&ddr->init_addr, regs->ddr_init_addr); out_be32(&ddr->init_ext_addr, regs->ddr_init_ext_addr); debug("before go\n"); /* * 200 painful micro-seconds must elapse between * the DDR clock setup and the DDR config enable. */ udelay(200); asm volatile("sync;isync"); out_be32(&ddr->sdram_cfg, regs->ddr_sdram_cfg); /* * Poll DDR_SDRAM_CFG_2[D_INIT] bit until auto-data init is done */ while (in_be32(&ddr->sdram_cfg_2) & 0x10) { udelay(10000); /* throttle polling rate */ } }
{ "pile_set_name": "Github" }
<?php $user = new \App\User\User(); $errors = array(); if ($_SERVER["REQUEST_METHOD"] == "POST") { if (!isset($_POST["username"]) || !trim($_POST["username"])) { $errors["username"] = "Veuillez indiquer un nom d'utilisateur."; } else { $user->setUsername(trim($_POST["username"])); } if (empty($_POST["password"])) { $errors["password"] = "Veuillez indiquer un mot de passe."; } elseif (empty($_POST["password"]) || $_POST["password"] != $_POST["confirmPassword"]) { $errors["confirmPassword"] = "Les deux mots de passe ne correspondent pas."; } if (empty($errors)) { $user->setPassword(sha1($_POST["password"])); $userStorage->save($user); header("LOCATION: ?mod=admin&a=users"); exit; } }
{ "pile_set_name": "Github" }
namespace ActivationFunctionViewer { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.zed = new ZedGraph.ZedGraphControl(); this.SuspendLayout(); // // zed // this.zed.Dock = System.Windows.Forms.DockStyle.Fill; this.zed.IsAntiAlias = true; this.zed.Location = new System.Drawing.Point(0, 0); this.zed.Name = "zed"; this.zed.ScrollGrace = 0D; this.zed.ScrollMaxX = 0D; this.zed.ScrollMaxY = 0D; this.zed.ScrollMaxY2 = 0D; this.zed.ScrollMinX = 0D; this.zed.ScrollMinY = 0D; this.zed.ScrollMinY2 = 0D; this.zed.Size = new System.Drawing.Size(713, 591); this.zed.TabIndex = 2; this.zed.UseExtendedPrintDialog = true; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(713, 591); this.Controls.Add(this.zed); this.Name = "Form1"; this.Text = "Activation Function Viewer"; this.ResumeLayout(false); } #endregion private ZedGraph.ZedGraphControl zed; } }
{ "pile_set_name": "Github" }
hooks style ^ 'form { padding: 2px; margin: 0; } form th { text-align: left; padding-right: 2em; } form textarea { width: 100%; height: 100px; border: 1px solid #aaa; }'
{ "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.isis.applib.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Indicates that an property, collection or action is to be called * programmatically and should be ignored from the metamodel. * * <p> * For example, it may be a helper method that needs to be <tt>public</tt> but * that doesn't conform to the requirements of an action (for example, invalid * parameter types). * * <p> * It can also be added to a type, meaning that the type is ignored from the metamodel. * This is intended as a &quot;get out of jail&quot; for any classes from unit tests, say, * that end up on the classpath of integration tests but should otherwise be ignored. */ // tag::refguide[] @Inherited @Target({ ElementType.METHOD, ElementType.TYPE, ElementType.FIELD }) @Retention(RetentionPolicy.RUNTIME) public @interface Programmatic { } // end::refguide[]
{ "pile_set_name": "Github" }
; EXPECT: unsat ; COMMAND-LINE: --sygus-out=status --lang=sygus2 --sygus-active-gen=enum (set-logic ALL) (declare-datatype Formula ( (P (Id Int)) (Op1 (op1 Int) (f Formula)) (Op2 (op2 Int) (f1 Formula) (f2 Formula)) ) ) (synth-fun phi () Formula ((<F> Formula) (<O2> Int)) ((<F> Formula ( (P <O2>) (Op1 <O2> <F>) (Op2 <O2> <F> <F>) ) ) (<O2> Int (0 1)) ) ) (define-fun holds ((f Formula)) Bool (and ((_ is Op2) f) (= (op2 f) 1)) ) (define-fun holds2 ((f Formula)) Bool (and ((_ is Op2) f) (= (op1 (f1 f)) 1)) ) (constraint (holds phi)) (check-synth)
{ "pile_set_name": "Github" }
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: dev \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class dictionary; object blockMeshDict; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // convertToMeters 0.01; vertices ( (-0.5 -5 -0.5) ( 0.5 -5 -0.5) ( 0.5 5 -0.5) (-0.5 5 -0.5) (-0.5 -5 0.5) ( 0.5 -5 0.5) ( 0.5 5 0.5) (-0.5 5 0.5) ); blocks ( hex (0 1 2 3 4 5 6 7) (5 50 5) simpleGrading (1 1 1) ); edges ( ); boundary ( walls { type wall; faces ( (3 7 6 2) (0 4 7 3) (2 6 5 1) (1 5 4 0) (0 3 2 1) (4 5 6 7) ); } ); // ************************************************************************* //
{ "pile_set_name": "Github" }
// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. /* Package trace implements tracing of requests and long-lived objects. It exports HTTP interfaces on /debug/requests and /debug/events. A trace.Trace provides tracing for short-lived objects, usually requests. A request handler might be implemented like this: func fooHandler(w http.ResponseWriter, req *http.Request) { tr := trace.New("mypkg.Foo", req.URL.Path) defer tr.Finish() ... tr.LazyPrintf("some event %q happened", str) ... if err := somethingImportant(); err != nil { tr.LazyPrintf("somethingImportant failed: %v", err) tr.SetError() } } The /debug/requests HTTP endpoint organizes the traces by family, errors, and duration. It also provides histogram of request duration for each family. A trace.EventLog provides tracing for long-lived objects, such as RPC connections. // A Fetcher fetches URL paths for a single domain. type Fetcher struct { domain string events trace.EventLog } func NewFetcher(domain string) *Fetcher { return &Fetcher{ domain, trace.NewEventLog("mypkg.Fetcher", domain), } } func (f *Fetcher) Fetch(path string) (string, error) { resp, err := http.Get("http://" + f.domain + "/" + path) if err != nil { f.events.Errorf("Get(%q) = %v", path, err) return "", err } f.events.Printf("Get(%q) = %s", path, resp.Status) ... } func (f *Fetcher) Close() error { f.events.Finish() return nil } The /debug/events HTTP endpoint organizes the event logs by family and by time since the last error. The expanded view displays recent log entries and the log's call stack. */ package trace // import "golang.org/x/net/trace" import ( "bytes" "context" "fmt" "html/template" "io" "log" "net" "net/http" "net/url" "runtime" "sort" "strconv" "sync" "sync/atomic" "time" "golang.org/x/net/internal/timeseries" ) // DebugUseAfterFinish controls whether to debug uses of Trace values after finishing. // FOR DEBUGGING ONLY. This will slow down the program. var DebugUseAfterFinish = false // HTTP ServeMux paths. const ( debugRequestsPath = "/debug/requests" debugEventsPath = "/debug/events" ) // AuthRequest determines whether a specific request is permitted to load the // /debug/requests or /debug/events pages. // // It returns two bools; the first indicates whether the page may be viewed at all, // and the second indicates whether sensitive events will be shown. // // AuthRequest may be replaced by a program to customize its authorization requirements. // // The default AuthRequest function returns (true, true) if and only if the request // comes from localhost/127.0.0.1/[::1]. var AuthRequest = func(req *http.Request) (any, sensitive bool) { // RemoteAddr is commonly in the form "IP" or "IP:port". // If it is in the form "IP:port", split off the port. host, _, err := net.SplitHostPort(req.RemoteAddr) if err != nil { host = req.RemoteAddr } switch host { case "localhost", "127.0.0.1", "::1": return true, true default: return false, false } } func init() { _, pat := http.DefaultServeMux.Handler(&http.Request{URL: &url.URL{Path: debugRequestsPath}}) if pat == debugRequestsPath { panic("/debug/requests is already registered. You may have two independent copies of " + "golang.org/x/net/trace in your binary, trying to maintain separate state. This may " + "involve a vendored copy of golang.org/x/net/trace.") } // TODO(jbd): Serve Traces from /debug/traces in the future? // There is no requirement for a request to be present to have traces. http.HandleFunc(debugRequestsPath, Traces) http.HandleFunc(debugEventsPath, Events) } // NewContext returns a copy of the parent context // and associates it with a Trace. func NewContext(ctx context.Context, tr Trace) context.Context { return context.WithValue(ctx, contextKey, tr) } // FromContext returns the Trace bound to the context, if any. func FromContext(ctx context.Context) (tr Trace, ok bool) { tr, ok = ctx.Value(contextKey).(Trace) return } // Traces responds with traces from the program. // The package initialization registers it in http.DefaultServeMux // at /debug/requests. // // It performs authorization by running AuthRequest. func Traces(w http.ResponseWriter, req *http.Request) { any, sensitive := AuthRequest(req) if !any { http.Error(w, "not allowed", http.StatusUnauthorized) return } w.Header().Set("Content-Type", "text/html; charset=utf-8") Render(w, req, sensitive) } // Events responds with a page of events collected by EventLogs. // The package initialization registers it in http.DefaultServeMux // at /debug/events. // // It performs authorization by running AuthRequest. func Events(w http.ResponseWriter, req *http.Request) { any, sensitive := AuthRequest(req) if !any { http.Error(w, "not allowed", http.StatusUnauthorized) return } w.Header().Set("Content-Type", "text/html; charset=utf-8") RenderEvents(w, req, sensitive) } // Render renders the HTML page typically served at /debug/requests. // It does not do any auth checking. The request may be nil. // // Most users will use the Traces handler. func Render(w io.Writer, req *http.Request, sensitive bool) { data := &struct { Families []string ActiveTraceCount map[string]int CompletedTraces map[string]*family // Set when a bucket has been selected. Traces traceList Family string Bucket int Expanded bool Traced bool Active bool ShowSensitive bool // whether to show sensitive events Histogram template.HTML HistogramWindow string // e.g. "last minute", "last hour", "all time" // If non-zero, the set of traces is a partial set, // and this is the total number. Total int }{ CompletedTraces: completedTraces, } data.ShowSensitive = sensitive if req != nil { // Allow show_sensitive=0 to force hiding of sensitive data for testing. // This only goes one way; you can't use show_sensitive=1 to see things. if req.FormValue("show_sensitive") == "0" { data.ShowSensitive = false } if exp, err := strconv.ParseBool(req.FormValue("exp")); err == nil { data.Expanded = exp } if exp, err := strconv.ParseBool(req.FormValue("rtraced")); err == nil { data.Traced = exp } } completedMu.RLock() data.Families = make([]string, 0, len(completedTraces)) for fam := range completedTraces { data.Families = append(data.Families, fam) } completedMu.RUnlock() sort.Strings(data.Families) // We are careful here to minimize the time spent locking activeMu, // since that lock is required every time an RPC starts and finishes. data.ActiveTraceCount = make(map[string]int, len(data.Families)) activeMu.RLock() for fam, s := range activeTraces { data.ActiveTraceCount[fam] = s.Len() } activeMu.RUnlock() var ok bool data.Family, data.Bucket, ok = parseArgs(req) switch { case !ok: // No-op case data.Bucket == -1: data.Active = true n := data.ActiveTraceCount[data.Family] data.Traces = getActiveTraces(data.Family) if len(data.Traces) < n { data.Total = n } case data.Bucket < bucketsPerFamily: if b := lookupBucket(data.Family, data.Bucket); b != nil { data.Traces = b.Copy(data.Traced) } default: if f := getFamily(data.Family, false); f != nil { var obs timeseries.Observable f.LatencyMu.RLock() switch o := data.Bucket - bucketsPerFamily; o { case 0: obs = f.Latency.Minute() data.HistogramWindow = "last minute" case 1: obs = f.Latency.Hour() data.HistogramWindow = "last hour" case 2: obs = f.Latency.Total() data.HistogramWindow = "all time" } f.LatencyMu.RUnlock() if obs != nil { data.Histogram = obs.(*histogram).html() } } } if data.Traces != nil { defer data.Traces.Free() sort.Sort(data.Traces) } completedMu.RLock() defer completedMu.RUnlock() if err := pageTmpl().ExecuteTemplate(w, "Page", data); err != nil { log.Printf("net/trace: Failed executing template: %v", err) } } func parseArgs(req *http.Request) (fam string, b int, ok bool) { if req == nil { return "", 0, false } fam, bStr := req.FormValue("fam"), req.FormValue("b") if fam == "" || bStr == "" { return "", 0, false } b, err := strconv.Atoi(bStr) if err != nil || b < -1 { return "", 0, false } return fam, b, true } func lookupBucket(fam string, b int) *traceBucket { f := getFamily(fam, false) if f == nil || b < 0 || b >= len(f.Buckets) { return nil } return f.Buckets[b] } type contextKeyT string var contextKey = contextKeyT("golang.org/x/net/trace.Trace") // Trace represents an active request. type Trace interface { // LazyLog adds x to the event log. It will be evaluated each time the // /debug/requests page is rendered. Any memory referenced by x will be // pinned until the trace is finished and later discarded. LazyLog(x fmt.Stringer, sensitive bool) // LazyPrintf evaluates its arguments with fmt.Sprintf each time the // /debug/requests page is rendered. Any memory referenced by a will be // pinned until the trace is finished and later discarded. LazyPrintf(format string, a ...interface{}) // SetError declares that this trace resulted in an error. SetError() // SetRecycler sets a recycler for the trace. // f will be called for each event passed to LazyLog at a time when // it is no longer required, whether while the trace is still active // and the event is discarded, or when a completed trace is discarded. SetRecycler(f func(interface{})) // SetTraceInfo sets the trace info for the trace. // This is currently unused. SetTraceInfo(traceID, spanID uint64) // SetMaxEvents sets the maximum number of events that will be stored // in the trace. This has no effect if any events have already been // added to the trace. SetMaxEvents(m int) // Finish declares that this trace is complete. // The trace should not be used after calling this method. Finish() } type lazySprintf struct { format string a []interface{} } func (l *lazySprintf) String() string { return fmt.Sprintf(l.format, l.a...) } // New returns a new Trace with the specified family and title. func New(family, title string) Trace { tr := newTrace() tr.ref() tr.Family, tr.Title = family, title tr.Start = time.Now() tr.maxEvents = maxEventsPerTrace tr.events = tr.eventsBuf[:0] activeMu.RLock() s := activeTraces[tr.Family] activeMu.RUnlock() if s == nil { activeMu.Lock() s = activeTraces[tr.Family] // check again if s == nil { s = new(traceSet) activeTraces[tr.Family] = s } activeMu.Unlock() } s.Add(tr) // Trigger allocation of the completed trace structure for this family. // This will cause the family to be present in the request page during // the first trace of this family. We don't care about the return value, // nor is there any need for this to run inline, so we execute it in its // own goroutine, but only if the family isn't allocated yet. completedMu.RLock() if _, ok := completedTraces[tr.Family]; !ok { go allocFamily(tr.Family) } completedMu.RUnlock() return tr } func (tr *trace) Finish() { elapsed := time.Now().Sub(tr.Start) tr.mu.Lock() tr.Elapsed = elapsed tr.mu.Unlock() if DebugUseAfterFinish { buf := make([]byte, 4<<10) // 4 KB should be enough n := runtime.Stack(buf, false) tr.finishStack = buf[:n] } activeMu.RLock() m := activeTraces[tr.Family] activeMu.RUnlock() m.Remove(tr) f := getFamily(tr.Family, true) tr.mu.RLock() // protects tr fields in Cond.match calls for _, b := range f.Buckets { if b.Cond.match(tr) { b.Add(tr) } } tr.mu.RUnlock() // Add a sample of elapsed time as microseconds to the family's timeseries h := new(histogram) h.addMeasurement(elapsed.Nanoseconds() / 1e3) f.LatencyMu.Lock() f.Latency.Add(h) f.LatencyMu.Unlock() tr.unref() // matches ref in New } const ( bucketsPerFamily = 9 tracesPerBucket = 10 maxActiveTraces = 20 // Maximum number of active traces to show. maxEventsPerTrace = 10 numHistogramBuckets = 38 ) var ( // The active traces. activeMu sync.RWMutex activeTraces = make(map[string]*traceSet) // family -> traces // Families of completed traces. completedMu sync.RWMutex completedTraces = make(map[string]*family) // family -> traces ) type traceSet struct { mu sync.RWMutex m map[*trace]bool // We could avoid the entire map scan in FirstN by having a slice of all the traces // ordered by start time, and an index into that from the trace struct, with a periodic // repack of the slice after enough traces finish; we could also use a skip list or similar. // However, that would shift some of the expense from /debug/requests time to RPC time, // which is probably the wrong trade-off. } func (ts *traceSet) Len() int { ts.mu.RLock() defer ts.mu.RUnlock() return len(ts.m) } func (ts *traceSet) Add(tr *trace) { ts.mu.Lock() if ts.m == nil { ts.m = make(map[*trace]bool) } ts.m[tr] = true ts.mu.Unlock() } func (ts *traceSet) Remove(tr *trace) { ts.mu.Lock() delete(ts.m, tr) ts.mu.Unlock() } // FirstN returns the first n traces ordered by time. func (ts *traceSet) FirstN(n int) traceList { ts.mu.RLock() defer ts.mu.RUnlock() if n > len(ts.m) { n = len(ts.m) } trl := make(traceList, 0, n) // Fast path for when no selectivity is needed. if n == len(ts.m) { for tr := range ts.m { tr.ref() trl = append(trl, tr) } sort.Sort(trl) return trl } // Pick the oldest n traces. // This is inefficient. See the comment in the traceSet struct. for tr := range ts.m { // Put the first n traces into trl in the order they occur. // When we have n, sort trl, and thereafter maintain its order. if len(trl) < n { tr.ref() trl = append(trl, tr) if len(trl) == n { // This is guaranteed to happen exactly once during this loop. sort.Sort(trl) } continue } if tr.Start.After(trl[n-1].Start) { continue } // Find where to insert this one. tr.ref() i := sort.Search(n, func(i int) bool { return trl[i].Start.After(tr.Start) }) trl[n-1].unref() copy(trl[i+1:], trl[i:]) trl[i] = tr } return trl } func getActiveTraces(fam string) traceList { activeMu.RLock() s := activeTraces[fam] activeMu.RUnlock() if s == nil { return nil } return s.FirstN(maxActiveTraces) } func getFamily(fam string, allocNew bool) *family { completedMu.RLock() f := completedTraces[fam] completedMu.RUnlock() if f == nil && allocNew { f = allocFamily(fam) } return f } func allocFamily(fam string) *family { completedMu.Lock() defer completedMu.Unlock() f := completedTraces[fam] if f == nil { f = newFamily() completedTraces[fam] = f } return f } // family represents a set of trace buckets and associated latency information. type family struct { // traces may occur in multiple buckets. Buckets [bucketsPerFamily]*traceBucket // latency time series LatencyMu sync.RWMutex Latency *timeseries.MinuteHourSeries } func newFamily() *family { return &family{ Buckets: [bucketsPerFamily]*traceBucket{ {Cond: minCond(0)}, {Cond: minCond(50 * time.Millisecond)}, {Cond: minCond(100 * time.Millisecond)}, {Cond: minCond(200 * time.Millisecond)}, {Cond: minCond(500 * time.Millisecond)}, {Cond: minCond(1 * time.Second)}, {Cond: minCond(10 * time.Second)}, {Cond: minCond(100 * time.Second)}, {Cond: errorCond{}}, }, Latency: timeseries.NewMinuteHourSeries(func() timeseries.Observable { return new(histogram) }), } } // traceBucket represents a size-capped bucket of historic traces, // along with a condition for a trace to belong to the bucket. type traceBucket struct { Cond cond // Ring buffer implementation of a fixed-size FIFO queue. mu sync.RWMutex buf [tracesPerBucket]*trace start int // < tracesPerBucket length int // <= tracesPerBucket } func (b *traceBucket) Add(tr *trace) { b.mu.Lock() defer b.mu.Unlock() i := b.start + b.length if i >= tracesPerBucket { i -= tracesPerBucket } if b.length == tracesPerBucket { // "Remove" an element from the bucket. b.buf[i].unref() b.start++ if b.start == tracesPerBucket { b.start = 0 } } b.buf[i] = tr if b.length < tracesPerBucket { b.length++ } tr.ref() } // Copy returns a copy of the traces in the bucket. // If tracedOnly is true, only the traces with trace information will be returned. // The logs will be ref'd before returning; the caller should call // the Free method when it is done with them. // TODO(dsymonds): keep track of traced requests in separate buckets. func (b *traceBucket) Copy(tracedOnly bool) traceList { b.mu.RLock() defer b.mu.RUnlock() trl := make(traceList, 0, b.length) for i, x := 0, b.start; i < b.length; i++ { tr := b.buf[x] if !tracedOnly || tr.spanID != 0 { tr.ref() trl = append(trl, tr) } x++ if x == b.length { x = 0 } } return trl } func (b *traceBucket) Empty() bool { b.mu.RLock() defer b.mu.RUnlock() return b.length == 0 } // cond represents a condition on a trace. type cond interface { match(t *trace) bool String() string } type minCond time.Duration func (m minCond) match(t *trace) bool { return t.Elapsed >= time.Duration(m) } func (m minCond) String() string { return fmt.Sprintf("≥%gs", time.Duration(m).Seconds()) } type errorCond struct{} func (e errorCond) match(t *trace) bool { return t.IsError } func (e errorCond) String() string { return "errors" } type traceList []*trace // Free calls unref on each element of the list. func (trl traceList) Free() { for _, t := range trl { t.unref() } } // traceList may be sorted in reverse chronological order. func (trl traceList) Len() int { return len(trl) } func (trl traceList) Less(i, j int) bool { return trl[i].Start.After(trl[j].Start) } func (trl traceList) Swap(i, j int) { trl[i], trl[j] = trl[j], trl[i] } // An event is a timestamped log entry in a trace. type event struct { When time.Time Elapsed time.Duration // since previous event in trace NewDay bool // whether this event is on a different day to the previous event Recyclable bool // whether this event was passed via LazyLog Sensitive bool // whether this event contains sensitive information What interface{} // string or fmt.Stringer } // WhenString returns a string representation of the elapsed time of the event. // It will include the date if midnight was crossed. func (e event) WhenString() string { if e.NewDay { return e.When.Format("2006/01/02 15:04:05.000000") } return e.When.Format("15:04:05.000000") } // discarded represents a number of discarded events. // It is stored as *discarded to make it easier to update in-place. type discarded int func (d *discarded) String() string { return fmt.Sprintf("(%d events discarded)", int(*d)) } // trace represents an active or complete request, // either sent or received by this program. type trace struct { // Family is the top-level grouping of traces to which this belongs. Family string // Title is the title of this trace. Title string // Start time of the this trace. Start time.Time mu sync.RWMutex events []event // Append-only sequence of events (modulo discards). maxEvents int recycler func(interface{}) IsError bool // Whether this trace resulted in an error. Elapsed time.Duration // Elapsed time for this trace, zero while active. traceID uint64 // Trace information if non-zero. spanID uint64 refs int32 // how many buckets this is in disc discarded // scratch space to avoid allocation finishStack []byte // where finish was called, if DebugUseAfterFinish is set eventsBuf [4]event // preallocated buffer in case we only log a few events } func (tr *trace) reset() { // Clear all but the mutex. Mutexes may not be copied, even when unlocked. tr.Family = "" tr.Title = "" tr.Start = time.Time{} tr.mu.Lock() tr.Elapsed = 0 tr.traceID = 0 tr.spanID = 0 tr.IsError = false tr.maxEvents = 0 tr.events = nil tr.recycler = nil tr.mu.Unlock() tr.refs = 0 tr.disc = 0 tr.finishStack = nil for i := range tr.eventsBuf { tr.eventsBuf[i] = event{} } } // delta returns the elapsed time since the last event or the trace start, // and whether it spans midnight. // L >= tr.mu func (tr *trace) delta(t time.Time) (time.Duration, bool) { if len(tr.events) == 0 { return t.Sub(tr.Start), false } prev := tr.events[len(tr.events)-1].When return t.Sub(prev), prev.Day() != t.Day() } func (tr *trace) addEvent(x interface{}, recyclable, sensitive bool) { if DebugUseAfterFinish && tr.finishStack != nil { buf := make([]byte, 4<<10) // 4 KB should be enough n := runtime.Stack(buf, false) log.Printf("net/trace: trace used after finish:\nFinished at:\n%s\nUsed at:\n%s", tr.finishStack, buf[:n]) } /* NOTE TO DEBUGGERS If you are here because your program panicked in this code, it is almost definitely the fault of code using this package, and very unlikely to be the fault of this code. The most likely scenario is that some code elsewhere is using a trace.Trace after its Finish method is called. You can temporarily set the DebugUseAfterFinish var to help discover where that is; do not leave that var set, since it makes this package much less efficient. */ e := event{When: time.Now(), What: x, Recyclable: recyclable, Sensitive: sensitive} tr.mu.Lock() e.Elapsed, e.NewDay = tr.delta(e.When) if len(tr.events) < tr.maxEvents { tr.events = append(tr.events, e) } else { // Discard the middle events. di := int((tr.maxEvents - 1) / 2) if d, ok := tr.events[di].What.(*discarded); ok { (*d)++ } else { // disc starts at two to count for the event it is replacing, // plus the next one that we are about to drop. tr.disc = 2 if tr.recycler != nil && tr.events[di].Recyclable { go tr.recycler(tr.events[di].What) } tr.events[di].What = &tr.disc } // The timestamp of the discarded meta-event should be // the time of the last event it is representing. tr.events[di].When = tr.events[di+1].When if tr.recycler != nil && tr.events[di+1].Recyclable { go tr.recycler(tr.events[di+1].What) } copy(tr.events[di+1:], tr.events[di+2:]) tr.events[tr.maxEvents-1] = e } tr.mu.Unlock() } func (tr *trace) LazyLog(x fmt.Stringer, sensitive bool) { tr.addEvent(x, true, sensitive) } func (tr *trace) LazyPrintf(format string, a ...interface{}) { tr.addEvent(&lazySprintf{format, a}, false, false) } func (tr *trace) SetError() { tr.mu.Lock() tr.IsError = true tr.mu.Unlock() } func (tr *trace) SetRecycler(f func(interface{})) { tr.mu.Lock() tr.recycler = f tr.mu.Unlock() } func (tr *trace) SetTraceInfo(traceID, spanID uint64) { tr.mu.Lock() tr.traceID, tr.spanID = traceID, spanID tr.mu.Unlock() } func (tr *trace) SetMaxEvents(m int) { tr.mu.Lock() // Always keep at least three events: first, discarded count, last. if len(tr.events) == 0 && m > 3 { tr.maxEvents = m } tr.mu.Unlock() } func (tr *trace) ref() { atomic.AddInt32(&tr.refs, 1) } func (tr *trace) unref() { if atomic.AddInt32(&tr.refs, -1) == 0 { tr.mu.RLock() if tr.recycler != nil { // freeTrace clears tr, so we hold tr.recycler and tr.events here. go func(f func(interface{}), es []event) { for _, e := range es { if e.Recyclable { f(e.What) } } }(tr.recycler, tr.events) } tr.mu.RUnlock() freeTrace(tr) } } func (tr *trace) When() string { return tr.Start.Format("2006/01/02 15:04:05.000000") } func (tr *trace) ElapsedTime() string { tr.mu.RLock() t := tr.Elapsed tr.mu.RUnlock() if t == 0 { // Active trace. t = time.Since(tr.Start) } return fmt.Sprintf("%.6f", t.Seconds()) } func (tr *trace) Events() []event { tr.mu.RLock() defer tr.mu.RUnlock() return tr.events } var traceFreeList = make(chan *trace, 1000) // TODO(dsymonds): Use sync.Pool? // newTrace returns a trace ready to use. func newTrace() *trace { select { case tr := <-traceFreeList: return tr default: return new(trace) } } // freeTrace adds tr to traceFreeList if there's room. // This is non-blocking. func freeTrace(tr *trace) { if DebugUseAfterFinish { return // never reuse } tr.reset() select { case traceFreeList <- tr: default: } } func elapsed(d time.Duration) string { b := []byte(fmt.Sprintf("%.6f", d.Seconds())) // For subsecond durations, blank all zeros before decimal point, // and all zeros between the decimal point and the first non-zero digit. if d < time.Second { dot := bytes.IndexByte(b, '.') for i := 0; i < dot; i++ { b[i] = ' ' } for i := dot + 1; i < len(b); i++ { if b[i] == '0' { b[i] = ' ' } else { break } } } return string(b) } var pageTmplCache *template.Template var pageTmplOnce sync.Once func pageTmpl() *template.Template { pageTmplOnce.Do(func() { pageTmplCache = template.Must(template.New("Page").Funcs(template.FuncMap{ "elapsed": elapsed, "add": func(a, b int) int { return a + b }, }).Parse(pageHTML)) }) return pageTmplCache } const pageHTML = ` {{template "Prolog" .}} {{template "StatusTable" .}} {{template "Epilog" .}} {{define "Prolog"}} <html> <head> <title>/debug/requests</title> <style type="text/css"> body { font-family: sans-serif; } table#tr-status td.family { padding-right: 2em; } table#tr-status td.active { padding-right: 1em; } table#tr-status td.latency-first { padding-left: 1em; } table#tr-status td.empty { color: #aaa; } table#reqs { margin-top: 1em; } table#reqs tr.first { {{if $.Expanded}}font-weight: bold;{{end}} } table#reqs td { font-family: monospace; } table#reqs td.when { text-align: right; white-space: nowrap; } table#reqs td.elapsed { padding: 0 0.5em; text-align: right; white-space: pre; width: 10em; } address { font-size: smaller; margin-top: 5em; } </style> </head> <body> <h1>/debug/requests</h1> {{end}} {{/* end of Prolog */}} {{define "StatusTable"}} <table id="tr-status"> {{range $fam := .Families}} <tr> <td class="family">{{$fam}}</td> {{$n := index $.ActiveTraceCount $fam}} <td class="active {{if not $n}}empty{{end}}"> {{if $n}}<a href="?fam={{$fam}}&b=-1{{if $.Expanded}}&exp=1{{end}}">{{end}} [{{$n}} active] {{if $n}}</a>{{end}} </td> {{$f := index $.CompletedTraces $fam}} {{range $i, $b := $f.Buckets}} {{$empty := $b.Empty}} <td {{if $empty}}class="empty"{{end}}> {{if not $empty}}<a href="?fam={{$fam}}&b={{$i}}{{if $.Expanded}}&exp=1{{end}}">{{end}} [{{.Cond}}] {{if not $empty}}</a>{{end}} </td> {{end}} {{$nb := len $f.Buckets}} <td class="latency-first"> <a href="?fam={{$fam}}&b={{$nb}}">[minute]</a> </td> <td> <a href="?fam={{$fam}}&b={{add $nb 1}}">[hour]</a> </td> <td> <a href="?fam={{$fam}}&b={{add $nb 2}}">[total]</a> </td> </tr> {{end}} </table> {{end}} {{/* end of StatusTable */}} {{define "Epilog"}} {{if $.Traces}} <hr /> <h3>Family: {{$.Family}}</h3> {{if or $.Expanded $.Traced}} <a href="?fam={{$.Family}}&b={{$.Bucket}}">[Normal/Summary]</a> {{else}} [Normal/Summary] {{end}} {{if or (not $.Expanded) $.Traced}} <a href="?fam={{$.Family}}&b={{$.Bucket}}&exp=1">[Normal/Expanded]</a> {{else}} [Normal/Expanded] {{end}} {{if not $.Active}} {{if or $.Expanded (not $.Traced)}} <a href="?fam={{$.Family}}&b={{$.Bucket}}&rtraced=1">[Traced/Summary]</a> {{else}} [Traced/Summary] {{end}} {{if or (not $.Expanded) (not $.Traced)}} <a href="?fam={{$.Family}}&b={{$.Bucket}}&exp=1&rtraced=1">[Traced/Expanded]</a> {{else}} [Traced/Expanded] {{end}} {{end}} {{if $.Total}} <p><em>Showing <b>{{len $.Traces}}</b> of <b>{{$.Total}}</b> traces.</em></p> {{end}} <table id="reqs"> <caption> {{if $.Active}}Active{{else}}Completed{{end}} Requests </caption> <tr><th>When</th><th>Elapsed&nbsp;(s)</th></tr> {{range $tr := $.Traces}} <tr class="first"> <td class="when">{{$tr.When}}</td> <td class="elapsed">{{$tr.ElapsedTime}}</td> <td>{{$tr.Title}}</td> {{/* TODO: include traceID/spanID */}} </tr> {{if $.Expanded}} {{range $tr.Events}} <tr> <td class="when">{{.WhenString}}</td> <td class="elapsed">{{elapsed .Elapsed}}</td> <td>{{if or $.ShowSensitive (not .Sensitive)}}... {{.What}}{{else}}<em>[redacted]</em>{{end}}</td> </tr> {{end}} {{end}} {{end}} </table> {{end}} {{/* if $.Traces */}} {{if $.Histogram}} <h4>Latency (&micro;s) of {{$.Family}} over {{$.HistogramWindow}}</h4> {{$.Histogram}} {{end}} {{/* if $.Histogram */}} </body> </html> {{end}} {{/* end of Epilog */}} `
{ "pile_set_name": "Github" }
// Copyright 2017 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Flags: --allow-natives-syntax --expose-externalize-string (function() { function foo(s) { return "abcdefghijklm" + s; } assertTrue(isOneByteString(foo("0"))); assertTrue(isOneByteString(foo("0"))); %OptimizeFunctionOnNextCall(foo); assertTrue(isOneByteString(foo("0"))); })(); (function() { function foo(s) { return s + "abcdefghijklm"; } assertTrue(isOneByteString(foo("0"))); assertTrue(isOneByteString(foo("0"))); %OptimizeFunctionOnNextCall(foo); assertTrue(isOneByteString(foo("0"))); })(); (function() { function foo(s) { return "abcdefghijklm" + s; } assertFalse(isOneByteString(foo("\u1234"))); assertFalse(isOneByteString(foo("\u1234"))); %OptimizeFunctionOnNextCall(foo); assertFalse(isOneByteString(foo("\u1234"))); })(); (function() { function foo(s) { return s + "abcdefghijklm"; } assertFalse(isOneByteString(foo("\u1234"))); assertFalse(isOneByteString(foo("\u1234"))); %OptimizeFunctionOnNextCall(foo); assertFalse(isOneByteString(foo("\u1234"))); })(); (function() { function foo(s) { return "abcdefghijkl\u1234" + s; } assertFalse(isOneByteString(foo("0"))); assertFalse(isOneByteString(foo("0"))); %OptimizeFunctionOnNextCall(foo); assertFalse(isOneByteString(foo("0"))); })(); (function() { function foo(s) { return s + "abcdefghijkl\u1234"; } assertFalse(isOneByteString(foo("0"))); assertFalse(isOneByteString(foo("0"))); %OptimizeFunctionOnNextCall(foo); assertFalse(isOneByteString(foo("0"))); })();
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <html xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:f="http://typo3.org/ns/TYPO3/CMS/Fluid/ViewHelpers" xmlns:n="http://typo3.org/ns/GeorgRinger/News/ViewHelpers" data-namespace-typo3-fluid="true"> <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom"> <channel> <title>{settings.list.rss.channel.title}</title> <link>{settings.list.rss.channel.link}</link> <description>{settings.list.rss.channel.description}</description> <language>{settings.list.rss.channel.language}</language> <f:if condition="{settings.list.rss.channel.copyright}"> <copyright>{settings.list.rss.channel.copyright}</copyright> </f:if> <pubDate><f:format.date format="r" date="now" /></pubDate> <lastBuildDate><f:format.date format="r" date="now" /></lastBuildDate> <f:if condition="{settings.list.rss.channel.category}"> <category>{settings.list.rss.channel.category}</category> </f:if> <atom:link href="{f:uri.page(pageType: 9818, absolute: 'true') -> f:format.htmlentities()}" rel="self" type="application/rss+xml" /> <generator>{settings.list.rss.channel.generator}</generator> <f:if condition="{news}"> <f:for each="{news}" as="newsItem"> <item> <guid isPermaLink="false">news-{newsItem.uid}</guid> <pubDate><f:format.date format="r">{newsItem.datetime}</f:format.date></pubDate> <title>{newsItem.title -> f:format.htmlspecialchars()}</title> <link><f:format.htmlentities><n:link newsItem="{newsItem}" settings="{settings}" configuration="{forceAbsoluteUrl: 1}" uriOnly="1" /></f:format.htmlentities></link> <description>{newsItem.teaser -> f:format.stripTags() -> f:format.htmlspecialchars()}</description> <content:encoded><f:format.cdata><f:format.html>{newsItem.bodytext}</f:format.html></f:format.cdata></content:encoded> <f:if condition="{newsItem.categories}"> <f:for each="{newsItem.categories}" as="newsItemCategory"> <category>{newsItemCategory.title -> f:format.htmlspecialchars()}</category> </f:for> </f:if> <f:if condition="{newsItem.firstPreview}"> <enclosure url="{f:uri.image(image:newsItem.firstPreview, absolute:1, maxWidth: '1920', maxHeight: '1920')}" length="{n:imageSize(property:'size')}" type="{newsItem.firstPreview.originalResource.mimeType}"/> </f:if> </item> </f:for> </f:if> </channel> </rss> </html>
{ "pile_set_name": "Github" }
// default includes #include "Global/Macros.h" CLANG_DIAG_OFF(mismatched-tags) GCC_DIAG_OFF(unused-parameter) GCC_DIAG_OFF(missing-field-initializers) GCC_DIAG_OFF(missing-declarations) GCC_DIAG_OFF(uninitialized) GCC_DIAG_UNUSED_LOCAL_TYPEDEFS_OFF #include <shiboken.h> // produces many warnings #include <pysidesignal.h> #include <pysideproperty.h> #include <pyside.h> #include <typeresolver.h> #include <typeinfo> #include "natronengine_python.h" #include "floatnodecreationproperty_wrapper.h" // Extra includes NATRON_NAMESPACE_USING NATRON_PYTHON_NAMESPACE_USING #include <vector> // Native --------------------------------------------------------- void FloatNodeCreationPropertyWrapper::pysideInitQtMetaTypes() { } FloatNodeCreationPropertyWrapper::FloatNodeCreationPropertyWrapper(const std::vector<double > & values) : FloatNodeCreationProperty(values) { // ... middle } FloatNodeCreationPropertyWrapper::FloatNodeCreationPropertyWrapper(double value) : FloatNodeCreationProperty(value) { // ... middle } FloatNodeCreationPropertyWrapper::~FloatNodeCreationPropertyWrapper() { SbkObject* wrapper = Shiboken::BindingManager::instance().retrieveWrapper(this); Shiboken::Object::destroy(wrapper, this); } // Target --------------------------------------------------------- extern "C" { static int Sbk_FloatNodeCreationProperty_Init(PyObject* self, PyObject* args, PyObject* kwds) { SbkObject* sbkSelf = reinterpret_cast<SbkObject*>(self); if (Shiboken::Object::isUserType(self) && !Shiboken::ObjectType::canCallConstructor(self->ob_type, Shiboken::SbkType< ::FloatNodeCreationProperty >())) return -1; ::FloatNodeCreationPropertyWrapper* cptr = 0; int overloadId = -1; PythonToCppFunc pythonToCpp[] = { 0 }; SBK_UNUSED(pythonToCpp) int numNamedArgs = (kwds ? PyDict_Size(kwds) : 0); int numArgs = PyTuple_GET_SIZE(args); PyObject* pyArgs[] = {0}; // invalid argument lengths if (numArgs + numNamedArgs > 1) { PyErr_SetString(PyExc_TypeError, "NatronEngine.FloatNodeCreationProperty(): too many arguments"); return -1; } if (!PyArg_ParseTuple(args, "|O:FloatNodeCreationProperty", &(pyArgs[0]))) return -1; // Overloaded function decisor // 0: FloatNodeCreationProperty(std::vector<double>) // 1: FloatNodeCreationProperty(double) if (numArgs == 0) { overloadId = 0; // FloatNodeCreationProperty(std::vector<double>) } else if (numArgs == 1 && (pythonToCpp[0] = Shiboken::Conversions::isPythonToCppConvertible(Shiboken::Conversions::PrimitiveTypeConverter<double>(), (pyArgs[0])))) { overloadId = 1; // FloatNodeCreationProperty(double) } else if ((pythonToCpp[0] = Shiboken::Conversions::isPythonToCppConvertible(SbkNatronEngineTypeConverters[SBK_NATRONENGINE_STD_VECTOR_DOUBLE_IDX], (pyArgs[0])))) { overloadId = 0; // FloatNodeCreationProperty(std::vector<double>) } // Function signature not found. if (overloadId == -1) goto Sbk_FloatNodeCreationProperty_Init_TypeError; // Call function/method switch (overloadId) { case 0: // FloatNodeCreationProperty(const std::vector<double > & values) { if (kwds) { PyObject* value = PyDict_GetItemString(kwds, "values"); if (value && pyArgs[0]) { PyErr_SetString(PyExc_TypeError, "NatronEngine.FloatNodeCreationProperty(): got multiple values for keyword argument 'values'."); return -1; } else if (value) { pyArgs[0] = value; if (!(pythonToCpp[0] = Shiboken::Conversions::isPythonToCppConvertible(SbkNatronEngineTypeConverters[SBK_NATRONENGINE_STD_VECTOR_DOUBLE_IDX], (pyArgs[0])))) goto Sbk_FloatNodeCreationProperty_Init_TypeError; } } ::std::vector<double > cppArg0; if (pythonToCpp[0]) pythonToCpp[0](pyArgs[0], &cppArg0); if (!PyErr_Occurred()) { // FloatNodeCreationProperty(std::vector<double>) cptr = new ::FloatNodeCreationPropertyWrapper(cppArg0); } break; } case 1: // FloatNodeCreationProperty(double value) { double cppArg0; pythonToCpp[0](pyArgs[0], &cppArg0); if (!PyErr_Occurred()) { // FloatNodeCreationProperty(double) cptr = new ::FloatNodeCreationPropertyWrapper(cppArg0); } break; } } if (PyErr_Occurred() || !Shiboken::Object::setCppPointer(sbkSelf, Shiboken::SbkType< ::FloatNodeCreationProperty >(), cptr)) { delete cptr; return -1; } if (!cptr) goto Sbk_FloatNodeCreationProperty_Init_TypeError; Shiboken::Object::setValidCpp(sbkSelf, true); Shiboken::Object::setHasCppWrapper(sbkSelf, true); Shiboken::BindingManager::instance().registerWrapper(sbkSelf, cptr); return 1; Sbk_FloatNodeCreationProperty_Init_TypeError: const char* overloads[] = {"list = std.vector< double >()", "float", 0}; Shiboken::setErrorAboutWrongArguments(args, "NatronEngine.FloatNodeCreationProperty", overloads); return -1; } static PyObject* Sbk_FloatNodeCreationPropertyFunc_getValues(PyObject* self) { ::FloatNodeCreationProperty* cppSelf = 0; SBK_UNUSED(cppSelf) if (!Shiboken::Object::isValid(self)) return 0; cppSelf = ((::FloatNodeCreationProperty*)Shiboken::Conversions::cppPointer(SbkNatronEngineTypes[SBK_FLOATNODECREATIONPROPERTY_IDX], (SbkObject*)self)); PyObject* pyResult = 0; // Call function/method { if (!PyErr_Occurred()) { // getValues()const const std::vector<double > & cppResult = const_cast<const ::FloatNodeCreationProperty*>(cppSelf)->getValues(); pyResult = Shiboken::Conversions::copyToPython(SbkNatronEngineTypeConverters[SBK_NATRONENGINE_STD_VECTOR_DOUBLE_IDX], &cppResult); } } if (PyErr_Occurred() || !pyResult) { Py_XDECREF(pyResult); return 0; } return pyResult; } static PyObject* Sbk_FloatNodeCreationPropertyFunc_setValue(PyObject* self, PyObject* args, PyObject* kwds) { ::FloatNodeCreationProperty* cppSelf = 0; SBK_UNUSED(cppSelf) if (!Shiboken::Object::isValid(self)) return 0; cppSelf = ((::FloatNodeCreationProperty*)Shiboken::Conversions::cppPointer(SbkNatronEngineTypes[SBK_FLOATNODECREATIONPROPERTY_IDX], (SbkObject*)self)); int overloadId = -1; PythonToCppFunc pythonToCpp[] = { 0, 0 }; SBK_UNUSED(pythonToCpp) int numNamedArgs = (kwds ? PyDict_Size(kwds) : 0); int numArgs = PyTuple_GET_SIZE(args); PyObject* pyArgs[] = {0, 0}; // invalid argument lengths if (numArgs + numNamedArgs > 2) { PyErr_SetString(PyExc_TypeError, "NatronEngine.FloatNodeCreationProperty.setValue(): too many arguments"); return 0; } else if (numArgs < 1) { PyErr_SetString(PyExc_TypeError, "NatronEngine.FloatNodeCreationProperty.setValue(): not enough arguments"); return 0; } if (!PyArg_ParseTuple(args, "|OO:setValue", &(pyArgs[0]), &(pyArgs[1]))) return 0; // Overloaded function decisor // 0: setValue(double,int) if ((pythonToCpp[0] = Shiboken::Conversions::isPythonToCppConvertible(Shiboken::Conversions::PrimitiveTypeConverter<double>(), (pyArgs[0])))) { if (numArgs == 1) { overloadId = 0; // setValue(double,int) } else if ((pythonToCpp[1] = Shiboken::Conversions::isPythonToCppConvertible(Shiboken::Conversions::PrimitiveTypeConverter<int>(), (pyArgs[1])))) { overloadId = 0; // setValue(double,int) } } // Function signature not found. if (overloadId == -1) goto Sbk_FloatNodeCreationPropertyFunc_setValue_TypeError; // Call function/method { if (kwds) { PyObject* value = PyDict_GetItemString(kwds, "index"); if (value && pyArgs[1]) { PyErr_SetString(PyExc_TypeError, "NatronEngine.FloatNodeCreationProperty.setValue(): got multiple values for keyword argument 'index'."); return 0; } else if (value) { pyArgs[1] = value; if (!(pythonToCpp[1] = Shiboken::Conversions::isPythonToCppConvertible(Shiboken::Conversions::PrimitiveTypeConverter<int>(), (pyArgs[1])))) goto Sbk_FloatNodeCreationPropertyFunc_setValue_TypeError; } } double cppArg0; pythonToCpp[0](pyArgs[0], &cppArg0); int cppArg1 = 0; if (pythonToCpp[1]) pythonToCpp[1](pyArgs[1], &cppArg1); if (!PyErr_Occurred()) { // setValue(double,int) cppSelf->setValue(cppArg0, cppArg1); } } if (PyErr_Occurred()) { return 0; } Py_RETURN_NONE; Sbk_FloatNodeCreationPropertyFunc_setValue_TypeError: const char* overloads[] = {"float, int = 0", 0}; Shiboken::setErrorAboutWrongArguments(args, "NatronEngine.FloatNodeCreationProperty.setValue", overloads); return 0; } static PyMethodDef Sbk_FloatNodeCreationProperty_methods[] = { {"getValues", (PyCFunction)Sbk_FloatNodeCreationPropertyFunc_getValues, METH_NOARGS}, {"setValue", (PyCFunction)Sbk_FloatNodeCreationPropertyFunc_setValue, METH_VARARGS|METH_KEYWORDS}, {0} // Sentinel }; } // extern "C" static int Sbk_FloatNodeCreationProperty_traverse(PyObject* self, visitproc visit, void* arg) { return reinterpret_cast<PyTypeObject*>(&SbkObject_Type)->tp_traverse(self, visit, arg); } static int Sbk_FloatNodeCreationProperty_clear(PyObject* self) { return reinterpret_cast<PyTypeObject*>(&SbkObject_Type)->tp_clear(self); } // Class Definition ----------------------------------------------- extern "C" { static SbkObjectType Sbk_FloatNodeCreationProperty_Type = { { { PyVarObject_HEAD_INIT(&SbkObjectType_Type, 0) /*tp_name*/ "NatronEngine.FloatNodeCreationProperty", /*tp_basicsize*/ sizeof(SbkObject), /*tp_itemsize*/ 0, /*tp_dealloc*/ &SbkDeallocWrapper, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ 0, /*tp_flags*/ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_GC, /*tp_doc*/ 0, /*tp_traverse*/ Sbk_FloatNodeCreationProperty_traverse, /*tp_clear*/ Sbk_FloatNodeCreationProperty_clear, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ 0, /*tp_methods*/ Sbk_FloatNodeCreationProperty_methods, /*tp_members*/ 0, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ 0, /*tp_init*/ Sbk_FloatNodeCreationProperty_Init, /*tp_alloc*/ 0, /*tp_new*/ SbkObjectTpNew, /*tp_free*/ 0, /*tp_is_gc*/ 0, /*tp_bases*/ 0, /*tp_mro*/ 0, /*tp_cache*/ 0, /*tp_subclasses*/ 0, /*tp_weaklist*/ 0 }, }, /*priv_data*/ 0 }; } //extern static void* Sbk_FloatNodeCreationProperty_typeDiscovery(void* cptr, SbkObjectType* instanceType) { if (instanceType == reinterpret_cast<SbkObjectType*>(Shiboken::SbkType< ::NodeCreationProperty >())) return dynamic_cast< ::FloatNodeCreationProperty*>(reinterpret_cast< ::NodeCreationProperty*>(cptr)); return 0; } // Type conversion functions. // Python to C++ pointer conversion - returns the C++ object of the Python wrapper (keeps object identity). static void FloatNodeCreationProperty_PythonToCpp_FloatNodeCreationProperty_PTR(PyObject* pyIn, void* cppOut) { Shiboken::Conversions::pythonToCppPointer(&Sbk_FloatNodeCreationProperty_Type, pyIn, cppOut); } static PythonToCppFunc is_FloatNodeCreationProperty_PythonToCpp_FloatNodeCreationProperty_PTR_Convertible(PyObject* pyIn) { if (pyIn == Py_None) return Shiboken::Conversions::nonePythonToCppNullPtr; if (PyObject_TypeCheck(pyIn, (PyTypeObject*)&Sbk_FloatNodeCreationProperty_Type)) return FloatNodeCreationProperty_PythonToCpp_FloatNodeCreationProperty_PTR; return 0; } // C++ to Python pointer conversion - tries to find the Python wrapper for the C++ object (keeps object identity). static PyObject* FloatNodeCreationProperty_PTR_CppToPython_FloatNodeCreationProperty(const void* cppIn) { PyObject* pyOut = (PyObject*)Shiboken::BindingManager::instance().retrieveWrapper(cppIn); if (pyOut) { Py_INCREF(pyOut); return pyOut; } const char* typeName = typeid(*((::FloatNodeCreationProperty*)cppIn)).name(); return Shiboken::Object::newObject(&Sbk_FloatNodeCreationProperty_Type, const_cast<void*>(cppIn), false, false, typeName); } void init_FloatNodeCreationProperty(PyObject* module) { SbkNatronEngineTypes[SBK_FLOATNODECREATIONPROPERTY_IDX] = reinterpret_cast<PyTypeObject*>(&Sbk_FloatNodeCreationProperty_Type); if (!Shiboken::ObjectType::introduceWrapperType(module, "FloatNodeCreationProperty", "FloatNodeCreationProperty*", &Sbk_FloatNodeCreationProperty_Type, &Shiboken::callCppDestructor< ::FloatNodeCreationProperty >, (SbkObjectType*)SbkNatronEngineTypes[SBK_NODECREATIONPROPERTY_IDX])) { return; } // Register Converter SbkConverter* converter = Shiboken::Conversions::createConverter(&Sbk_FloatNodeCreationProperty_Type, FloatNodeCreationProperty_PythonToCpp_FloatNodeCreationProperty_PTR, is_FloatNodeCreationProperty_PythonToCpp_FloatNodeCreationProperty_PTR_Convertible, FloatNodeCreationProperty_PTR_CppToPython_FloatNodeCreationProperty); Shiboken::Conversions::registerConverterName(converter, "FloatNodeCreationProperty"); Shiboken::Conversions::registerConverterName(converter, "FloatNodeCreationProperty*"); Shiboken::Conversions::registerConverterName(converter, "FloatNodeCreationProperty&"); Shiboken::Conversions::registerConverterName(converter, typeid(::FloatNodeCreationProperty).name()); Shiboken::Conversions::registerConverterName(converter, typeid(::FloatNodeCreationPropertyWrapper).name()); Shiboken::ObjectType::setTypeDiscoveryFunctionV2(&Sbk_FloatNodeCreationProperty_Type, &Sbk_FloatNodeCreationProperty_typeDiscovery); FloatNodeCreationPropertyWrapper::pysideInitQtMetaTypes(); }
{ "pile_set_name": "Github" }
using CleanArchitecture.Web; using System.Net.Http; using System.Threading.Tasks; using Xunit; namespace CleanArchitecture.FunctionalTests { public class HomeControllerIndex : IClassFixture<CustomWebApplicationFactory<Startup>> { private readonly HttpClient _client; public HomeControllerIndex(CustomWebApplicationFactory<Startup> factory) { _client = factory.CreateClient(); } [Fact] public async Task ReturnsViewWithCorrectMessage() { HttpResponseMessage response = await _client.GetAsync("/"); response.EnsureSuccessStatusCode(); string stringResponse = await response.Content.ReadAsStringAsync(); Assert.Contains("CleanArchitecture.Web", stringResponse); } } }
{ "pile_set_name": "Github" }
"use strict";var exports=module.exports={};var isObject = require('./isObject.js'); /** * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` if suitable for strict * equality comparisons, else `false`. */ function isStrictComparable(value) { return value === value && !isObject(value); } module.exports = isStrictComparable;
{ "pile_set_name": "Github" }
(* *********************************************************************) (* *) (* The Compcert verified compiler *) (* *) (* Xavier Leroy, INRIA Paris-Rocquencourt *) (* *) (* Copyright Institut National de Recherche en Informatique et en *) (* Automatique. All rights reserved. This file is distributed *) (* under the terms of the INRIA Non-Commercial License Agreement. *) (* *) (* *********************************************************************) (** Postorder renumbering of RTL control-flow graphs. *) Require Import Coqlib Maps Postorder. Require Import AST Linking. Require Import Values Memory Globalenvs Events Smallstep. Require Import Op Registers RTL Renumber. Definition match_prog (p tp: RTL.program) := match_program (fun ctx f tf => tf = transf_fundef f) eq p tp. Lemma transf_program_match: forall p, match_prog p (transf_program p). Proof. intros. eapply match_transform_program; eauto. Qed. Section PRESERVATION. Variables prog tprog: program. Hypothesis TRANSL: match_prog prog tprog. Let ge := Genv.globalenv prog. Let tge := Genv.globalenv tprog. Lemma functions_translated: forall v f, Genv.find_funct ge v = Some f -> Genv.find_funct tge v = Some (transf_fundef f). Proof (Genv.find_funct_transf TRANSL). Lemma function_ptr_translated: forall v f, Genv.find_funct_ptr ge v = Some f -> Genv.find_funct_ptr tge v = Some (transf_fundef f). Proof (Genv.find_funct_ptr_transf TRANSL). Lemma symbols_preserved: forall id, Genv.find_symbol tge id = Genv.find_symbol ge id. Proof (Genv.find_symbol_transf TRANSL). Lemma senv_preserved: Senv.equiv ge tge. Proof (Genv.senv_transf TRANSL). Lemma sig_preserved: forall f, funsig (transf_fundef f) = funsig f. Proof. destruct f; reflexivity. Qed. Lemma find_function_translated: forall ros rs fd, find_function ge ros rs = Some fd -> find_function tge ros rs = Some (transf_fundef fd). Proof. unfold find_function; intros. destruct ros as [r|id]. eapply functions_translated; eauto. rewrite symbols_preserved. destruct (Genv.find_symbol ge id); try congruence. eapply function_ptr_translated; eauto. Qed. (** Effect of an injective renaming of nodes on a CFG. *) Section RENUMBER. Variable f: PTree.t positive. Hypothesis f_inj: forall x1 x2 y, f!x1 = Some y -> f!x2 = Some y -> x1 = x2. Lemma renum_cfg_nodes: forall c x y i, c!x = Some i -> f!x = Some y -> (renum_cfg f c)!y = Some(renum_instr f i). Proof. set (P := fun (c c': code) => forall x y i, c!x = Some i -> f!x = Some y -> c'!y = Some(renum_instr f i)). intros c0. change (P c0 (renum_cfg f c0)). unfold renum_cfg. apply PTree_Properties.fold_rec; unfold P; intros. (* extensionality *) eapply H0; eauto. rewrite H; auto. (* base *) rewrite PTree.gempty in H; congruence. (* induction *) rewrite PTree.gsspec in H2. unfold renum_node. destruct (peq x k). inv H2. rewrite H3. apply PTree.gss. destruct f!k as [y'|] eqn:?. rewrite PTree.gso. eauto. red; intros; subst y'. elim n. eapply f_inj; eauto. eauto. Qed. End RENUMBER. Definition pnum (f: function) := postorder (successors_map f) f.(fn_entrypoint). Definition reach (f: function) (pc: node) := reachable (successors_map f) f.(fn_entrypoint) pc. Lemma transf_function_at: forall f pc i, f.(fn_code)!pc = Some i -> reach f pc -> (transf_function f).(fn_code)!(renum_pc (pnum f) pc) = Some(renum_instr (pnum f) i). Proof. intros. destruct (postorder_correct (successors_map f) f.(fn_entrypoint)) as [A B]. fold (pnum f) in *. unfold renum_pc. destruct (pnum f)! pc as [pc'|] eqn:?. simpl. eapply renum_cfg_nodes; eauto. elim (B pc); auto. unfold successors_map. rewrite PTree.gmap1. rewrite H. simpl. congruence. Qed. Ltac TR_AT := match goal with | [ A: (fn_code _)!_ = Some _ , B: reach _ _ |- _ ] => generalize (transf_function_at _ _ _ A B); simpl renum_instr; intros end. Lemma reach_succ: forall f pc i s, f.(fn_code)!pc = Some i -> In s (successors_instr i) -> reach f pc -> reach f s. Proof. unfold reach; intros. econstructor; eauto. unfold successors_map. rewrite PTree.gmap1. rewrite H. auto. Qed. Inductive match_frames: RTL.stackframe -> RTL.stackframe -> Prop := | match_frames_intro: forall res f sp pc rs (REACH: reach f pc), match_frames (Stackframe res f sp pc rs) (Stackframe res (transf_function f) sp (renum_pc (pnum f) pc) rs). Inductive match_states: RTL.state -> RTL.state -> Prop := | match_regular_states: forall stk f sp pc rs m stk' (STACKS: list_forall2 match_frames stk stk') (REACH: reach f pc), match_states (State stk f sp pc rs m) (State stk' (transf_function f) sp (renum_pc (pnum f) pc) rs m) | match_callstates: forall stk f args m stk' (STACKS: list_forall2 match_frames stk stk'), match_states (Callstate stk f args m) (Callstate stk' (transf_fundef f) args m) | match_returnstates: forall stk v m stk' (STACKS: list_forall2 match_frames stk stk'), match_states (Returnstate stk v m) (Returnstate stk' v m). Lemma step_simulation: forall S1 t S2, RTL.step ge S1 t S2 -> forall S1', match_states S1 S1' -> exists S2', RTL.step tge S1' t S2' /\ match_states S2 S2'. Proof. induction 1; intros S1' MS; inv MS; try TR_AT. (* nop *) econstructor; split. eapply exec_Inop; eauto. constructor; auto. eapply reach_succ; eauto. simpl; auto. (* op *) econstructor; split. eapply exec_Iop; eauto. instantiate (1 := v). rewrite <- H0. apply eval_operation_preserved. exact symbols_preserved. constructor; auto. eapply reach_succ; eauto. simpl; auto. (* load *) econstructor; split. assert (eval_addressing tge sp addr rs ## args = Some a). rewrite <- H0. apply eval_addressing_preserved. exact symbols_preserved. eapply exec_Iload; eauto. constructor; auto. eapply reach_succ; eauto. simpl; auto. (* store *) econstructor; split. assert (eval_addressing tge sp addr rs ## args = Some a). rewrite <- H0. apply eval_addressing_preserved. exact symbols_preserved. eapply exec_Istore; eauto. constructor; auto. eapply reach_succ; eauto. simpl; auto. (* call *) econstructor; split. eapply exec_Icall with (fd := transf_fundef fd); eauto. eapply find_function_translated; eauto. apply sig_preserved. constructor. constructor; auto. constructor. eapply reach_succ; eauto. simpl; auto. (* tailcall *) econstructor; split. eapply exec_Itailcall with (fd := transf_fundef fd); eauto. eapply find_function_translated; eauto. apply sig_preserved. constructor. auto. (* builtin *) econstructor; split. eapply exec_Ibuiltin; eauto. eapply eval_builtin_args_preserved with (ge1 := ge); eauto. exact symbols_preserved. eapply external_call_symbols_preserved; eauto. apply senv_preserved. constructor; auto. eapply reach_succ; eauto. simpl; auto. (* cond *) econstructor; split. eapply exec_Icond; eauto. replace (if b then renum_pc (pnum f) ifso else renum_pc (pnum f) ifnot) with (renum_pc (pnum f) (if b then ifso else ifnot)). constructor; auto. eapply reach_succ; eauto. simpl. destruct b; auto. destruct b; auto. (* jumptbl *) econstructor; split. eapply exec_Ijumptable; eauto. rewrite list_nth_z_map. rewrite H1. simpl; eauto. constructor; auto. eapply reach_succ; eauto. simpl. eapply list_nth_z_in; eauto. (* return *) econstructor; split. eapply exec_Ireturn; eauto. constructor; auto. (* internal function *) simpl. econstructor; split. eapply exec_function_internal; eauto. constructor; auto. unfold reach. constructor. (* external function *) econstructor; split. eapply exec_function_external; eauto. eapply external_call_symbols_preserved; eauto. apply senv_preserved. constructor; auto. (* return *) inv STACKS. inv H1. econstructor; split. eapply exec_return; eauto. constructor; auto. Qed. Lemma transf_initial_states: forall S1, RTL.initial_state prog S1 -> exists S2, RTL.initial_state tprog S2 /\ match_states S1 S2. Proof. intros. inv H. econstructor; split. econstructor. eapply (Genv.init_mem_transf TRANSL); eauto. rewrite symbols_preserved. rewrite (match_program_main TRANSL). eauto. eapply function_ptr_translated; eauto. rewrite <- H3; apply sig_preserved. constructor. constructor. Qed. Lemma transf_final_states: forall S1 S2 r, match_states S1 S2 -> RTL.final_state S1 r -> RTL.final_state S2 r. Proof. intros. inv H0. inv H. inv STACKS. constructor. Qed. Theorem transf_program_correct: forward_simulation (RTL.semantics prog) (RTL.semantics tprog). Proof. eapply forward_simulation_step. apply senv_preserved. eexact transf_initial_states. eexact transf_final_states. exact step_simulation. Qed. End PRESERVATION.
{ "pile_set_name": "Github" }
# Copyright 2018 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import("//third_party/closure_compiler/compile_js.gni") js_type_check("closure_compile") { deps = [ ":app_installer", ":cws_webview_client", ":cws_widget_container", ":cws_widget_container_error_dialog", ":cws_widget_container_platform_delegate", ] } js_library("app_installer") { deps = [ ":cws_widget_container_platform_delegate" ] } js_library("cws_widget_container") { deps = [ ":app_installer", ":cws_webview_client", ":cws_widget_container_error_dialog", ] } js_library("cws_widget_container_error_dialog") { deps = [ "//ui/webui/resources/js/cr/ui:dialogs" ] } js_library("cws_widget_container_platform_delegate") { } js_library("cws_webview_client") { deps = [ ":cws_widget_container_platform_delegate", "//ui/webui/resources/js:cr", "//ui/webui/resources/js/cr:event_target", ] externs_list = [ "$externs_path/chrome_extensions.js", "$externs_path/webview_tag.js", ] }
{ "pile_set_name": "Github" }
package test type typeForTest map[string]*[4]string
{ "pile_set_name": "Github" }
#!/usr/bin/perl =head1 NAME Iplogs =cut =head1 DESCRIPTION unit test for Iplogs =cut use strict; use warnings; use DateTime; use DateTime::Format::Strptime; use lib '/usr/local/pf/lib'; use pf::ip4log; use pf::dal::ip4log; use pf::dal::ip4log_history; use pf::dal::ip4log_archive; BEGIN { #include test libs use lib qw(/usr/local/pf/t); #Module for overriding configuration paths use setup_test_config; } use Test::More tests => 34; use Test::Mojo; use Test::NoWarnings; my $t = Test::Mojo->new('pf::UnifiedApi'); #pre-cleanup pf::dal::ip4log->remove_items(); pf::dal::ip4log_history->remove_items(); pf::dal::ip4log_archive->remove_items(); #run unittest on empty dB $t->get_ok('/api/v1/ip4logs' => json => { }) ->json_is('/items',[]) ->status_is(200); #setup data my $ip = '0.0.0.1'; my $mac = '00:01:02:03:04:05'; my $escaped_mac = '00%3A01%3A02%3A03%3A04%3A05'; my $lease_length = 120; my $dt_format = DateTime::Format::Strptime->new(pattern => '%Y-%m-%d %H:%M:%S'); my $dt_start = DateTime->now(time_zone=>'local'); my $dt_end = DateTime->now(time_zone=>'local')->add(seconds => $lease_length); #insert good data my $status = pf::ip4log::open($ip, $mac, $lease_length); #run unittest on single dB entry $t->get_ok('/api/v1/ip4logs') ->status_is(200) ->json_is('/items/0/mac',$mac) ->json_is('/items/0/ip',$ip) ->json_has('/items/0/start_time') ->json_has('/items/0/end_time') ; #run unittest on list by mac $t->get_ok('/api/v1/ip4logs/open/'.$mac) ->status_is(200) ->json_is('/item/ip',$ip) ->json_is('/item/mac',$mac) ->json_has('/item/start_time') ->json_has('/item/end_time') ; #run unittest on list by mac $t->get_ok('/api/v1/ip4logs/open/'.$escaped_mac) ->status_is(200) ->json_is('/item/ip',$ip) ->json_is('/item/mac',$mac) ->json_has('/item/start_time') ->json_has('/item/end_time') ; #run unittest on history list by mac $t->get_ok('/api/v1/ip4logs/history/'.$mac => json => { }) ->status_is(200) ->json_is('/items/0/ip',$ip) ->json_is('/items/0/mac',$mac) ->json_has('/items/0/start_time') ->json_has('/items/0/end_time') ; #run unittest on archive list by mac $t->get_ok('/api/v1/ip4logs/archive/'.$mac => json => { }) ->json_is('/items/0/ip',$ip) ->json_is('/items/0/mac',$mac) ->json_has('/items/0/start_time') ->json_has('/items/0/end_time') ->status_is(200) ; #debug output #my $j = $t->tx->res->json; #use Data::Dumper;print Dumper($j); #post-cleanup pf::dal::ip4log->remove_items(); pf::dal::ip4log_history->remove_items(); pf::dal::ip4log_archive->remove_items(); =head1 AUTHOR Inverse inc. <info@inverse.ca> =head1 COPYRIGHT Copyright (C) 2005-2020 Inverse inc. =head1 LICENSE 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. =cut 1;
{ "pile_set_name": "Github" }
module("Keyboard"); (function () { test("Document keypress event binding", function () { /* Initialization */ $('#t').append('<img id="test-img" src="data/elephant.jpg" />'); stop(); var keyPressed = false; $(document).bind('keydown keypress', function () { keyPressed = true; }); $('#test-img').imgAreaSelect({ onInit: function (img, selection) { $(document).keydown(); $(document).keypress(); ok(keyPressed, 'Check if the original document keypress/keydown ' + 'event handler is called after plugin initialization'); $('#test-img').imgAreaSelect({ remove: true }); testCleanup(); start(); } }); }); })();
{ "pile_set_name": "Github" }
// Copyright (c) 2017 The Chromium Embedded Framework Authors. All rights // reserved. Use of this source code is governed by a BSD-style license that // can be found in the LICENSE file. // // --------------------------------------------------------------------------- // // This file was generated by the CEF translator tool. If making changes by // hand only do so within the body of existing method and function // implementations. See the translator.README.txt file in the tools directory // for more information. // #include "libcef_dll/cpptoc/views/browser_view_cpptoc.h" #include "libcef_dll/cpptoc/views/button_cpptoc.h" #include "libcef_dll/cpptoc/views/label_button_cpptoc.h" #include "libcef_dll/cpptoc/views/menu_button_cpptoc.h" #include "libcef_dll/cpptoc/views/panel_cpptoc.h" #include "libcef_dll/cpptoc/views/scroll_view_cpptoc.h" #include "libcef_dll/cpptoc/views/textfield_cpptoc.h" #include "libcef_dll/cpptoc/views/view_cpptoc.h" #include "libcef_dll/cpptoc/views/window_cpptoc.h" #include "libcef_dll/ctocpp/views/view_delegate_ctocpp.h" namespace { // MEMBER FUNCTIONS - Body may be edited by hand. cef_label_button_t* CEF_CALLBACK button_as_label_button( struct _cef_button_t* self) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return NULL; // Execute CefRefPtr<CefLabelButton> _retval = CefButtonCppToC::Get(self)->AsLabelButton( ); // Return type: refptr_same return CefLabelButtonCppToC::Wrap(_retval); } void CEF_CALLBACK button_set_state(struct _cef_button_t* self, cef_button_state_t state) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return; // Execute CefButtonCppToC::Get(self)->SetState( state); } cef_button_state_t CEF_CALLBACK button_get_state(struct _cef_button_t* self) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return CEF_BUTTON_STATE_NORMAL; // Execute cef_button_state_t _retval = CefButtonCppToC::Get(self)->GetState(); // Return type: simple return _retval; } void CEF_CALLBACK button_set_ink_drop_enabled(struct _cef_button_t* self, int enabled) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return; // Execute CefButtonCppToC::Get(self)->SetInkDropEnabled( enabled?true:false); } void CEF_CALLBACK button_set_tooltip_text(struct _cef_button_t* self, const cef_string_t* tooltip_text) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return; // Verify param: tooltip_text; type: string_byref_const DCHECK(tooltip_text); if (!tooltip_text) return; // Execute CefButtonCppToC::Get(self)->SetTooltipText( CefString(tooltip_text)); } void CEF_CALLBACK button_set_accessible_name(struct _cef_button_t* self, const cef_string_t* name) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return; // Verify param: name; type: string_byref_const DCHECK(name); if (!name) return; // Execute CefButtonCppToC::Get(self)->SetAccessibleName( CefString(name)); } cef_browser_view_t* CEF_CALLBACK button_as_browser_view( struct _cef_view_t* self) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return NULL; // Execute CefRefPtr<CefBrowserView> _retval = CefButtonCppToC::Get( reinterpret_cast<cef_button_t*>(self))->AsBrowserView(); // Return type: refptr_same return CefBrowserViewCppToC::Wrap(_retval); } cef_button_t* CEF_CALLBACK button_as_button(struct _cef_view_t* self) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return NULL; // Execute CefRefPtr<CefButton> _retval = CefButtonCppToC::Get( reinterpret_cast<cef_button_t*>(self))->AsButton(); // Return type: refptr_same return CefButtonCppToC::Wrap(_retval); } cef_panel_t* CEF_CALLBACK button_as_panel(struct _cef_view_t* self) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return NULL; // Execute CefRefPtr<CefPanel> _retval = CefButtonCppToC::Get( reinterpret_cast<cef_button_t*>(self))->AsPanel(); // Return type: refptr_same return CefPanelCppToC::Wrap(_retval); } cef_scroll_view_t* CEF_CALLBACK button_as_scroll_view( struct _cef_view_t* self) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return NULL; // Execute CefRefPtr<CefScrollView> _retval = CefButtonCppToC::Get( reinterpret_cast<cef_button_t*>(self))->AsScrollView(); // Return type: refptr_same return CefScrollViewCppToC::Wrap(_retval); } cef_textfield_t* CEF_CALLBACK button_as_textfield(struct _cef_view_t* self) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return NULL; // Execute CefRefPtr<CefTextfield> _retval = CefButtonCppToC::Get( reinterpret_cast<cef_button_t*>(self))->AsTextfield(); // Return type: refptr_same return CefTextfieldCppToC::Wrap(_retval); } cef_string_userfree_t CEF_CALLBACK button_get_type_string( struct _cef_view_t* self) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return NULL; // Execute CefString _retval = CefButtonCppToC::Get(reinterpret_cast<cef_button_t*>( self))->GetTypeString(); // Return type: string return _retval.DetachToUserFree(); } cef_string_userfree_t CEF_CALLBACK button_to_string(struct _cef_view_t* self, int include_children) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return NULL; // Execute CefString _retval = CefButtonCppToC::Get(reinterpret_cast<cef_button_t*>( self))->ToString( include_children?true:false); // Return type: string return _retval.DetachToUserFree(); } int CEF_CALLBACK button_is_valid(struct _cef_view_t* self) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return 0; // Execute bool _retval = CefButtonCppToC::Get(reinterpret_cast<cef_button_t*>( self))->IsValid(); // Return type: bool return _retval; } int CEF_CALLBACK button_is_attached(struct _cef_view_t* self) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return 0; // Execute bool _retval = CefButtonCppToC::Get(reinterpret_cast<cef_button_t*>( self))->IsAttached(); // Return type: bool return _retval; } int CEF_CALLBACK button_is_same(struct _cef_view_t* self, struct _cef_view_t* that) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return 0; // Verify param: that; type: refptr_same DCHECK(that); if (!that) return 0; // Execute bool _retval = CefButtonCppToC::Get(reinterpret_cast<cef_button_t*>( self))->IsSame( CefViewCppToC::Unwrap(that)); // Return type: bool return _retval; } struct _cef_view_delegate_t* CEF_CALLBACK button_get_delegate( struct _cef_view_t* self) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return NULL; // Execute CefRefPtr<CefViewDelegate> _retval = CefButtonCppToC::Get( reinterpret_cast<cef_button_t*>(self))->GetDelegate(); // Return type: refptr_diff return CefViewDelegateCToCpp::Unwrap(_retval); } struct _cef_window_t* CEF_CALLBACK button_get_window(struct _cef_view_t* self) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return NULL; // Execute CefRefPtr<CefWindow> _retval = CefButtonCppToC::Get( reinterpret_cast<cef_button_t*>(self))->GetWindow(); // Return type: refptr_same return CefWindowCppToC::Wrap(_retval); } int CEF_CALLBACK button_get_id(struct _cef_view_t* self) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return 0; // Execute int _retval = CefButtonCppToC::Get(reinterpret_cast<cef_button_t*>( self))->GetID(); // Return type: simple return _retval; } void CEF_CALLBACK button_set_id(struct _cef_view_t* self, int id) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return; // Execute CefButtonCppToC::Get(reinterpret_cast<cef_button_t*>(self))->SetID( id); } int CEF_CALLBACK button_get_group_id(struct _cef_view_t* self) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return 0; // Execute int _retval = CefButtonCppToC::Get(reinterpret_cast<cef_button_t*>( self))->GetGroupID(); // Return type: simple return _retval; } void CEF_CALLBACK button_set_group_id(struct _cef_view_t* self, int group_id) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return; // Execute CefButtonCppToC::Get(reinterpret_cast<cef_button_t*>(self))->SetGroupID( group_id); } struct _cef_view_t* CEF_CALLBACK button_get_parent_view( struct _cef_view_t* self) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return NULL; // Execute CefRefPtr<CefView> _retval = CefButtonCppToC::Get( reinterpret_cast<cef_button_t*>(self))->GetParentView(); // Return type: refptr_same return CefViewCppToC::Wrap(_retval); } struct _cef_view_t* CEF_CALLBACK button_get_view_for_id( struct _cef_view_t* self, int id) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return NULL; // Execute CefRefPtr<CefView> _retval = CefButtonCppToC::Get( reinterpret_cast<cef_button_t*>(self))->GetViewForID( id); // Return type: refptr_same return CefViewCppToC::Wrap(_retval); } void CEF_CALLBACK button_set_bounds(struct _cef_view_t* self, const cef_rect_t* bounds) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return; // Verify param: bounds; type: simple_byref_const DCHECK(bounds); if (!bounds) return; // Translate param: bounds; type: simple_byref_const CefRect boundsVal = bounds?*bounds:CefRect(); // Execute CefButtonCppToC::Get(reinterpret_cast<cef_button_t*>(self))->SetBounds( boundsVal); } cef_rect_t CEF_CALLBACK button_get_bounds(struct _cef_view_t* self) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return CefRect(); // Execute cef_rect_t _retval = CefButtonCppToC::Get(reinterpret_cast<cef_button_t*>( self))->GetBounds(); // Return type: simple return _retval; } cef_rect_t CEF_CALLBACK button_get_bounds_in_screen(struct _cef_view_t* self) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return CefRect(); // Execute cef_rect_t _retval = CefButtonCppToC::Get(reinterpret_cast<cef_button_t*>( self))->GetBoundsInScreen(); // Return type: simple return _retval; } void CEF_CALLBACK button_set_size(struct _cef_view_t* self, const cef_size_t* size) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return; // Verify param: size; type: simple_byref_const DCHECK(size); if (!size) return; // Translate param: size; type: simple_byref_const CefSize sizeVal = size?*size:CefSize(); // Execute CefButtonCppToC::Get(reinterpret_cast<cef_button_t*>(self))->SetSize( sizeVal); } cef_size_t CEF_CALLBACK button_get_size(struct _cef_view_t* self) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return CefSize(); // Execute cef_size_t _retval = CefButtonCppToC::Get(reinterpret_cast<cef_button_t*>( self))->GetSize(); // Return type: simple return _retval; } void CEF_CALLBACK button_set_position(struct _cef_view_t* self, const cef_point_t* position) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return; // Verify param: position; type: simple_byref_const DCHECK(position); if (!position) return; // Translate param: position; type: simple_byref_const CefPoint positionVal = position?*position:CefPoint(); // Execute CefButtonCppToC::Get(reinterpret_cast<cef_button_t*>(self))->SetPosition( positionVal); } cef_point_t CEF_CALLBACK button_get_position(struct _cef_view_t* self) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return CefPoint(); // Execute cef_point_t _retval = CefButtonCppToC::Get(reinterpret_cast<cef_button_t*>( self))->GetPosition(); // Return type: simple return _retval; } cef_size_t CEF_CALLBACK button_get_preferred_size(struct _cef_view_t* self) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return CefSize(); // Execute cef_size_t _retval = CefButtonCppToC::Get(reinterpret_cast<cef_button_t*>( self))->GetPreferredSize(); // Return type: simple return _retval; } void CEF_CALLBACK button_size_to_preferred_size(struct _cef_view_t* self) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return; // Execute CefButtonCppToC::Get(reinterpret_cast<cef_button_t*>( self))->SizeToPreferredSize(); } cef_size_t CEF_CALLBACK button_get_minimum_size(struct _cef_view_t* self) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return CefSize(); // Execute cef_size_t _retval = CefButtonCppToC::Get(reinterpret_cast<cef_button_t*>( self))->GetMinimumSize(); // Return type: simple return _retval; } cef_size_t CEF_CALLBACK button_get_maximum_size(struct _cef_view_t* self) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return CefSize(); // Execute cef_size_t _retval = CefButtonCppToC::Get(reinterpret_cast<cef_button_t*>( self))->GetMaximumSize(); // Return type: simple return _retval; } int CEF_CALLBACK button_get_height_for_width(struct _cef_view_t* self, int width) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return 0; // Execute int _retval = CefButtonCppToC::Get(reinterpret_cast<cef_button_t*>( self))->GetHeightForWidth( width); // Return type: simple return _retval; } void CEF_CALLBACK button_invalidate_layout(struct _cef_view_t* self) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return; // Execute CefButtonCppToC::Get(reinterpret_cast<cef_button_t*>(self))->InvalidateLayout( ); } void CEF_CALLBACK button_set_visible(struct _cef_view_t* self, int visible) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return; // Execute CefButtonCppToC::Get(reinterpret_cast<cef_button_t*>(self))->SetVisible( visible?true:false); } int CEF_CALLBACK button_is_visible(struct _cef_view_t* self) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return 0; // Execute bool _retval = CefButtonCppToC::Get(reinterpret_cast<cef_button_t*>( self))->IsVisible(); // Return type: bool return _retval; } int CEF_CALLBACK button_is_drawn(struct _cef_view_t* self) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return 0; // Execute bool _retval = CefButtonCppToC::Get(reinterpret_cast<cef_button_t*>( self))->IsDrawn(); // Return type: bool return _retval; } void CEF_CALLBACK button_set_enabled(struct _cef_view_t* self, int enabled) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return; // Execute CefButtonCppToC::Get(reinterpret_cast<cef_button_t*>(self))->SetEnabled( enabled?true:false); } int CEF_CALLBACK button_is_enabled(struct _cef_view_t* self) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return 0; // Execute bool _retval = CefButtonCppToC::Get(reinterpret_cast<cef_button_t*>( self))->IsEnabled(); // Return type: bool return _retval; } void CEF_CALLBACK button_set_focusable(struct _cef_view_t* self, int focusable) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return; // Execute CefButtonCppToC::Get(reinterpret_cast<cef_button_t*>(self))->SetFocusable( focusable?true:false); } int CEF_CALLBACK button_is_focusable(struct _cef_view_t* self) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return 0; // Execute bool _retval = CefButtonCppToC::Get(reinterpret_cast<cef_button_t*>( self))->IsFocusable(); // Return type: bool return _retval; } int CEF_CALLBACK button_is_accessibility_focusable(struct _cef_view_t* self) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return 0; // Execute bool _retval = CefButtonCppToC::Get(reinterpret_cast<cef_button_t*>( self))->IsAccessibilityFocusable(); // Return type: bool return _retval; } void CEF_CALLBACK button_request_focus(struct _cef_view_t* self) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return; // Execute CefButtonCppToC::Get(reinterpret_cast<cef_button_t*>(self))->RequestFocus(); } void CEF_CALLBACK button_set_background_color(struct _cef_view_t* self, cef_color_t color) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return; // Execute CefButtonCppToC::Get(reinterpret_cast<cef_button_t*>( self))->SetBackgroundColor( color); } cef_color_t CEF_CALLBACK button_get_background_color(struct _cef_view_t* self) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return 0; // Execute cef_color_t _retval = CefButtonCppToC::Get(reinterpret_cast<cef_button_t*>( self))->GetBackgroundColor(); // Return type: simple return _retval; } int CEF_CALLBACK button_convert_point_to_screen(struct _cef_view_t* self, cef_point_t* point) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return 0; // Verify param: point; type: simple_byref DCHECK(point); if (!point) return 0; // Translate param: point; type: simple_byref CefPoint pointVal = point?*point:CefPoint(); // Execute bool _retval = CefButtonCppToC::Get(reinterpret_cast<cef_button_t*>( self))->ConvertPointToScreen( pointVal); // Restore param: point; type: simple_byref if (point) *point = pointVal; // Return type: bool return _retval; } int CEF_CALLBACK button_convert_point_from_screen(struct _cef_view_t* self, cef_point_t* point) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return 0; // Verify param: point; type: simple_byref DCHECK(point); if (!point) return 0; // Translate param: point; type: simple_byref CefPoint pointVal = point?*point:CefPoint(); // Execute bool _retval = CefButtonCppToC::Get(reinterpret_cast<cef_button_t*>( self))->ConvertPointFromScreen( pointVal); // Restore param: point; type: simple_byref if (point) *point = pointVal; // Return type: bool return _retval; } int CEF_CALLBACK button_convert_point_to_window(struct _cef_view_t* self, cef_point_t* point) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return 0; // Verify param: point; type: simple_byref DCHECK(point); if (!point) return 0; // Translate param: point; type: simple_byref CefPoint pointVal = point?*point:CefPoint(); // Execute bool _retval = CefButtonCppToC::Get(reinterpret_cast<cef_button_t*>( self))->ConvertPointToWindow( pointVal); // Restore param: point; type: simple_byref if (point) *point = pointVal; // Return type: bool return _retval; } int CEF_CALLBACK button_convert_point_from_window(struct _cef_view_t* self, cef_point_t* point) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return 0; // Verify param: point; type: simple_byref DCHECK(point); if (!point) return 0; // Translate param: point; type: simple_byref CefPoint pointVal = point?*point:CefPoint(); // Execute bool _retval = CefButtonCppToC::Get(reinterpret_cast<cef_button_t*>( self))->ConvertPointFromWindow( pointVal); // Restore param: point; type: simple_byref if (point) *point = pointVal; // Return type: bool return _retval; } int CEF_CALLBACK button_convert_point_to_view(struct _cef_view_t* self, struct _cef_view_t* view, cef_point_t* point) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return 0; // Verify param: view; type: refptr_same DCHECK(view); if (!view) return 0; // Verify param: point; type: simple_byref DCHECK(point); if (!point) return 0; // Translate param: point; type: simple_byref CefPoint pointVal = point?*point:CefPoint(); // Execute bool _retval = CefButtonCppToC::Get(reinterpret_cast<cef_button_t*>( self))->ConvertPointToView( CefViewCppToC::Unwrap(view), pointVal); // Restore param: point; type: simple_byref if (point) *point = pointVal; // Return type: bool return _retval; } int CEF_CALLBACK button_convert_point_from_view(struct _cef_view_t* self, struct _cef_view_t* view, cef_point_t* point) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING DCHECK(self); if (!self) return 0; // Verify param: view; type: refptr_same DCHECK(view); if (!view) return 0; // Verify param: point; type: simple_byref DCHECK(point); if (!point) return 0; // Translate param: point; type: simple_byref CefPoint pointVal = point?*point:CefPoint(); // Execute bool _retval = CefButtonCppToC::Get(reinterpret_cast<cef_button_t*>( self))->ConvertPointFromView( CefViewCppToC::Unwrap(view), pointVal); // Restore param: point; type: simple_byref if (point) *point = pointVal; // Return type: bool return _retval; } } // namespace // CONSTRUCTOR - Do not edit by hand. CefButtonCppToC::CefButtonCppToC() { GetStruct()->as_label_button = button_as_label_button; GetStruct()->set_state = button_set_state; GetStruct()->get_state = button_get_state; GetStruct()->set_ink_drop_enabled = button_set_ink_drop_enabled; GetStruct()->set_tooltip_text = button_set_tooltip_text; GetStruct()->set_accessible_name = button_set_accessible_name; GetStruct()->base.as_browser_view = button_as_browser_view; GetStruct()->base.as_button = button_as_button; GetStruct()->base.as_panel = button_as_panel; GetStruct()->base.as_scroll_view = button_as_scroll_view; GetStruct()->base.as_textfield = button_as_textfield; GetStruct()->base.get_type_string = button_get_type_string; GetStruct()->base.to_string = button_to_string; GetStruct()->base.is_valid = button_is_valid; GetStruct()->base.is_attached = button_is_attached; GetStruct()->base.is_same = button_is_same; GetStruct()->base.get_delegate = button_get_delegate; GetStruct()->base.get_window = button_get_window; GetStruct()->base.get_id = button_get_id; GetStruct()->base.set_id = button_set_id; GetStruct()->base.get_group_id = button_get_group_id; GetStruct()->base.set_group_id = button_set_group_id; GetStruct()->base.get_parent_view = button_get_parent_view; GetStruct()->base.get_view_for_id = button_get_view_for_id; GetStruct()->base.set_bounds = button_set_bounds; GetStruct()->base.get_bounds = button_get_bounds; GetStruct()->base.get_bounds_in_screen = button_get_bounds_in_screen; GetStruct()->base.set_size = button_set_size; GetStruct()->base.get_size = button_get_size; GetStruct()->base.set_position = button_set_position; GetStruct()->base.get_position = button_get_position; GetStruct()->base.get_preferred_size = button_get_preferred_size; GetStruct()->base.size_to_preferred_size = button_size_to_preferred_size; GetStruct()->base.get_minimum_size = button_get_minimum_size; GetStruct()->base.get_maximum_size = button_get_maximum_size; GetStruct()->base.get_height_for_width = button_get_height_for_width; GetStruct()->base.invalidate_layout = button_invalidate_layout; GetStruct()->base.set_visible = button_set_visible; GetStruct()->base.is_visible = button_is_visible; GetStruct()->base.is_drawn = button_is_drawn; GetStruct()->base.set_enabled = button_set_enabled; GetStruct()->base.is_enabled = button_is_enabled; GetStruct()->base.set_focusable = button_set_focusable; GetStruct()->base.is_focusable = button_is_focusable; GetStruct()->base.is_accessibility_focusable = button_is_accessibility_focusable; GetStruct()->base.request_focus = button_request_focus; GetStruct()->base.set_background_color = button_set_background_color; GetStruct()->base.get_background_color = button_get_background_color; GetStruct()->base.convert_point_to_screen = button_convert_point_to_screen; GetStruct()->base.convert_point_from_screen = button_convert_point_from_screen; GetStruct()->base.convert_point_to_window = button_convert_point_to_window; GetStruct()->base.convert_point_from_window = button_convert_point_from_window; GetStruct()->base.convert_point_to_view = button_convert_point_to_view; GetStruct()->base.convert_point_from_view = button_convert_point_from_view; } template<> CefRefPtr<CefButton> CefCppToCRefCounted<CefButtonCppToC, CefButton, cef_button_t>::UnwrapDerived(CefWrapperType type, cef_button_t* s) { if (type == WT_LABEL_BUTTON) { return CefLabelButtonCppToC::Unwrap(reinterpret_cast<cef_label_button_t*>( s)); } if (type == WT_MENU_BUTTON) { return CefMenuButtonCppToC::Unwrap(reinterpret_cast<cef_menu_button_t*>(s)); } NOTREACHED() << "Unexpected class type: " << type; return NULL; } #if DCHECK_IS_ON() template<> base::AtomicRefCount CefCppToCRefCounted<CefButtonCppToC, CefButton, cef_button_t>::DebugObjCt = 0; #endif template<> CefWrapperType CefCppToCRefCounted<CefButtonCppToC, CefButton, cef_button_t>::kWrapperType = WT_BUTTON;
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: e227d0e11c8e0498a88231ab7e5f9da8 timeCreated: 1510610474 licenseType: Free MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
#ifndef __STARTUP_DIALOG_H__ #define __STARTUP_DIALOG_H__ #include "UmodelSettings.h" class UIStartupDialog : public UIBaseDialog { public: UIStartupDialog(CStartupSettings& settings); bool Show(); protected: CStartupSettings& Opt; UICheckboxGroup* OverrideGameGroup; UICombobox* OverrideEngineCombo; UICombobox* OverrideGameCombo; void FillGameList(); virtual void InitUI(); }; #endif // __STARTUP_DIALOG_H__
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <!-- ~ Copyright 2014 Eduardo Barrenechea ~ ~ 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. --> <TextView android:id="@+id/text_item" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="72dp" android:gravity="center_vertical" android:paddingLeft="72dp" android:textAppearance="?android:attr/textAppearanceMedium" tools:text="Sample text"/>
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <CONFIG> <Makefile Value="2"/> <Params Value=" -Fu../../packager/units/$(CPU_TARGET)-$(OS_TARGET);../lazutils/lib/$(CPU_TARGET)-$(OS_TARGET);../freetype/lib/$(CPU_TARGET)-$(OS_TARGET);../../lcl/units/$(CPU_TARGET)-$(OS_TARGET);. -MObjFPC -Scghi -O1 -g -gl -l -venibq -vw-h- -vm4046 debuggerintf.pas"/> </CONFIG>
{ "pile_set_name": "Github" }
// // SendPaxViewController.swift // Blockchain // // Created by Alex McGregor on 4/23/19. // Copyright © 2019 Blockchain Luxembourg S.A. All rights reserved. // import DIKit import ERC20Kit import EthereumKit import Foundation import PlatformKit import PlatformUIKit import RxCocoa import RxSwift import SafariServices import ToolKit protocol SendPaxViewControllerDelegate: class { func onLoad() func onAppear() func onConfirmSendTapped() func onSendProposed() func onPaxEntry(_ value: CryptoValue?) func onFiatEntry(_ value: FiatValue) func onAddressEntry(_ value: String?) func onErrorBarButtonItemTapped() func onExchangeAddressButtonTapped() func onQRBarButtonItemTapped() var rightNavigationCTAType: NavigationCTAType { get } } class SendPaxViewController: UIViewController { // MARK: Public Properties weak var delegate: SendPaxViewControllerDelegate? // MARK: Private IBOutlets @IBOutlet private var outerStackView: UIStackView! @IBOutlet private var topGravityStackView: UIStackView! @IBOutlet private var sourceAccountTitleLabel: UILabel! @IBOutlet private var sourceAccountValueLabel: UILabel! @IBOutlet private var destinationAddressTitleLabel: UILabel! @IBOutlet private var destinationAddressIndicatorLabel: UILabel! @IBOutlet private var destinationAddressTextField: UITextField! @IBOutlet private var feesTitleLabel: UILabel! @IBOutlet private var networkFeesLabel: UILabel! @IBOutlet private var maxAvailableLabel: ActionableLabel! @IBOutlet private var cryptoTitleLabel: UILabel! @IBOutlet private var cryptoAmountTextField: UITextField! @IBOutlet private var fiatTitleLabel: UILabel! @IBOutlet private var fiatAmountTextField: UITextField! @IBOutlet private var sendNowButton: UIButton! @IBOutlet private var exchangeAddressButton: UIButton! private var fields: [UITextField] { [ destinationAddressTextField, cryptoAmountTextField, fiatAmountTextField ] } // MARK: Private Properties private var coordinator: SendPaxCoordinator! private let alertViewPresenter: AlertViewPresenter = AlertViewPresenter.shared private let loadingViewPresenter: LoadingViewPresenting = LoadingViewPresenter.shared private var qrScannerViewModel: QRCodeScannerViewModel<AddressQRCodeParser>? private let analyticsRecorder: AnalyticsEventRecording = resolve() private var maxAvailableTrigger: ActionableTrigger? { didSet { guard let trigger = maxAvailableTrigger else { maxAvailableLabel.text = "" return } let maxText = NSMutableAttributedString( string: trigger.primaryString, attributes: useMaxAttributes() ) let CTA = NSAttributedString( string: trigger.callToAction, attributes: useMaxActionAttributes() ) maxText.append(CTA) maxAvailableLabel.attributedText = maxText } } // MARK: Class Functions @objc class func make() -> SendPaxViewController { SendPaxViewController.makeFromStoryboard() } // MARK: Lifecycle override func viewDidLoad() { super.viewDidLoad() coordinator = SendPaxCoordinator( interface: self, exchangeAddressPresenter: SendExchangeAddressStatePresenter(assetType: .pax) ) fields.forEach({ $0.delegate = self }) topGravityStackView.addBackgroundColor(#colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1)) sendNowButton.layer.cornerRadius = 4.0 sendNowButton.setTitle(LocalizationConstants.continueString, for: .normal) maxAvailableLabel.delegate = self delegate?.onLoad() setupKeyboard() setupAccessibility() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) delegate?.onAppear() } private func setupAccessibility() { sourceAccountTitleLabel.accessibilityIdentifier = AccessibilityIdentifiers.SendScreen.sourceAccountTitleLabel sourceAccountValueLabel.accessibilityIdentifier = AccessibilityIdentifiers.SendScreen.sourceAccountValueLabel destinationAddressTitleLabel.accessibilityIdentifier = AccessibilityIdentifiers.SendScreen.destinationAddressTitleLabel destinationAddressTextField.accessibilityIdentifier = AccessibilityIdentifiers.SendScreen.destinationAddressTextField destinationAddressIndicatorLabel.accessibilityIdentifier = AccessibilityIdentifiers.SendScreen.destinationAddressIndicatorLabel feesTitleLabel.accessibilityIdentifier = AccessibilityIdentifiers.SendScreen.feesTitleLabel networkFeesLabel.accessibilityIdentifier = AccessibilityIdentifiers.SendScreen.feesValueLabel maxAvailableLabel.accessibilityIdentifier = AccessibilityIdentifiers.SendScreen.maxAvailableLabel cryptoTitleLabel.accessibilityIdentifier = AccessibilityIdentifiers.SendScreen.cryptoTitleLabel cryptoAmountTextField.accessibilityIdentifier = AccessibilityIdentifiers.SendScreen.cryptoAmountTextField fiatTitleLabel.accessibilityIdentifier = AccessibilityIdentifiers.SendScreen.fiatTitleLabel fiatAmountTextField.accessibilityIdentifier = AccessibilityIdentifiers.SendScreen.fiatAmountTextField exchangeAddressButton.accessibilityIdentifier = AccessibilityIdentifiers.SendScreen.exchangeAddressButton sendNowButton.accessibilityIdentifier = AccessibilityIdentifiers.SendScreen.continueButton } private func setupKeyboard() { let bar = UIToolbar() let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(dismissKeyboard)) let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil) bar.items = [ flexibleSpace, doneButton ] bar.sizeToFit() destinationAddressTextField.inputAccessoryView = bar fiatAmountTextField.inputAccessoryView = bar cryptoAmountTextField.inputAccessoryView = bar hideKeyboardWhenTappedAround() } private func apply(_ update: SendMoniesPresentationUpdate) { switch update { case .cryptoValueTextField(let amount): guard cryptoAmountTextField.isFirstResponder == false else { return } if amount?.amount == 0 { cryptoAmountTextField.text = "" } else { cryptoAmountTextField.text = amount?.toDisplayString(includeSymbol: false) } case .feeValueLabel(let fee): networkFeesLabel.text = fee case .toAddressTextField(let address): destinationAddressTextField.text = address case .fiatValueTextField(let amount): guard fiatAmountTextField.isFirstResponder == false else { return } if amount?.amount == 0 { fiatAmountTextField.text = "" } else { fiatAmountTextField.text = amount?.toDisplayString(includeSymbol: false, locale: Locale.current) } case .loadingIndicatorVisibility(let visibility): switch visibility { case .hidden: loadingViewPresenter.hide() case .visible: loadingViewPresenter.show(with: LocalizationConstants.loading) } case .sendButtonEnabled(let enabled): sendNowButton.isEnabled = enabled sendNowButton.alpha = enabled ? 1.0 : 0.5 case .textFieldEditingEnabled(let editable): fields.forEach({ $0.isEnabled = editable }) case .showAlertSheetForError(let error): handle(error: error) case .showAlertSheetForSuccess: let alert = AlertModel( headline: LocalizationConstants.success, body: LocalizationConstants.SendAsset.paymentSent, image: #imageLiteral(resourceName: "eth_good"), style: .sheet ) let alertView = AlertView.make(with: alert, completion: nil) alertView.show() case .hideConfirmationModal: ModalPresenter.shared.closeAllModals() case .updateNavigationItems: if let navController = navigationController as? BaseNavigationController { navController.update() } case .walletLabel(let accountLabel): sourceAccountValueLabel.text = accountLabel case .maxAvailable(let max): maxAvailableTrigger = ActionableTrigger( text: LocalizationConstants.SendAsset.useTotalSpendableBalance, CTA: max?.toDisplayString(includeSymbol: true) ?? "..." ) { [weak self] in guard let max = max else { return } self?.delegate?.onPaxEntry(max) } case .fiatCurrencyLabel(let fiatCurrency): fiatTitleLabel.text = fiatCurrency case .exchangeAddressButtonVisibility(let isVisible): exchangeAddressButton.isHidden = !isVisible case .useExchangeAddress(let address): destinationAddressTextField.text = address if address == nil { exchangeAddressButton.setImage(UIImage(named: "exchange-icon-small"), for: .normal) destinationAddressTextField.isHidden = false destinationAddressIndicatorLabel.text = nil } else { exchangeAddressButton.setImage(UIImage(named: "cancel_icon"), for: .normal) destinationAddressTextField.isHidden = true destinationAddressIndicatorLabel.text = String( format: LocalizationConstants.Exchange.Send.destination, CryptoCurrency.pax.displayCode ) } case .showAlertForEnabling2FA: alertViewPresenter.standardNotify( title: LocalizationConstants.Errors.error, message: LocalizationConstants.Exchange.twoFactorNotEnabled ) } } // MARK: Private Helpers private func useMaxAttributes() -> [NSAttributedString.Key: Any] { let fontName = Constants.FontNames.montserratRegular let font = UIFont(name: fontName, size: 13.0) ?? UIFont.systemFont(ofSize: 13.0) return [ .font: font, .foregroundColor: UIColor.darkGray ] } private func useMaxActionAttributes() -> [NSAttributedString.Key: Any] { let fontName = Constants.FontNames.montserratRegular let font = UIFont(name: fontName, size: 13.0) ?? UIFont.systemFont(ofSize: 13.0) return [ .font: font, .foregroundColor: UIColor.brandSecondary ] } fileprivate func handle(error: SendMoniesInternalError) { fields.forEach({ $0.resignFirstResponder() }) var alert = AlertModel( headline: error.title, body: error.description, image: #imageLiteral(resourceName: "eth_bad"), style: .sheet ) if error == .insufficientFeeCoverage { guard let url = URL(string: Constants.Url.ethGasExplanationForPax) else { return } let action = AlertAction(style: .confirm(LocalizationConstants.learnMore), metadata: .url(url)) alert.actions = [action] } let alertView = AlertView.make(with: alert) { [weak self] action in guard let self = self else { return } guard let metadata = action.metadata else { return } switch metadata { case .url(let url): let viewController = SFSafariViewController(url: url) viewController.modalPresentationStyle = .overFullScreen self.present(viewController, animated: true, completion: nil) case .block, .pop, .payload, .dismiss: break } } alertView.show() } // MARK: Actions @IBAction private func sendNowTapped(_ sender: UIButton) { delegate?.onSendProposed() } @IBAction private func exchangeAddressButtonPressed() { delegate?.onExchangeAddressButtonTapped() } } extension SendPaxViewController: UITextFieldDelegate { func textFieldDidEndEditing(_ textField: UITextField) { guard let text = textField.text, !text.isEmpty else { return } if textField == cryptoAmountTextField { let value = CryptoValue.paxFromMajor(string: text) delegate?.onPaxEntry(value) } if textField == fiatAmountTextField { let currencyCode = BlockchainSettings.App.shared.fiatCurrencyCode let value = FiatValue.create(amountString: text, currencyCode: currencyCode) delegate?.onFiatEntry(value) } } func textFieldShouldClear(_ textField: UITextField) -> Bool { if textField == destinationAddressTextField { delegate?.onAddressEntry("") } return true } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { guard let text = textField.text else { return true } let replacementInput = (text as NSString).replacingCharacters(in: range, with: string) if textField == destinationAddressTextField { delegate?.onAddressEntry(replacementInput) } if textField == cryptoAmountTextField { let value = CryptoValue.paxFromMajor(string: replacementInput) delegate?.onPaxEntry(value) } if textField == fiatAmountTextField { let currencyCode = BlockchainSettings.App.shared.fiatCurrencyCode let value = FiatValue.create(amountString: replacementInput, currencyCode: currencyCode) delegate?.onFiatEntry(value) } return true } } extension SendPaxViewController: NavigatableView { func navControllerRightBarButtonTapped(_ navController: UINavigationController) { if let type = delegate?.rightNavigationCTAType, type == .error { delegate?.onErrorBarButtonItemTapped() } else if let type = delegate?.rightNavigationCTAType, type == .qrCode { delegate?.onQRBarButtonItemTapped() } else if let parent = parent as? AssetSelectorContainerViewController { parent.navControllerRightBarButtonTapped(navController) } } func navControllerLeftBarButtonTapped(_ navController: UINavigationController) { if let parent = parent as? AssetSelectorContainerViewController { parent.navControllerLeftBarButtonTapped(navController) } } var rightNavControllerCTAType: NavigationCTAType { delegate?.rightNavigationCTAType ?? .qrCode } var rightCTATintColor: UIColor { guard let delegate = delegate else { return .white } if delegate.rightNavigationCTAType == .qrCode || delegate.rightNavigationCTAType == .activityIndicator { return .white } return .pending } } extension SendPaxViewController: SendPAXInterface { func apply(updates: Set<SendMoniesPresentationUpdate>) { updates.forEach({ self.apply($0) }) } func display(confirmation: BCConfirmPaymentViewModel) { let confirmView = BCConfirmPaymentView( frame: view.frame, viewModel: confirmation, sendButtonFrame: sendNowButton.frame )! confirmView.confirmDelegate = self ModalPresenter.shared.showModal( withContent: confirmView, closeType: ModalCloseTypeBack, showHeader: true, headerText: LocalizationConstants.SendAsset.confirmPayment ) } func displayQRCodeScanner() { scanQrCodeForDestinationAddress() } } extension SendPaxViewController: ConfirmPaymentViewDelegate { func confirmButtonDidTap(_ note: String?) { delegate?.onConfirmSendTapped() } func feeInformationButtonClicked() { // TODO } } extension SendPaxViewController { func hideKeyboardWhenTappedAround() { let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(SendPaxViewController.dismissKeyboard)) tap.cancelsTouchesInView = false view.addGestureRecognizer(tap) } @objc func dismissKeyboard() { view.endEditing(true) } } // TODO: Clean this up, move to Coordinator extension SendPaxViewController { @objc func scanQrCodeForDestinationAddress() { guard let scanner = QRCodeScanner() else { return } let parser = AddressQRCodeParser(assetType: .pax) let textViewModel = AddressQRCodeTextViewModel() qrScannerViewModel = QRCodeScannerViewModel( parser: parser, additionalParsingOptions: .lax(routes: [.exchangeLinking]), textViewModel: textViewModel, scanner: scanner, completed: { [weak self] result in self?.handleAddressScan(result: result) } ) let viewController = QRCodeScannerViewControllerBuilder(viewModel: qrScannerViewModel)? .with(presentationType: .modal(dismissWithAnimation: false)) .build() guard let qrCodeScannerViewController = viewController else { return } DispatchQueue.main.async { guard let controller = AppCoordinator.shared.tabControllerManager.tabViewController else { return } controller.present(qrCodeScannerViewController, animated: true, completion: nil) } } private func handleAddressScan(result: Result<AddressQRCodeParser.Address, AddressQRCodeParser.AddressQRCodeParserError>) { if case .success(let assetURL) = result { let address = assetURL.payload.address delegate?.onAddressEntry(address) destinationAddressTextField.text = address guard let amount = assetURL.payload.amount, let value = CryptoValue.paxFromMajor(string: amount) else { return } delegate?.onPaxEntry(value) cryptoAmountTextField.insertText(amount) } } } extension SendPaxViewController: ActionableLabelDelegate { func targetRange(_ label: ActionableLabel) -> NSRange? { maxAvailableTrigger?.actionRange() } func actionRequestingExecution(label: ActionableLabel) { guard let trigger = maxAvailableTrigger else { return } analyticsRecorder.record(event: AnalyticsEvents.Send.sendFormUseBalanceClick(asset: .pax)) trigger.execute() } }
{ "pile_set_name": "Github" }
# Change Log **ATTN**: This project uses [semantic versioning](http://semver.org/). ## [Unreleased] ## 1.20.0 - 2017-08-10 ### Fixed * `HandleExitCoder` is now correctly iterates over all errors in a `MultiError`. The exit code is the exit code of the last error or `1` if there are no `ExitCoder`s in the `MultiError`. * Fixed YAML file loading on Windows (previously would fail validate the file path) * Subcommand `Usage`, `Description`, `ArgsUsage`, `OnUsageError` correctly propogated * `ErrWriter` is now passed downwards through command structure to avoid the need to redefine it * Pass `Command` context into `OnUsageError` rather than parent context so that all fields are avaiable * Errors occuring in `Before` funcs are no longer double printed * Use `UsageText` in the help templates for commands and subcommands if defined; otherwise build the usage as before (was previously ignoring this field) * `IsSet` and `GlobalIsSet` now correctly return whether a flag is set if a program calls `Set` or `GlobalSet` directly after flag parsing (would previously only return `true` if the flag was set during parsing) ### Changed * No longer exit the program on command/subcommand error if the error raised is not an `OsExiter`. This exiting behavior was introduced in 1.19.0, but was determined to be a regression in functionality. See [the PR](https://github.com/urfave/cli/pull/595) for discussion. ### Added * `CommandsByName` type was added to make it easy to sort `Command`s by name, alphabetically * `altsrc` now handles loading of string and int arrays from TOML * Support for definition of custom help templates for `App` via `CustomAppHelpTemplate` * Support for arbitrary key/value fields on `App` to be used with `CustomAppHelpTemplate` via `ExtraInfo` * `HelpFlag`, `VersionFlag`, and `BashCompletionFlag` changed to explictly be `cli.Flag`s allowing for the use of custom flags satisfying the `cli.Flag` interface to be used. ## [1.19.1] - 2016-11-21 ### Fixed - Fixes regression introduced in 1.19.0 where using an `ActionFunc` as the `Action` for a command would cause it to error rather than calling the function. Should not have a affected declarative cases using `func(c *cli.Context) err)`. - Shell completion now handles the case where the user specifies `--generate-bash-completion` immediately after a flag that takes an argument. Previously it call the application with `--generate-bash-completion` as the flag value. ## [1.19.0] - 2016-11-19 ### Added - `FlagsByName` was added to make it easy to sort flags (e.g. `sort.Sort(cli.FlagsByName(app.Flags))`) - A `Description` field was added to `App` for a more detailed description of the application (similar to the existing `Description` field on `Command`) - Flag type code generation via `go generate` - Write to stderr and exit 1 if action returns non-nil error - Added support for TOML to the `altsrc` loader - `SkipArgReorder` was added to allow users to skip the argument reordering. This is useful if you want to consider all "flags" after an argument as arguments rather than flags (the default behavior of the stdlib `flag` library). This is backported functionality from the [removal of the flag reordering](https://github.com/urfave/cli/pull/398) in the unreleased version 2 - For formatted errors (those implementing `ErrorFormatter`), the errors will be formatted during output. Compatible with `pkg/errors`. ### Changed - Raise minimum tested/supported Go version to 1.2+ ### Fixed - Consider empty environment variables as set (previously environment variables with the equivalent of `""` would be skipped rather than their value used). - Return an error if the value in a given environment variable cannot be parsed as the flag type. Previously these errors were silently swallowed. - Print full error when an invalid flag is specified (which includes the invalid flag) - `App.Writer` defaults to `stdout` when `nil` - If no action is specified on a command or app, the help is now printed instead of `panic`ing - `App.Metadata` is initialized automatically now (previously was `nil` unless initialized) - Correctly show help message if `-h` is provided to a subcommand - `context.(Global)IsSet` now respects environment variables. Previously it would return `false` if a flag was specified in the environment rather than as an argument - Removed deprecation warnings to STDERR to avoid them leaking to the end-user - `altsrc`s import paths were updated to use `gopkg.in/urfave/cli.v1`. This fixes issues that occurred when `gopkg.in/urfave/cli.v1` was imported as well as `altsrc` where Go would complain that the types didn't match ## [1.18.1] - 2016-08-28 ### Fixed - Removed deprecation warnings to STDERR to avoid them leaking to the end-user (backported) ## [1.18.0] - 2016-06-27 ### Added - `./runtests` test runner with coverage tracking by default - testing on OS X - testing on Windows - `UintFlag`, `Uint64Flag`, and `Int64Flag` types and supporting code ### Changed - Use spaces for alignment in help/usage output instead of tabs, making the output alignment consistent regardless of tab width ### Fixed - Printing of command aliases in help text - Printing of visible flags for both struct and struct pointer flags - Display the `help` subcommand when using `CommandCategories` - No longer swallows `panic`s that occur within the `Action`s themselves when detecting the signature of the `Action` field ## [1.17.1] - 2016-08-28 ### Fixed - Removed deprecation warnings to STDERR to avoid them leaking to the end-user ## [1.17.0] - 2016-05-09 ### Added - Pluggable flag-level help text rendering via `cli.DefaultFlagStringFunc` - `context.GlobalBoolT` was added as an analogue to `context.GlobalBool` - Support for hiding commands by setting `Hidden: true` -- this will hide the commands in help output ### Changed - `Float64Flag`, `IntFlag`, and `DurationFlag` default values are no longer quoted in help text output. - All flag types now include `(default: {value})` strings following usage when a default value can be (reasonably) detected. - `IntSliceFlag` and `StringSliceFlag` usage strings are now more consistent with non-slice flag types - Apps now exit with a code of 3 if an unknown subcommand is specified (previously they printed "No help topic for...", but still exited 0. This makes it easier to script around apps built using `cli` since they can trust that a 0 exit code indicated a successful execution. - cleanups based on [Go Report Card feedback](https://goreportcard.com/report/github.com/urfave/cli) ## [1.16.1] - 2016-08-28 ### Fixed - Removed deprecation warnings to STDERR to avoid them leaking to the end-user ## [1.16.0] - 2016-05-02 ### Added - `Hidden` field on all flag struct types to omit from generated help text ### Changed - `BashCompletionFlag` (`--enable-bash-completion`) is now omitted from generated help text via the `Hidden` field ### Fixed - handling of error values in `HandleAction` and `HandleExitCoder` ## [1.15.0] - 2016-04-30 ### Added - This file! - Support for placeholders in flag usage strings - `App.Metadata` map for arbitrary data/state management - `Set` and `GlobalSet` methods on `*cli.Context` for altering values after parsing. - Support for nested lookup of dot-delimited keys in structures loaded from YAML. ### Changed - The `App.Action` and `Command.Action` now prefer a return signature of `func(*cli.Context) error`, as defined by `cli.ActionFunc`. If a non-nil `error` is returned, there may be two outcomes: - If the error fulfills `cli.ExitCoder`, then `os.Exit` will be called automatically - Else the error is bubbled up and returned from `App.Run` - Specifying an `Action` with the legacy return signature of `func(*cli.Context)` will produce a deprecation message to stderr - Specifying an `Action` that is not a `func` type will produce a non-zero exit from `App.Run` - Specifying an `Action` func that has an invalid (input) signature will produce a non-zero exit from `App.Run` ### Deprecated - <a name="deprecated-cli-app-runandexitonerror"></a> `cli.App.RunAndExitOnError`, which should now be done by returning an error that fulfills `cli.ExitCoder` to `cli.App.Run`. - <a name="deprecated-cli-app-action-signature"></a> the legacy signature for `cli.App.Action` of `func(*cli.Context)`, which should now have a return signature of `func(*cli.Context) error`, as defined by `cli.ActionFunc`. ### Fixed - Added missing `*cli.Context.GlobalFloat64` method ## [1.14.0] - 2016-04-03 (backfilled 2016-04-25) ### Added - Codebeat badge - Support for categorization via `CategorizedHelp` and `Categories` on app. ### Changed - Use `filepath.Base` instead of `path.Base` in `Name` and `HelpName`. ### Fixed - Ensure version is not shown in help text when `HideVersion` set. ## [1.13.0] - 2016-03-06 (backfilled 2016-04-25) ### Added - YAML file input support. - `NArg` method on context. ## [1.12.0] - 2016-02-17 (backfilled 2016-04-25) ### Added - Custom usage error handling. - Custom text support in `USAGE` section of help output. - Improved help messages for empty strings. - AppVeyor CI configuration. ### Changed - Removed `panic` from default help printer func. - De-duping and optimizations. ### Fixed - Correctly handle `Before`/`After` at command level when no subcommands. - Case of literal `-` argument causing flag reordering. - Environment variable hints on Windows. - Docs updates. ## [1.11.1] - 2015-12-21 (backfilled 2016-04-25) ### Changed - Use `path.Base` in `Name` and `HelpName` - Export `GetName` on flag types. ### Fixed - Flag parsing when skipping is enabled. - Test output cleanup. - Move completion check to account for empty input case. ## [1.11.0] - 2015-11-15 (backfilled 2016-04-25) ### Added - Destination scan support for flags. - Testing against `tip` in Travis CI config. ### Changed - Go version in Travis CI config. ### Fixed - Removed redundant tests. - Use correct example naming in tests. ## [1.10.2] - 2015-10-29 (backfilled 2016-04-25) ### Fixed - Remove unused var in bash completion. ## [1.10.1] - 2015-10-21 (backfilled 2016-04-25) ### Added - Coverage and reference logos in README. ### Fixed - Use specified values in help and version parsing. - Only display app version and help message once. ## [1.10.0] - 2015-10-06 (backfilled 2016-04-25) ### Added - More tests for existing functionality. - `ArgsUsage` at app and command level for help text flexibility. ### Fixed - Honor `HideHelp` and `HideVersion` in `App.Run`. - Remove juvenile word from README. ## [1.9.0] - 2015-09-08 (backfilled 2016-04-25) ### Added - `FullName` on command with accompanying help output update. - Set default `$PROG` in bash completion. ### Changed - Docs formatting. ### Fixed - Removed self-referential imports in tests. ## [1.8.0] - 2015-06-30 (backfilled 2016-04-25) ### Added - Support for `Copyright` at app level. - `Parent` func at context level to walk up context lineage. ### Fixed - Global flag processing at top level. ## [1.7.1] - 2015-06-11 (backfilled 2016-04-25) ### Added - Aggregate errors from `Before`/`After` funcs. - Doc comments on flag structs. - Include non-global flags when checking version and help. - Travis CI config updates. ### Fixed - Ensure slice type flags have non-nil values. - Collect global flags from the full command hierarchy. - Docs prose. ## [1.7.0] - 2015-05-03 (backfilled 2016-04-25) ### Changed - `HelpPrinter` signature includes output writer. ### Fixed - Specify go 1.1+ in docs. - Set `Writer` when running command as app. ## [1.6.0] - 2015-03-23 (backfilled 2016-04-25) ### Added - Multiple author support. - `NumFlags` at context level. - `Aliases` at command level. ### Deprecated - `ShortName` at command level. ### Fixed - Subcommand help output. - Backward compatible support for deprecated `Author` and `Email` fields. - Docs regarding `Names`/`Aliases`. ## [1.5.0] - 2015-02-20 (backfilled 2016-04-25) ### Added - `After` hook func support at app and command level. ### Fixed - Use parsed context when running command as subcommand. - Docs prose. ## [1.4.1] - 2015-01-09 (backfilled 2016-04-25) ### Added - Support for hiding `-h / --help` flags, but not `help` subcommand. - Stop flag parsing after `--`. ### Fixed - Help text for generic flags to specify single value. - Use double quotes in output for defaults. - Use `ParseInt` instead of `ParseUint` for int environment var values. - Use `0` as base when parsing int environment var values. ## [1.4.0] - 2014-12-12 (backfilled 2016-04-25) ### Added - Support for environment variable lookup "cascade". - Support for `Stdout` on app for output redirection. ### Fixed - Print command help instead of app help in `ShowCommandHelp`. ## [1.3.1] - 2014-11-13 (backfilled 2016-04-25) ### Added - Docs and example code updates. ### Changed - Default `-v / --version` flag made optional. ## [1.3.0] - 2014-08-10 (backfilled 2016-04-25) ### Added - `FlagNames` at context level. - Exposed `VersionPrinter` var for more control over version output. - Zsh completion hook. - `AUTHOR` section in default app help template. - Contribution guidelines. - `DurationFlag` type. ## [1.2.0] - 2014-08-02 ### Added - Support for environment variable defaults on flags plus tests. ## [1.1.0] - 2014-07-15 ### Added - Bash completion. - Optional hiding of built-in help command. - Optional skipping of flag parsing at command level. - `Author`, `Email`, and `Compiled` metadata on app. - `Before` hook func support at app and command level. - `CommandNotFound` func support at app level. - Command reference available on context. - `GenericFlag` type. - `Float64Flag` type. - `BoolTFlag` type. - `IsSet` flag helper on context. - More flag lookup funcs at context level. - More tests &amp; docs. ### Changed - Help template updates to account for presence/absence of flags. - Separated subcommand help template. - Exposed `HelpPrinter` var for more control over help output. ## [1.0.0] - 2013-11-01 ### Added - `help` flag in default app flag set and each command flag set. - Custom handling of argument parsing errors. - Command lookup by name at app level. - `StringSliceFlag` type and supporting `StringSlice` type. - `IntSliceFlag` type and supporting `IntSlice` type. - Slice type flag lookups by name at context level. - Export of app and command help functions. - More tests &amp; docs. ## 0.1.0 - 2013-07-22 ### Added - Initial implementation. [Unreleased]: https://github.com/urfave/cli/compare/v1.18.0...HEAD [1.18.0]: https://github.com/urfave/cli/compare/v1.17.0...v1.18.0 [1.17.0]: https://github.com/urfave/cli/compare/v1.16.0...v1.17.0 [1.16.0]: https://github.com/urfave/cli/compare/v1.15.0...v1.16.0 [1.15.0]: https://github.com/urfave/cli/compare/v1.14.0...v1.15.0 [1.14.0]: https://github.com/urfave/cli/compare/v1.13.0...v1.14.0 [1.13.0]: https://github.com/urfave/cli/compare/v1.12.0...v1.13.0 [1.12.0]: https://github.com/urfave/cli/compare/v1.11.1...v1.12.0 [1.11.1]: https://github.com/urfave/cli/compare/v1.11.0...v1.11.1 [1.11.0]: https://github.com/urfave/cli/compare/v1.10.2...v1.11.0 [1.10.2]: https://github.com/urfave/cli/compare/v1.10.1...v1.10.2 [1.10.1]: https://github.com/urfave/cli/compare/v1.10.0...v1.10.1 [1.10.0]: https://github.com/urfave/cli/compare/v1.9.0...v1.10.0 [1.9.0]: https://github.com/urfave/cli/compare/v1.8.0...v1.9.0 [1.8.0]: https://github.com/urfave/cli/compare/v1.7.1...v1.8.0 [1.7.1]: https://github.com/urfave/cli/compare/v1.7.0...v1.7.1 [1.7.0]: https://github.com/urfave/cli/compare/v1.6.0...v1.7.0 [1.6.0]: https://github.com/urfave/cli/compare/v1.5.0...v1.6.0 [1.5.0]: https://github.com/urfave/cli/compare/v1.4.1...v1.5.0 [1.4.1]: https://github.com/urfave/cli/compare/v1.4.0...v1.4.1 [1.4.0]: https://github.com/urfave/cli/compare/v1.3.1...v1.4.0 [1.3.1]: https://github.com/urfave/cli/compare/v1.3.0...v1.3.1 [1.3.0]: https://github.com/urfave/cli/compare/v1.2.0...v1.3.0 [1.2.0]: https://github.com/urfave/cli/compare/v1.1.0...v1.2.0 [1.1.0]: https://github.com/urfave/cli/compare/v1.0.0...v1.1.0 [1.0.0]: https://github.com/urfave/cli/compare/v0.1.0...v1.0.0
{ "pile_set_name": "Github" }
<!DOCTYPE HTML> <html> <!-- https://bugzilla.mozilla.org/show_bug.cgi?id=402380 --> <head> <title>Test for Bug 402380</title> <script src="/tests/SimpleTest/SimpleTest.js"></script> <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" /> <style type="text/css"> div::first-letter { color: green; } span:before { content: open-quote "This "; } span:after { content: close-quote; } </style> </head> <body style="font-family: monospace; width: 7ch; border: 1px solid orange;" onload="document.getElementById('div').style.direction = 'rtl';"> <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=402380">Mozilla Bug 402380</a> <div id="div"><span>is text</span></div> <pre id="test"> <script class="testbody" type="text/javascript"> function test() { /** Test for Bug 402380 **/ ok(true, "Should not crash"); SimpleTest.finish(); } SimpleTest.requestFlakyTimeout("untriaged"); setTimeout(test, 500); SimpleTest.waitForExplicitFinish(); </script> </pre> </body> </html>
{ "pile_set_name": "Github" }
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 2011-2014 OpenFOAM Foundation \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM 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. OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>. Class Foam::displacementSBRStressFvMotionSolver Description Mesh motion solver for an fvMesh. Based on solving the cell-centre solid-body rotation stress equations for the motion displacement. SourceFiles displacementSBRStressFvMotionSolver.C \*---------------------------------------------------------------------------*/ #ifndef displacementSBRStressFvMotionSolver_H #define displacementSBRStressFvMotionSolver_H #include "displacementMotionSolver.H" #include "fvMotionSolverCore.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { // Forward class declarations class motionDiffusivity; /*---------------------------------------------------------------------------*\ Class displacementSBRStressFvMotionSolver Declaration \*---------------------------------------------------------------------------*/ class displacementSBRStressFvMotionSolver : public displacementMotionSolver, public fvMotionSolverCore { // Private data //- Cell-centre motion field mutable volVectorField cellDisplacement_; //- Diffusivity used to control the motion autoPtr<motionDiffusivity> diffusivityPtr_; // Private Member Functions //- Disallow default bitwise copy construct displacementSBRStressFvMotionSolver ( const displacementSBRStressFvMotionSolver& ); //- Disallow default bitwise assignment void operator=(const displacementSBRStressFvMotionSolver&); public: //- Runtime type information TypeName("displacementSBRStress"); // Constructors //- Construct from polyMesh and IOdictionary displacementSBRStressFvMotionSolver ( const polyMesh&, const IOdictionary& ); //- Destructor ~displacementSBRStressFvMotionSolver(); // Member Functions //- Return reference to the cell motion displacement field volVectorField& cellDisplacement() { return cellDisplacement_; } //- Return const reference to the cell motion displacement field const volVectorField& cellDisplacement() const { return cellDisplacement_; } //- Return diffusivity motionDiffusivity& diffusivity() { return diffusivityPtr_(); } //- Return point location obtained from the current motion field virtual tmp<pointField> curPoints() const; //- Solve for motion virtual void solve(); //- Update topology virtual void updateMesh(const mapPolyMesh&); }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace Foam // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
{ "pile_set_name": "Github" }
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard. // #import <SAObjects/SADomainCommand.h> @interface SAMPLoadPredefinedQueue : SADomainCommand { } + (id)loadPredefinedQueueWithDictionary:(id)arg1 context:(id)arg2; + (id)loadPredefinedQueue; - (BOOL)requiresResponse; @property(nonatomic) BOOL shouldShuffle; @property(nonatomic) int mediaItemType; - (id)encodedClassName; - (id)groupIdentifier; @end
{ "pile_set_name": "Github" }
<!DOCTYPE HTML> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc --> <title>ConstantCallSite (Java SE 12 &amp; JDK 12 )</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="keywords" content="java.lang.invoke.ConstantCallSite class"> <meta name="keywords" content="getTarget()"> <meta name="keywords" content="setTarget()"> <meta name="keywords" content="dynamicInvoker()"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> <link rel="stylesheet" type="text/css" href="../../../../jquery/jquery-ui.css" title="Style"> <script type="text/javascript" src="../../../../script.js"></script> <script type="text/javascript" src="../../../../jquery/jszip/dist/jszip.min.js"></script> <script type="text/javascript" src="../../../../jquery/jszip-utils/dist/jszip-utils.min.js"></script> <!--[if IE]> <script type="text/javascript" src="../../../../jquery/jszip-utils/dist/jszip-utils-ie.min.js"></script> <![endif]--> <script type="text/javascript" src="../../../../jquery/jquery-3.3.1.js"></script> <script type="text/javascript" src="../../../../jquery/jquery-migrate-3.0.1.js"></script> <script type="text/javascript" src="../../../../jquery/jquery-ui.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="ConstantCallSite (Java SE 12 & JDK 12 )"; } } catch(err) { } //--> var data = {"i0":10,"i1":10,"i2":10}; var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; var pathtoroot = "../../../../"; var useModuleDirectories = true; loadScripts(document, 'script');</script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <header role="banner"> <nav role="navigation"> <div class="fixedNav"> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a id="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a id="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../index.html">Overview</a></li> <li><a href="../../../module-summary.html">Module</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/ConstantCallSite.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><div style="margin-top: 14px;"><strong>Java SE 12 &amp; JDK 12</strong> </div></div> </div> <div class="subNav"> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <ul class="navListSearch"> <li><label for="search">SEARCH:</label> <input type="text" id="search" value="search" disabled="disabled"> <input type="reset" id="reset" value="reset" disabled="disabled"> </li> </ul> </div> <a id="skip.navbar.top"> <!-- --> </a> <!-- ========= END OF TOP NAVBAR ========= --> </div> <div class="navPadding">&nbsp;</div> <script type="text/javascript"><!-- $('.navPadding').css('padding-top', $('.fixedNav').css("height")); //--> </script> </nav> </header> <!-- ======== START OF CLASS DATA ======== --> <main role="main"> <div class="header"> <div class="subTitle"><span class="moduleLabelInType">Module</span>&nbsp;<a href="../../../module-summary.html">java.base</a></div> <div class="subTitle"><span class="packageLabelInType">Package</span>&nbsp;<a href="package-summary.html">java.lang.invoke</a></div> <h2 title="Class ConstantCallSite" class="title">Class ConstantCallSite</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li><a href="../Object.html" title="class in java.lang">java.lang.Object</a></li> <li> <ul class="inheritance"> <li><a href="CallSite.html" title="class in java.lang.invoke">java.lang.invoke.CallSite</a></li> <li> <ul class="inheritance"> <li>java.lang.invoke.ConstantCallSite</li> </ul> </li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <pre>public class <span class="typeNameLabel">ConstantCallSite</span> extends <a href="CallSite.html" title="class in java.lang.invoke">CallSite</a></pre> <div class="block">A <code>ConstantCallSite</code> is a <a href="CallSite.html" title="class in java.lang.invoke"><code>CallSite</code></a> whose target is permanent, and can never be changed. An <code>invokedynamic</code> instruction linked to a <code>ConstantCallSite</code> is permanently bound to the call site's target.</div> <dl> <dt><span class="simpleTagLabel">Since:</span></dt> <dd>1.7</dd> </dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <section role="region"> <ul class="blockList"> <li class="blockList"><a id="constructor.summary"> <!-- --> </a> <h3>Constructor Summary</h3> <div class="memberSummary"> <table> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier</th> <th class="colSecond" scope="col">Constructor</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>&nbsp;</code></td> <th class="colConstructorName" scope="row"><code><span class="memberNameLink"><a href="#%3Cinit%3E(java.lang.invoke.MethodHandle)">ConstantCallSite</a></span>&#8203;(<a href="MethodHandle.html" title="class in java.lang.invoke">MethodHandle</a>&nbsp;target)</code></th> <td class="colLast"> <div class="block">Creates a call site with a permanent target.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>protected </code></td> <th class="colConstructorName" scope="row"><code><span class="memberNameLink"><a href="#%3Cinit%3E(java.lang.invoke.MethodType,java.lang.invoke.MethodHandle)">ConstantCallSite</a></span>&#8203;(<a href="MethodType.html" title="class in java.lang.invoke">MethodType</a>&nbsp;targetType, <a href="MethodHandle.html" title="class in java.lang.invoke">MethodHandle</a>&nbsp;createTargetHook)</code></th> <td class="colLast"> <div class="block">Creates a call site with a permanent target, possibly bound to the call site itself.</div> </td> </tr> </tbody> </table> </div> </li> </ul> </section> <!-- ========== METHOD SUMMARY =========== --> <section role="region"> <ul class="blockList"> <li class="blockList"><a id="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <div class="memberSummary"> <div role="tablist" aria-orientation="horizontal"><button role="tab" aria-selected="true" aria-controls="memberSummary_tabpanel" tabindex="0" onkeydown="switchTab(event)" id="t0" class="activeTableTab">All Methods</button><button role="tab" aria-selected="false" aria-controls="memberSummary_tabpanel" tabindex="-1" onkeydown="switchTab(event)" id="t2" class="tableTab" onclick="show(2);">Instance Methods</button><button role="tab" aria-selected="false" aria-controls="memberSummary_tabpanel" tabindex="-1" onkeydown="switchTab(event)" id="t4" class="tableTab" onclick="show(8);">Concrete Methods</button></div> <div id="memberSummary_tabpanel" role="tabpanel"> <table aria-labelledby="t0"> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colSecond" scope="col">Method</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor" id="i0"> <td class="colFirst"><code><a href="MethodHandle.html" title="class in java.lang.invoke">MethodHandle</a></code></td> <th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="#dynamicInvoker()">dynamicInvoker</a></span>()</code></th> <td class="colLast"> <div class="block">Returns this call site's permanent target.</div> </td> </tr> <tr class="rowColor" id="i1"> <td class="colFirst"><code><a href="MethodHandle.html" title="class in java.lang.invoke">MethodHandle</a></code></td> <th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="#getTarget()">getTarget</a></span>()</code></th> <td class="colLast"> <div class="block">Returns the target method of the call site, which behaves like a <code>final</code> field of the <code>ConstantCallSite</code>.</div> </td> </tr> <tr class="altColor" id="i2"> <td class="colFirst"><code>void</code></td> <th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="#setTarget(java.lang.invoke.MethodHandle)">setTarget</a></span>&#8203;(<a href="MethodHandle.html" title="class in java.lang.invoke">MethodHandle</a>&nbsp;ignore)</code></th> <td class="colLast"> <div class="block">Always throws an <a href="../UnsupportedOperationException.html" title="class in java.lang"><code>UnsupportedOperationException</code></a>.</div> </td> </tr> </tbody> </table> </div> </div> <ul class="blockList"> <li class="blockList"><a id="methods.inherited.from.class.java.lang.invoke.CallSite"> <!-- --> </a> <h3>Methods declared in class&nbsp;java.lang.invoke.<a href="CallSite.html" title="class in java.lang.invoke">CallSite</a></h3> <code><a href="CallSite.html#type()">type</a></code></li> </ul> <ul class="blockList"> <li class="blockList"><a id="methods.inherited.from.class.java.lang.Object"> <!-- --> </a> <h3>Methods declared in class&nbsp;java.lang.<a href="../Object.html" title="class in java.lang">Object</a></h3> <code><a href="../Object.html#clone()">clone</a>, <a href="../Object.html#equals(java.lang.Object)">equals</a>, <a href="../Object.html#finalize()">finalize</a>, <a href="../Object.html#getClass()">getClass</a>, <a href="../Object.html#hashCode()">hashCode</a>, <a href="../Object.html#notify()">notify</a>, <a href="../Object.html#notifyAll()">notifyAll</a>, <a href="../Object.html#toString()">toString</a>, <a href="../Object.html#wait()">wait</a>, <a href="../Object.html#wait(long)">wait</a>, <a href="../Object.html#wait(long,int)">wait</a></code></li> </ul> </li> </ul> </section> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <section role="region"> <ul class="blockList"> <li class="blockList"><a id="constructor.detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a id="&lt;init&gt;(java.lang.invoke.MethodHandle)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>ConstantCallSite</h4> <pre>public&nbsp;ConstantCallSite&#8203;(<a href="MethodHandle.html" title="class in java.lang.invoke">MethodHandle</a>&nbsp;target)</pre> <div class="block">Creates a call site with a permanent target.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>target</code> - the target to be permanently associated with this call site</dd> <dt><span class="throwsLabel">Throws:</span></dt> <dd><code><a href="../NullPointerException.html" title="class in java.lang">NullPointerException</a></code> - if the proposed target is null</dd> </dl> </li> </ul> <a id="&lt;init&gt;(java.lang.invoke.MethodType,java.lang.invoke.MethodHandle)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>ConstantCallSite</h4> <pre>protected&nbsp;ConstantCallSite&#8203;(<a href="MethodType.html" title="class in java.lang.invoke">MethodType</a>&nbsp;targetType, <a href="MethodHandle.html" title="class in java.lang.invoke">MethodHandle</a>&nbsp;createTargetHook) throws <a href="../Throwable.html" title="class in java.lang">Throwable</a></pre> <div class="block">Creates a call site with a permanent target, possibly bound to the call site itself. <p> During construction of the call site, the <code>createTargetHook</code> is invoked to produce the actual target, as if by a call of the form <code>(MethodHandle) createTargetHook.invoke(this)</code>. <p> Note that user code cannot perform such an action directly in a subclass constructor, since the target must be fixed before the <code>ConstantCallSite</code> constructor returns. <p> The hook is said to bind the call site to a target method handle, and a typical action would be <code>someTarget.bindTo(this)</code>. However, the hook is free to take any action whatever, including ignoring the call site and returning a constant target. <p> The result returned by the hook must be a method handle of exactly the same type as the call site. <p> While the hook is being called, the new <code>ConstantCallSite</code> object is in a partially constructed state. In this state, a call to <code>getTarget</code>, or any other attempt to use the target, will result in an <code>IllegalStateException</code>. It is legal at all times to obtain the call site's type using the <code>type</code> method.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>targetType</code> - the type of the method handle to be permanently associated with this call site</dd> <dd><code>createTargetHook</code> - a method handle to invoke (on the call site) to produce the call site's target</dd> <dt><span class="throwsLabel">Throws:</span></dt> <dd><code><a href="WrongMethodTypeException.html" title="class in java.lang.invoke">WrongMethodTypeException</a></code> - if the hook cannot be invoked on the required arguments, or if the target returned by the hook is not of the given <code>targetType</code></dd> <dd><code><a href="../NullPointerException.html" title="class in java.lang">NullPointerException</a></code> - if the hook returns a null value</dd> <dd><code><a href="../ClassCastException.html" title="class in java.lang">ClassCastException</a></code> - if the hook returns something other than a <code>MethodHandle</code></dd> <dd><code><a href="../Throwable.html" title="class in java.lang">Throwable</a></code> - anything else thrown by the hook function</dd> </dl> </li> </ul> </li> </ul> </section> <!-- ============ METHOD DETAIL ========== --> <section role="region"> <ul class="blockList"> <li class="blockList"><a id="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a id="getTarget()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getTarget</h4> <pre class="methodSignature">public final&nbsp;<a href="MethodHandle.html" title="class in java.lang.invoke">MethodHandle</a>&nbsp;getTarget()</pre> <div class="block">Returns the target method of the call site, which behaves like a <code>final</code> field of the <code>ConstantCallSite</code>. That is, the target is always the original value passed to the constructor call which created this instance.</div> <dl> <dt><span class="overrideSpecifyLabel">Specified by:</span></dt> <dd><code><a href="CallSite.html#getTarget()">getTarget</a></code>&nbsp;in class&nbsp;<code><a href="CallSite.html" title="class in java.lang.invoke">CallSite</a></code></dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>the immutable linkage state of this call site, a constant method handle</dd> <dt><span class="throwsLabel">Throws:</span></dt> <dd><code><a href="../IllegalStateException.html" title="class in java.lang">IllegalStateException</a></code> - if the <code>ConstantCallSite</code> constructor has not completed</dd> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="ConstantCallSite.html" title="class in java.lang.invoke"><code>ConstantCallSite</code></a>, <a href="VolatileCallSite.html" title="class in java.lang.invoke"><code>VolatileCallSite</code></a>, <a href="CallSite.html#setTarget(java.lang.invoke.MethodHandle)"><code>CallSite.setTarget(java.lang.invoke.MethodHandle)</code></a>, <a href="#getTarget()"><code>getTarget()</code></a>, <a href="MutableCallSite.html#getTarget()"><code>MutableCallSite.getTarget()</code></a>, <a href="VolatileCallSite.html#getTarget()"><code>VolatileCallSite.getTarget()</code></a></dd> </dl> </li> </ul> <a id="setTarget(java.lang.invoke.MethodHandle)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setTarget</h4> <pre class="methodSignature">public final&nbsp;void&nbsp;setTarget&#8203;(<a href="MethodHandle.html" title="class in java.lang.invoke">MethodHandle</a>&nbsp;ignore)</pre> <div class="block">Always throws an <a href="../UnsupportedOperationException.html" title="class in java.lang"><code>UnsupportedOperationException</code></a>. This kind of call site cannot change its target.</div> <dl> <dt><span class="overrideSpecifyLabel">Specified by:</span></dt> <dd><code><a href="CallSite.html#setTarget(java.lang.invoke.MethodHandle)">setTarget</a></code>&nbsp;in class&nbsp;<code><a href="CallSite.html" title="class in java.lang.invoke">CallSite</a></code></dd> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>ignore</code> - a new target proposed for the call site, which is ignored</dd> <dt><span class="throwsLabel">Throws:</span></dt> <dd><code><a href="../UnsupportedOperationException.html" title="class in java.lang">UnsupportedOperationException</a></code> - because this kind of call site cannot change its target</dd> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="CallSite.html#getTarget()"><code>CallSite.getTarget()</code></a>, <a href="#setTarget(java.lang.invoke.MethodHandle)"><code>setTarget(java.lang.invoke.MethodHandle)</code></a>, <a href="MutableCallSite.html#setTarget(java.lang.invoke.MethodHandle)"><code>MutableCallSite.setTarget(java.lang.invoke.MethodHandle)</code></a>, <a href="VolatileCallSite.html#setTarget(java.lang.invoke.MethodHandle)"><code>VolatileCallSite.setTarget(java.lang.invoke.MethodHandle)</code></a></dd> </dl> </li> </ul> <a id="dynamicInvoker()"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>dynamicInvoker</h4> <pre class="methodSignature">public final&nbsp;<a href="MethodHandle.html" title="class in java.lang.invoke">MethodHandle</a>&nbsp;dynamicInvoker()</pre> <div class="block">Returns this call site's permanent target. Since that target will never change, this is a correct implementation of <a href="CallSite.html#dynamicInvoker()"><code>CallSite.dynamicInvoker</code></a>.</div> <dl> <dt><span class="overrideSpecifyLabel">Specified by:</span></dt> <dd><code><a href="CallSite.html#dynamicInvoker()">dynamicInvoker</a></code>&nbsp;in class&nbsp;<code><a href="CallSite.html" title="class in java.lang.invoke">CallSite</a></code></dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>the immutable linkage state of this call site, a constant method handle</dd> <dt><span class="throwsLabel">Throws:</span></dt> <dd><code><a href="../IllegalStateException.html" title="class in java.lang">IllegalStateException</a></code> - if the <code>ConstantCallSite</code> constructor has not completed</dd> </dl> </li> </ul> </li> </ul> </section> </li> </ul> </div> </div> </main> <!-- ========= END OF CLASS DATA ========= --> <footer role="contentinfo"> <nav role="navigation"> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a id="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a id="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../index.html">Overview</a></li> <li><a href="../../../module-summary.html">Module</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/ConstantCallSite.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><div style="margin-top: 14px;"><strong>Java SE 12 &amp; JDK 12</strong> </div></div> </div> <div class="subNav"> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> </div> <a id="skip.navbar.bottom"> <!-- --> </a> <!-- ======== END OF BOTTOM NAVBAR ======= --> </nav> <p class="legalCopy"><small><a href="https://bugreport.java.com/bugreport/">Report a bug or suggest an enhancement</a><br> For further API reference and developer documentation see the <a href="https://docs.oracle.com/pls/topic/lookup?ctx=javase12.0.2&amp;id=homepage" target="_blank">Java SE Documentation</a>, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples.<br> Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.<br> <a href="../../../../../legal/copyright.html">Copyright</a> &copy; 1993, 2019, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.<br>All rights reserved. Use is subject to <a href="https://www.oracle.com/technetwork/java/javase/terms/license/java12.0.2speclicense.html">license terms</a> and the <a href="https://www.oracle.com/technetwork/java/redist-137594.html">documentation redistribution policy</a>. <!-- Version 12.0.2+10 --></small></p> </footer> </body> </html>
{ "pile_set_name": "Github" }
package com.lfk.justweengine.utils.logger; public enum LogLevel { /** * Prints all logs */ FULL, /** * No log will be printed */ NONE, VERBOSE, DEBUG, INFO, WARN, ERROR, FATAL, ASSERT }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <module external.linked.project.id=":app" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" type="JAVA_MODULE" version="4"> <component name="FacetManager"> <facet type="android-gradle" name="Android-Gradle"> <configuration> <option name="GRADLE_PROJECT_PATH" value=":app" /> </configuration> </facet> <facet type="android" name="Android"> <configuration> <option name="SELECTED_BUILD_VARIANT" value="debug" /> <option name="ASSEMBLE_TASK_NAME" value="assembleDebug" /> <option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" /> <afterSyncTasks> <task>generateDebugSources</task> </afterSyncTasks> <option name="ALLOW_USER_CONFIGURATION" value="false" /> <option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" /> <option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" /> <option name="RES_FOLDERS_RELATIVE_PATH" value="file://$MODULE_DIR$/src/main/res" /> <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" /> </configuration> </facet> </component> <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_8" inherit-compiler-output="false"> <output url="file://$MODULE_DIR$/build/intermediates/classes/debug" /> <output-test url="file://$MODULE_DIR$/build/intermediates/classes/test/debug" /> <exclude-output /> <content url="file://$MODULE_DIR$"> <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/debug" isTestSource="false" generated="true" /> <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/debug" isTestSource="false" generated="true" /> <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" /> <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/debug" isTestSource="false" generated="true" /> <sourceFolder url="file://$MODULE_DIR$/build/generated/source/apt/debug" isTestSource="false" generated="true" /> <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/debug" type="java-resource" /> <sourceFolder url="file://$MODULE_DIR$/build/generated/res/resValues/debug" type="java-resource" /> <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/androidTest/debug" isTestSource="true" generated="true" /> <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/androidTest/debug" isTestSource="true" generated="true" /> <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/androidTest/debug" isTestSource="true" generated="true" /> <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/androidTest/debug" isTestSource="true" generated="true" /> <sourceFolder url="file://$MODULE_DIR$/build/generated/source/apt/androidTest/debug" isTestSource="true" generated="true" /> <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/androidTest/debug" type="java-test-resource" /> <sourceFolder url="file://$MODULE_DIR$/build/generated/res/resValues/androidTest/debug" type="java-test-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/src/debug/shaders" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/src/testDebug/res" type="java-test-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/testDebug/resources" type="java-test-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/testDebug/assets" type="java-test-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/testDebug/aidl" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/src/testDebug/java" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/src/testDebug/rs" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/src/testDebug/shaders" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/src/main/res" type="java-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/src/main/shaders" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/src/test/res" type="java-test-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/test/resources" type="java-test-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/test/assets" type="java-test-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/test/aidl" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/src/test/rs" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/src/test/shaders" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/src/androidTest/shaders" isTestSource="true" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/blame" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental-safeguard" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/jniLibs" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/pre-dexed" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/shaders" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/transforms" /> <excludeFolder url="file://$MODULE_DIR$/build/outputs" /> <excludeFolder url="file://$MODULE_DIR$/build/tmp" /> </content> <orderEntry type="jdk" jdkName="Android API 26 Platform" jdkType="Android SDK" /> <orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="library" exported="" name="constraint-layout-1.0.0-beta3" level="project" /> <orderEntry type="library" exported="" scope="TEST" name="byte-buddy-1.6.14" level="project" /> <orderEntry type="library" exported="" name="support-core-ui-26.0.0-alpha1" level="project" /> <orderEntry type="library" exported="" scope="TEST" name="runner-0.5" level="project" /> <orderEntry type="library" exported="" scope="TEST" name="espresso-idling-resource-2.2.2" level="project" /> <orderEntry type="library" exported="" name="support-fragment-26.0.0-alpha1" level="project" /> <orderEntry type="library" exported="" scope="TEST" name="byte-buddy-agent-1.6.14" level="project" /> <orderEntry type="library" exported="" scope="TEST" name="hamcrest-library-1.3" level="project" /> <orderEntry type="library" exported="" name="support-v4-26.0.0-alpha1" level="project" /> <orderEntry type="library" exported="" name="support-media-compat-26.0.0-alpha1" level="project" /> <orderEntry type="library" exported="" scope="TEST" name="libcore-dex-2" level="project" /> <orderEntry type="library" exported="" name="relinker-1.2.2" level="project" /> <orderEntry type="library" exported="" name="constraint-layout-solver-1.0.0-beta3" level="project" /> <orderEntry type="library" exported="" scope="TEST" name="byte-buddy-android-1.6.14" level="project" /> <orderEntry type="library" exported="" scope="TEST" name="hamcrest-integration-1.3" level="project" /> <orderEntry type="library" exported="" name="commons-cli-1.2" level="project" /> <orderEntry type="library" exported="" name="stetho-1.5.0" level="project" /> <orderEntry type="library" exported="" name="design-26.0.0-alpha1" level="project" /> <orderEntry type="library" exported="" scope="TEST" name="objenesis-2.5" level="project" /> <orderEntry type="library" exported="" name="rxjava-2.0.5" level="project" /> <orderEntry type="library" exported="" scope="TEST" name="dalvik-dx-1" level="project" /> <orderEntry type="library" exported="" name="jsr305-2.0.1" level="project" /> <orderEntry type="library" exported="" scope="TEST" name="espresso-core-2.2.2" level="project" /> <orderEntry type="library" exported="" name="reactive-streams-1.0.0" level="project" /> <orderEntry type="library" exported="" scope="TEST" name="exposed-instrumentation-api-publish-0.5" level="project" /> <orderEntry type="library" exported="" name="stetho_realm-2.1.0" level="project" /> <orderEntry type="library" exported="" name="support-core-utils-26.0.0-alpha1" level="project" /> <orderEntry type="library" exported="" scope="TEST" name="rules-0.5" level="project" /> <orderEntry type="library" exported="" name="transition-26.0.0-alpha1" level="project" /> <orderEntry type="library" exported="" name="support-vector-drawable-26.0.0-alpha1" level="project" /> <orderEntry type="library" exported="" scope="TEST" name="javax.annotation-api-1.2" level="project" /> <orderEntry type="library" exported="" scope="TEST" name="mockito-android-2.8.47" level="project" /> <orderEntry type="library" exported="" scope="TEST" name="javax.inject-1" level="project" /> <orderEntry type="library" exported="" name="realm-annotations-3.5.0" level="project" /> <orderEntry type="library" exported="" name="appcompat-v7-26.0.0-alpha1" level="project" /> <orderEntry type="library" exported="" scope="TEST" name="mockito-core-2.8.47" level="project" /> <orderEntry type="library" exported="" scope="TEST" name="javawriter-2.1.1" level="project" /> <orderEntry type="library" exported="" scope="TEST" name="hamcrest-core-1.3" level="project" /> <orderEntry type="library" exported="" name="realm-android-library-3.5.0" level="project" /> <orderEntry type="library" exported="" scope="TEST" name="junit-4.12" level="project" /> <orderEntry type="library" exported="" name="recyclerview-v7-26.0.0-alpha1" level="project" /> <orderEntry type="library" exported="" name="support-compat-26.0.0-alpha1" level="project" /> <orderEntry type="library" exported="" name="support-annotations-26.0.0-alpha1" level="project" /> <orderEntry type="library" exported="" name="animated-vector-drawable-26.0.0-alpha1" level="project" /> </component> </module>
{ "pile_set_name": "Github" }
class Logstalgia < Formula desc "Web server access log visualizer with retro style" homepage "http://logstalgia.io/" url "https://github.com/acaudwell/Logstalgia/releases/download/logstalgia-1.0.7/logstalgia-1.0.7.tar.gz" sha256 "5553fd03fb7be564538fe56e871eac6e3caf56f40e8abc4602d2553964f8f0e1" bottle do sha256 "248428cb04a28dd6cfac58d860417324e2d3349314d0fcbbf180470e618ca8a0" => :el_capitan sha256 "ae50b8635b79a567f8076581fe74ec5fdeb191acdc9174a64463a5253dde9866" => :yosemite sha256 "bf42ae5b89745a8e16450611d0bfabd5c9b157222abbacff2ecf75f68d6e2da8" => :mavericks end head do url "https://github.com/acaudwell/Logstalgia.git" depends_on "autoconf" => :build depends_on "automake" => :build depends_on "libtool" => :build end depends_on "pkg-config" => :build depends_on "boost" => :build depends_on "glm" => :build depends_on "sdl2" depends_on "sdl2_image" depends_on "freetype" depends_on "glew" depends_on "libpng" depends_on "jpeg" depends_on "pcre" needs :cxx11 def install # clang on Mt. Lion will try to build against libstdc++, # despite -std=gnu++0x ENV.libcxx # For non-/usr/local installs ENV.append "CXXFLAGS", "-I#{HOMEBREW_PREFIX}/include" # Handle building head. system "autoreconf", "-f", "-i" if build.head? system "./configure", "--disable-dependency-tracking", "--prefix=#{prefix}", "--without-x" system "make" system "make", "install" end test do assert_match "Logstalgia v1.", shell_output("#{bin}/logstalgia --help") end end
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Web Prolog</title> <meta name="description" content=""> <meta name="author" content="Torbjörn Lager"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- CSS --> <link rel="stylesheet" href="/vendor/bootstrap/css/bootstrap.min.css"> <link rel="stylesheet" href="/apps/swish/css/swish.css"> <link rel="stylesheet" href="/apps/swish/css/jquery.terminal.css"/> <link rel="shortcut icon" href="/favicon.ico"> </head> <body> <header class="navbar navbar-default navbar-fixed-top"> <div class="container pull-left"> <div class="navbar-header"> <button class="navbar-toggle" type="button" data-toggle="collapse" data-target=".bs-navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a href="/"><img style="position:absolute;top:4px;left:4px;" src="/apps/swish/img/logo.png"></a> <a href="/" style="margin-left:30px;font-size:24px" class="navbar-brand"><b><span style="color:maroon">Web Prolog</span></b></a> </div> <nav class="collapse navbar-collapse bs-navbar-collapse pull-left"> <ul class="nav navbar-nav"> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">File<b class="caret"></b></a> <ul id="file-menu" class="dropdown-menu"> <li><a id="new">New</a></li> <li class="divider"></li> <li><a id="save">Save</a></li> <li class="divider"></li> <li><a id="share">Share...</a></li> <li class="divider"></li> <li><a id="prefs">Preferences...</a></li> <li class="divider"></li> <li><a id="print">Print...</a></li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Edit<b class="caret"></b></a> <ul id="edit-menu" class="dropdown-menu"> <li><a id="undo">Undo</a></li> <li><a id="redo">Redo</a></li> <li class="divider"></li> <li><a id="indent">Indent</a></li> <li><a id="outdent">Outdent</a></li> <li class="divider"></li> <li><a id="comment">Toggle comment</a></li> <li class="divider"></li> <li><a id="find">Find and replace...</a></li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Examples<b class="caret"></b></a> <ul id="example-menu" class="dropdown-menu"> <li><a id="tut">Tutorial</a></li> <li class="divider"></li> <li><a href="/apps/swish/examples/kb.pl">Knowledge bases</a></li> <li><a href="/apps/swish/examples/lists.pl">List processing</a></li> <li><a href="/apps/swish/examples/io.pl">Read and write</a></li> <li><a href="/apps/swish/examples/database.pl">Assert and retract</a></li> <li><a href="/apps/swish/examples/movies.pl">Movie database</a></li> <li><a href="/apps/swish/examples/grammar.pl">DCG grammar</a></li> <!--<li><a href="/apps/swish/examples/eliza.pl">Eliza</a></li>--> <li><a href="/apps/swish/examples/expert-system.pl">Expert system</a></li> <!--<li><a href="/apps/swish/examples/queens.pl">Queens</a></li>--> <li><a href="/apps/swish/examples/clpfd-sudoku.pl">Sudoku (clp(fd))</a></li> <li><a href="/apps/swish/examples/japanese.pl">Japanese source</a></li> <li class="divider"></li> <li><a href="/apps/swish/examples/priority_queue.pl">Priority queue</a></li> <li><a href="/apps/swish/examples/fridge.pl">Fridge simulation</a></li> <li><a href="/apps/swish/examples/pingpong.pl">Playing ping-pong</a></li> <li><a href="/apps/swish/examples/process_ring.pl">Process ring</a></li> <li><a href="/apps/swish/examples/philosophers.pl">Dining philosophers</a></li> <li><a href="/apps/swish/examples/hotswapping.pl">Hotswapping code</a></li> <li><a href="/apps/swish/examples/chat_client.pl">Chat client</a></li> <li><a href="/apps/swish/examples/simple_pengine.pl">Simple pengine</a></li> <li><a href="/apps/swish/examples/simple_rpc.pl">Simple RPC</a></li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Help<b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="#about" data-toggle="modal">About...</a></li> </ul> </li> </ul> </nav> </div> </header> <div id="preferences" class="modal fade" tabindex="-1"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">×</button> <h4 id="myModalLabel">Preferences</h4> </div> <div class="modal-body"> <form class="form-horizontal"> <legend>General</legend> <div class="form-group"> <label class="col-lg-3 control-label" for="theme-menu">Theme </label> <select id="theme-menu" class="input-sm preference-menu"> <option value="brain">Brain</option> </select> </div> <legend>Editor</legend> <div class="form-group"> <label class="col-lg-3 control-label" for="font-family-menu">Font family </label> <select id="font-family-menu" class="input-sm preference-menu"> <option value="'andale mono',monospace">Andale Mono</option> <option value="consolas,monospace">Consolas</option> <option selected value="'courier new',monospace">Courier New</option> <option value="courier,monospace">Courier</option> <option value="monaco,monospace">Monaco</option> <option value="menlo,monospace">Menlo</option> <option value="'ubuntu mono',monospace">Ubuntu Mono</option> <option value="'dejavu',monospace">Dejavu</option> </select> </div> <div class="form-group"> <label class="col-lg-3 control-label" for="font-size-menu">Font size </label> <select id="font-size-menu" class="input-sm preference-menu"> <option value="10">10</option> <option value="12">12</option> <option selected value="14">14</option> <option value="16">16</option> <option value="18">18</option> <option value="20">20</option> </select> </div> <div class="form-group"> <label class="col-lg-3 control-label" for="tab-size-menu">Tab size </label> <select id="tab-size-menu" class="input-sm preference-menu"> <option value="2">2</option> <option selected value="4">4</option> <option value="6">6</option> <option value="8">8</option> </select> </div> <div class="form-group"> <label class="col-lg-3 control-label" for="tab-soft-checkbox">Use soft tabs</label> <input id="tab-soft-checkbox" class="input-sm" checked type="checkbox"> </div> <div class="form-group"> <label class="col-lg-3 control-label" for="line-wrap-checkbox">Lines</label> <label class="checkbox-inline"><input id="line-wrap-checkbox" checked type="checkbox" class=""> Wrap</label> <label class="checkbox-inline"><input id="line-highlight-checkbox" type="checkbox"> Highlight current</label> <label class="checkbox-inline"><input id="line-numbering-checkbox" checked type="checkbox"> Show numbers</label> </div> </form> </div> </div> </div> </div> <div id="share-dialog" class="modal fade" tabindex="-1"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">×</button> <h3 id="myModalLabel">Share your program!</h3> </div> <div class="modal-body"> <p>Your program is saved to the <span style="color:maroon">Web Prolog</span> node for a period of at least one month. A link to it is given below. Copy the link, send it around, do what you want with it. Anyone in possession of the link will be able to access <span style="color:maroon">Web Prolog</span> with your program loaded and ready to run.</p> <p> Link: <input style="width:520px;" class="input-sm" type="text" id="url" onclick="this.select()" value=""> </p> </div> </div> </div> </div> <div id="about" class="modal fade" tabindex="-1"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">×</button> <h4 id="myModalLabel2">About <span style="color:maroon">Web Prolog</span><span class="pull-right">Version 0.1&nbsp;&nbsp;</span></h4> </div> <div class="modal-body"> <p>This is a proof-of-concept online demonstration and tutorial of <span style="color:maroon">Web Prolog</span>, a proposal for a web logic programming language. Design and implementation by Torbjörn Lager, with a lot of help from Jan Wielemaker. </p> </div> </div> </div> </div> <div class="container"> <pre id="editor"></pre> <div id="tutorial-container"></div> <div id="shell"></div> <div id="controls" onclick="return false"> <div> <div> <div> <button id="ask-btn" class="btn btn-xs btn-primary">Ask</button> <button id="next-btn" class="btn btn-xs btn-success" disabled>Next</button> <button id="stop-btn" class="btn btn-xs btn-warning" disabled>Stop</button> <button id="abort-btn" class="btn btn-xs btn-danger" disabled>Abort</button> &nbsp;&nbsp;&nbsp; <div class="btn-group dropup"> <button id="examples-btn" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown" disabled> Examples <span class="caret"></span> </button> <ul id="examples" class="dropdown-menu"> </ul> </div> <div class="btn-group dropup"> <button id="history-btn" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown"> History <span class="caret"></span> </button> <ul id="history" class="dropdown-menu"></ul> </div> &nbsp;&nbsp; <label class="checkbox-inline"><input id="json-trace-checkbox" type="checkbox"> Trace JSON</label> <div class="btn-group pull-right"> <button id="clear-btn-query" class="btn btn-default btn-xs">Clear</button> </div> </div> </div> </div> <div> </div> </div> </div> <header class="navbar navbar-default navbar-fixed-bottom bs-docs-nav"> <div class="footer"> <p class="muted credit pull-left"> Inspired by Erlang, powered by <a target="_blank" href="http://www.swi-prolog.org/">SWI-Prolog</a>. </p> <input class="pull-right" id="slider" type='range' step='1' min='30' max='70' /> </div> </header> <!-- Placed at the end of the document so the pages load faster --> <script src="/vendor/jquery/jquery-2.0.3.min.js"></script> <script src="/vendor/bootstrap/js/bootstrap.min.js"></script> <script src="/vendor/src-min-noconflict/ace.js" charset="utf-8"></script> <script src="/apps/swish/js/jquery.mousewheel-min.js"></script> <script src="/apps/swish/js/jquery.terminal.min.js"></script> <script src="/apps/swish/js/swish.js" charset="utf-8"></script> <script> var pid; var gterm; var gmysend; var state = 1; var currcommand = ""; var trace = !$("#json-trace-checkbox").is(':checked'); function to_text(data) { var text = []; var hasBindings = false; for (var key in data) { var value = data[key]; if (Array.isArray(value)) { value = "[" + value + "]"; } if (value.charAt(0) != "_") { text.push(key + " = " + value); text.push(", \n"); hasBindings = true; } } text.pop(); // get rid of the last comma text.push(" "); if (hasBindings) { return text.join(""); } else { return "true "; } } function report(data) { return to_text(data[0]); } function speak(string) { var uu = new SpeechSynthesisUtterance(string); speechSynthesis.speak(uu); } $(document).ready(function($) { var ws = new WebSocket('ws://localhost:3060/ws', 'pcp-0.2'); function mysend(json) { var jsonstr = JSON.stringify(json, null, 1); if (!trace) { gterm.echo(jsonstr, { finalize: function(div) { div.css("color", "blue"); } }); }; ws.send(jsonstr); } gmysend = mysend; ws.onopen = function(message) { mysend({ command:"pengine_spawn", options:"[exit(false), format('json-s')]" }); }; ws.onerror = function(e) { console.log(e); }; ws.onclose = function(e) { console.log(e); }; ws.onmessage = function(message) { var msg = JSON.parse(message.data); if (msg.type == "spawned") { pid = msg.pid; } $('#tutorial-container').load('/apps/swish/tutorial.html', function() { recursiveReplaceHost(document.body, window.location.origin); recursiveReplacePengine(document.body, pid); }); disableButtons(false, true, true, true); }; $('#shell').terminal(function(command, term) { ws.onmessage = function(message) { term.resume(); var msgstr = message.data; msg = JSON.parse(msgstr); if (!trace) { term.echo(JSON.stringify(msg, null, 1), { finalize: function(div) { div.css("color", "green"); } }); } var type = msg.type; if (type == "success") { if (msg.more) { state = 4; term.set_prompt(report(msg.data)); disableButtons(true, false, false, true); } else { state = 1; term.echo(report(msg.data).trim() + "."); term.set_prompt(myprompt); disableButtons(false, true, true, true); } term.scroll_to_bottom(); } else if (type == "failure") { state = 1; term.echo("false."); term.set_prompt(myprompt); term.scroll_to_bottom(); disableButtons(false, true, true, true); } else if (type == "error") { state = 1; term.error(msg.data); term.set_prompt(myprompt); term.scroll_to_bottom(); disableButtons(false, true, true, true); } else if (type == "stop") { state = 1; if (!trace) { term.update(-3, term.get_prompt().trim() + "."); } else { term.update(-1, term.get_prompt().trim() + "."); } term.set_prompt(myprompt); term.scroll_to_bottom(); disableButtons(false, true, true, true); } else if (type == "prompt") { state = 3; term.set_prompt(msg.data + ": "); } else if (type == "output") { term.echo(msg.data); term.set_prompt(""); } else if (type == "speak") { speak(msg.data); term.set_prompt(""); } else if (type == "echo") { term.echo(msg.data); term.set_prompt(""); } else if (type == "abort") { term.echo("Aborted"); term.scroll_to_bottom(); disableButtons(false, true, true, true); } else if (type == "exit") { term.echo("Exiting"); term.pop(); term.echo("Exiting"); if (ws) ws.close(); } else { term.echo(data); } }; myprompt = " \n?- "; if (env.dirty) { term.echo("Consulting from editor."); var program = getProgram().replace(/'/g,"\\'"); console.log(program); mysend({ command:"pengine_ask", pid:pid, query:"consult_text('" + program + "')" }); env.dirty = false; term.set_prompt(""); } if (state == 1) { if (command.trim() == "") { term.set_prompt(myprompt); term.scroll_to_bottom(); disableButtons(false, true, true, true); } else if (command.trim().endsWith('.')) { currcommand += command.trim().slice(0, -1); state = 2; mysend({ command:"pengine_ask", pid:pid, query:currcommand }); updateHistory(currcommand); currcommand = ""; term.pause(); disableButtons(true, true, true, false); } else { term.set_prompt(" "); currcommand += command; } } else if (state == 4) { if (command == ";") { state = 2; mysend({ command:"pengine_next", pid:pid }); term.pause(); disableButtons(true, true, true, false); } else if (command == "") { mysend({ command:"pengine_stop", pid:pid }); term.pause(); disableButtons(true, true, true, false); } } else if (state == 3) { state = 2; if (command !== "") { mysend({ command:"pengine_respond", pid:pid, term:command }); } disableButtons(true, true, true, false); } }, { greetings:'Welcome to SWI Web Prolog!\n', prompt:'?- ', onInit: function(term) { gterm = term; }, keymap: { 'CTRL+C': function(e, a) { if (state == 2 || state == 3) { mysend({ command:"pengine_abort", pid:pid }); gterm.pause(); return false; } } }, keypress: function(e) { if (state == 4 && (e.which == 59 || e.which == 32)) { gterm.echo(gterm.get_prompt() + ";"); mysend({ command:"pengine_next", pid:pid }); gterm.pause(); disableButtons(true, true, true, false); return false; } }, convertLinks: false, historyFilter: function(command) { if (command == "" ) return false; if (command == ";" ) return false; return true; } }); }); </script> </body> </html>
{ "pile_set_name": "Github" }
# GeoFirestore for iOS — Realtime location queries with Firestore GeoFirestore is an open-source library for Swift that allows you to store and query a set of documents based on their geographic location. At its heart, GeoFirestore simply stores locations with string keys. Its main benefit however, is the possibility of querying documents within a given geographic area - all in realtime. GeoFirestore uses the Firestore database for data storage, allowing query results to be updated in realtime as they change. GeoFirestore selectively loads only the data near certain locations, keeping your applications light and responsive, even with extremely large datasets. A compatible GeoFirestore client is also available for [Android](https://github.com/imperiumlabs/GeoFirestore-Android). ### Integrating GeoFirestore with your data GeoFirestore is designed as a lightweight add-on to Firestore. However, to keep things simple, GeoFirestore stores data in its own format and its own location within your Firestore database. This allows your existing data format and security rules to remain unchanged and for you to add GeoFirestore as an easy solution for geo queries without modifying your existing data. ### Example usage Assume you are building an app to rate bars, and you store all information for a bar (e.g. name, business hours and price range) at `collection(bars).document(bar-id)`. Later, you want to add the possibility for users to search for bars in their vicinity. This is where GeoFirestore comes in. You can store the location for each bar document using GeoFirestore. GeoFirestore then allows you to easily query which bar are nearby. ## Example To run the example project, clone the repo, and run `pod repo update` and `pod install` from the Example directory first. ## Downloading GeoFirestore for iOS If you're using [CocoaPods](https://cocoapods.org/) add the following to your Podfile: ``` pod 'Geofirestore' ``` Then run the following in terminal: ``` pod repo update pod install ``` ## Getting Started with Firestore GeoFirestore requires the Firestore database in order to store location data. You can [learn more about Firestore here](https://firebase.google.com/docs/firestore/). ## Using GeoFirestore ### GeoFirestore A `GeoFirestore` object is used to read and write geo location data to your Firestore database and to create queries. To create a new `GeoFirestore` instance you need to attach it to a Firestore collection reference: ````swift import Firebase import Geofirestore let geoFirestoreRef = Firestore.firestore().collection("my-collection") let geoFirestore = GeoFirestore(collectionRef: geoFirestoreRef) ```` #### Setting location data To set the location of a document simply call the `setLocation` method: ````swift geoFirestore.setLocation(location: CLLocation(latitude: 37.7853889, longitude: -122.4056973), forDocumentWithID: "que8B9fxxjcvbC81h32VRjeBSUW2") { (error) in if let error = error { print("An error occured: \(error)") } else { print("Saved location successfully!") } } ```` Alternatively set the location using a `GeoPoint` : ````swift geoFirestore.setLocation(geopoint: GeoPoint(latitude: 37.7853889, longitude: -122.4056973), forDocumentWithID: "que8B9fxxjcvbC81h32VRjeBSUW2") { (error) in if let error = error { print("An error occured: \(error)") } else { print("Saved location successfully!") } } ```` To remove a location and delete the location from your database simply call: ````swift geoFirestore.removeLocation(forDocumentWithID: "que8B9fxxjcvbC81h32VRjeBSUW2") ```` #### Retrieving a location Retrieving locations happens with callbacks. If the document is not present in GeoFirestore, the callback will be called with `nil`. If an error occurred, the callback is passed the error and the location will be `nil`. ````swift geoFirestore.getLocation(forDocumentWithID: "que8B9fxxjcvbC81h32VRjeBSUW2") { (location: CLLocation?, error) in if let error = error { print("An error occurred: \(error)") } else if let location = location { print("Location: [\(location.coordinate.latitude), \(location.coordinate.longitude)]") } else { print("GeoFirestore does not contain a location for this document") } } ```` Alternatively get the location as a `GeoPoint` : ````swift geoFirestore.getLocation(forDocumentWithID: "que8B9fxxjcvbC81h32VRjeBSUW2") { (location: GeoPoint?, error) in if let error = error { print("An error occurred: \(error)") } else if let location = location { print("Location: [\(location.latitude), \(location.longitude)]") } else { print("GeoFirestore does not contain a location for this document") } } ```` ### GeoFirestore Queries GeoFirestore allows you to query all documents within a geographic area using `GFSQuery` objects. As the locations for documents change, the query is updated in realtime and fires events letting you know if any relevant documents have moved. `GFSQuery` parameters can be updated later to change the size and center of the queried area. ````swift // Query using CLLocation let center = CLLocation(latitude: 37.7832889, longitude: -122.4056973) // Query locations at [37.7832889, -122.4056973] with a radius of 600 meters var circleQuery = geoFirestore.query(withCenter: center, radius: 0.6) // Query using GeoPoint let center2 = GeoPoint(latitude: 37.7832889, longitude: -122.4056973) // Query locations at [37.7832889, -122.4056973] with a radius of 600 meters var circleQuery2 = geoFirestore.query(withCenter: center2, radius: 0.6) // Query location by region let span = MKCoordinateSpanMake(0.001, 0.001) let region = MKCoordinateRegionMake(center.coordinate, span) var regionQuery = geoFirestore.query(inRegion: region) ```` #### Receiving events for geo queries There are three kinds of events that can occur with a geo query: 1. **Document Entered**: The location of a document now matches the query criteria. 2. **Document Exited**: The location of a document no longer matches the query criteria. 3. **Document Moved**: The location of a document changed but the location still matches the query criteria. Document entered events will be fired for all documents initially matching the query as well as any time afterwards that a document enters the query. Document moved and document exited events are guaranteed to be preceded by a document entered event. To observe events for a geo query you can register a callback with `observe:with:`: ````swift let queryHandle = query.observe(.documentEntered, with: { (key, location) in print("The document with documentID '\(key)' entered the search area and is at location '\(location)'") }) ```` To cancel one or all callbacks for a geo query, call `removeObserver:withHandle:` or `removeAllObservers:`, respectively. #### Waiting for queries to be "ready" Sometimes you want to know when the data for all the initial documents has been loaded from the server and the corresponding events for those documents have been fired. For example, you may want to hide a loading animation after your data has fully loaded. `GFSQuery` offers a method to listen for these ready events: ````swift query.observeReady { print("All initial data has been loaded and events have been fired!") } ```` Note that locations might change while initially loading the data and document moved and document exited events might therefore still occur before the ready event was fired. When the query criteria is updated, the existing locations are re-queried and the ready event is fired again once all events for the updated query have been fired. This includes document exited events for documents that no longer match the query. #### Updating the query criteria To update the query criteria you can use the `center` and `radius` properties on the `GFSQuery` object. Document exited and document entered events will be fired for documents moving in and out of the old and new search area, respectively. No document moved events will be fired as a result of the query criteria changing; however, document moved events might occur independently. #### Convenient extensions To make it easier to convert between a `GeoPoint` and a `CLLocation` we have provided some useful extensions: ````swift let cllocation = CLLocation(latitude: 37.7832889, longitude: -122.4056973) let geopoint = GeoPoint(latitude: 37.7832889, longitude: -122.4056973) // Converting from CLLocation to Geopoint let loc1: GeoPoint = cllocation.geopointValue() let loc2: GeoPoint = GeoPoint.geopointWithLocation(location: cllocation) // Converting from Geopoint to CLLocation let loc3: CLLocation = geopoint.locationValue() let loc4: CLLocation = CLLocation.locationWithGeopoint(geopoint: geopoint) ```` ## API Reference & Documentation Full API reference and documentation is available [here](http://imperiumlabs.org/GeoFirestore-iOS/) ## License GeoFirestore is available under the MIT license. See the LICENSE file for more info. Copyright (c) 2018 Imperium Labs
{ "pile_set_name": "Github" }
"use strict"; // Use the fastest means possible to execute a task in its own turn, with // priority over other events including IO, animation, reflow, and redraw // events in browsers. // // An exception thrown by a task will permanently interrupt the processing of // subsequent tasks. The higher level `asap` function ensures that if an // exception is thrown by a task, that the task queue will continue flushing as // soon as possible, but if you use `rawAsap` directly, you are responsible to // either ensure that no exceptions are thrown from your task, or to manually // call `rawAsap.requestFlush` if an exception is thrown. module.exports = rawAsap; function rawAsap(task) { if (!queue.length) { requestFlush(); flushing = true; } // Equivalent to push, but avoids a function call. queue[queue.length] = task; } var queue = []; // Once a flush has been requested, no further calls to `requestFlush` are // necessary until the next `flush` completes. var flushing = false; // `requestFlush` is an implementation-specific method that attempts to kick // off a `flush` event as quickly as possible. `flush` will attempt to exhaust // the event queue before yielding to the browser's own event loop. var requestFlush; // The position of the next task to execute in the task queue. This is // preserved between calls to `flush` so that it can be resumed if // a task throws an exception. var index = 0; // If a task schedules additional tasks recursively, the task queue can grow // unbounded. To prevent memory exhaustion, the task queue will periodically // truncate already-completed tasks. var capacity = 1024; // The flush function processes all tasks that have been scheduled with // `rawAsap` unless and until one of those tasks throws an exception. // If a task throws an exception, `flush` ensures that its state will remain // consistent and will resume where it left off when called again. // However, `flush` does not make any arrangements to be called again if an // exception is thrown. function flush() { while (index < queue.length) { var currentIndex = index; // Advance the index before calling the task. This ensures that we will // begin flushing on the next task the task throws an error. index = index + 1; queue[currentIndex].call(); // Prevent leaking memory for long chains of recursive calls to `asap`. // If we call `asap` within tasks scheduled by `asap`, the queue will // grow, but to avoid an O(n) walk for every task we execute, we don't // shift tasks off the queue after they have been executed. // Instead, we periodically shift 1024 tasks off the queue. if (index > capacity) { // Manually shift all values starting at the index back to the // beginning of the queue. for (var scan = 0, newLength = queue.length - index; scan < newLength; scan++) { queue[scan] = queue[scan + index]; } queue.length -= index; index = 0; } } queue.length = 0; index = 0; flushing = false; } // `requestFlush` is implemented using a strategy based on data collected from // every available SauceLabs Selenium web driver worker at time of writing. // https://docs.google.com/spreadsheets/d/1mG-5UYGup5qxGdEMWkhP6BWCz053NUb2E1QoUTU16uA/edit#gid=783724593 // Safari 6 and 6.1 for desktop, iPad, and iPhone are the only browsers that // have WebKitMutationObserver but not un-prefixed MutationObserver. // Must use `global` instead of `window` to work in both frames and web // workers. `global` is a provision of Browserify, Mr, Mrs, or Mop. var BrowserMutationObserver = global.MutationObserver || global.WebKitMutationObserver; // MutationObservers are desirable because they have high priority and work // reliably everywhere they are implemented. // They are implemented in all modern browsers. // // - Android 4-4.3 // - Chrome 26-34 // - Firefox 14-29 // - Internet Explorer 11 // - iPad Safari 6-7.1 // - iPhone Safari 7-7.1 // - Safari 6-7 if (typeof BrowserMutationObserver === "function") { requestFlush = makeRequestCallFromMutationObserver(flush); // MessageChannels are desirable because they give direct access to the HTML // task queue, are implemented in Internet Explorer 10, Safari 5.0-1, and Opera // 11-12, and in web workers in many engines. // Although message channels yield to any queued rendering and IO tasks, they // would be better than imposing the 4ms delay of timers. // However, they do not work reliably in Internet Explorer or Safari. // Internet Explorer 10 is the only browser that has setImmediate but does // not have MutationObservers. // Although setImmediate yields to the browser's renderer, it would be // preferrable to falling back to setTimeout since it does not have // the minimum 4ms penalty. // Unfortunately there appears to be a bug in Internet Explorer 10 Mobile (and // Desktop to a lesser extent) that renders both setImmediate and // MessageChannel useless for the purposes of ASAP. // https://github.com/kriskowal/q/issues/396 // Timers are implemented universally. // We fall back to timers in workers in most engines, and in foreground // contexts in the following browsers. // However, note that even this simple case requires nuances to operate in a // broad spectrum of browsers. // // - Firefox 3-13 // - Internet Explorer 6-9 // - iPad Safari 4.3 // - Lynx 2.8.7 } else { requestFlush = makeRequestCallFromTimer(flush); } // `requestFlush` requests that the high priority event queue be flushed as // soon as possible. // This is useful to prevent an error thrown in a task from stalling the event // queue if the exception handled by Node.js’s // `process.on("uncaughtException")` or by a domain. rawAsap.requestFlush = requestFlush; // To request a high priority event, we induce a mutation observer by toggling // the text of a text node between "1" and "-1". function makeRequestCallFromMutationObserver(callback) { var toggle = 1; var observer = new BrowserMutationObserver(callback); var node = document.createTextNode(""); observer.observe(node, {characterData: true}); return function requestCall() { toggle = -toggle; node.data = toggle; }; } // The message channel technique was discovered by Malte Ubl and was the // original foundation for this library. // http://www.nonblocking.io/2011/06/windownexttick.html // Safari 6.0.5 (at least) intermittently fails to create message ports on a // page's first load. Thankfully, this version of Safari supports // MutationObservers, so we don't need to fall back in that case. // function makeRequestCallFromMessageChannel(callback) { // var channel = new MessageChannel(); // channel.port1.onmessage = callback; // return function requestCall() { // channel.port2.postMessage(0); // }; // } // For reasons explained above, we are also unable to use `setImmediate` // under any circumstances. // Even if we were, there is another bug in Internet Explorer 10. // It is not sufficient to assign `setImmediate` to `requestFlush` because // `setImmediate` must be called *by name* and therefore must be wrapped in a // closure. // Never forget. // function makeRequestCallFromSetImmediate(callback) { // return function requestCall() { // setImmediate(callback); // }; // } // Safari 6.0 has a problem where timers will get lost while the user is // scrolling. This problem does not impact ASAP because Safari 6.0 supports // mutation observers, so that implementation is used instead. // However, if we ever elect to use timers in Safari, the prevalent work-around // is to add a scroll event listener that calls for a flush. // `setTimeout` does not call the passed callback if the delay is less than // approximately 7 in web workers in Firefox 8 through 18, and sometimes not // even then. function makeRequestCallFromTimer(callback) { return function requestCall() { // We dispatch a timeout with a specified delay of 0 for engines that // can reliably accommodate that request. This will usually be snapped // to a 4 milisecond delay, but once we're flushing, there's no delay // between events. var timeoutHandle = setTimeout(handleTimer, 0); // However, since this timer gets frequently dropped in Firefox // workers, we enlist an interval handle that will try to fire // an event 20 times per second until it succeeds. var intervalHandle = setInterval(handleTimer, 50); function handleTimer() { // Whichever timer succeeds will cancel both timers and // execute the callback. clearTimeout(timeoutHandle); clearInterval(intervalHandle); callback(); } }; } // This is for `asap.js` only. // Its name will be periodically randomized to break any code that depends on // its existence. rawAsap.makeRequestCallFromTimer = makeRequestCallFromTimer; // ASAP was originally a nextTick shim included in Q. This was factored out // into this ASAP package. It was later adapted to RSVP which made further // amendments. These decisions, particularly to marginalize MessageChannel and // to capture the MutationObserver implementation in a closure, were integrated // back into ASAP proper. // https://github.com/tildeio/rsvp.js/blob/cddf7232546a9cf858524b75cde6f9edf72620a7/lib/rsvp/asap.js
{ "pile_set_name": "Github" }
/* * jQuery Simple Templates plugin 1.1.1 * * http://andrew.hedges.name/tmpl/ * http://docs.jquery.com/Plugins/Tmpl * * Copyright (c) 2008 Andrew Hedges, andrew@hedges.name * * Usage: $.tmpl('<div class="#{classname}">#{content}</div>', { 'classname' : 'my-class', 'content' : 'My content.' }); * * The changes for version 1.1 were inspired by the discussion at this thread: * http://groups.google.com/group/jquery-ui/browse_thread/thread/45d0f5873dad0178/0f3c684499d89ff4 * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html */ (function($) { $.extend({ // public interface: $.tmpl tmpl : function(tmpl, vals) { var rgxp, repr; // default to doing no harm tmpl = tmpl || ''; vals = vals || {}; // regular expression for matching our placeholders; e.g., #{my-cLaSs_name77} rgxp = /#\{([^{}]*)}/g; // function to making replacements repr = function (str, match) { return typeof vals[match] === 'string' || typeof vals[match] === 'number' ? vals[match] : str; }; return tmpl.replace(rgxp, repr); } }); })(jQuery);
{ "pile_set_name": "Github" }
module.exports = preferredCharsets; preferredCharsets.preferredCharsets = preferredCharsets; function parseAcceptCharset(accept) { var accepts = accept.split(','); for (var i = 0, j = 0; i < accepts.length; i++) { var charset = parseCharset(accepts[i].trim(), i); if (charset) { accepts[j++] = charset; } } // trim accepts accepts.length = j; return accepts; } function parseCharset(s, i) { var match = s.match(/^\s*(\S+?)\s*(?:;(.*))?$/); if (!match) return null; var charset = match[1]; var q = 1; if (match[2]) { var params = match[2].split(';') for (var i = 0; i < params.length; i ++) { var p = params[i].trim().split('='); if (p[0] === 'q') { q = parseFloat(p[1]); break; } } } return { charset: charset, q: q, i: i }; } function getCharsetPriority(charset, accepted, index) { var priority = {o: -1, q: 0, s: 0}; for (var i = 0; i < accepted.length; i++) { var spec = specify(charset, accepted[i], index); if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { priority = spec; } } return priority; } function specify(charset, spec, index) { var s = 0; if(spec.charset.toLowerCase() === charset.toLowerCase()){ s |= 1; } else if (spec.charset !== '*' ) { return null } return { i: index, o: spec.i, q: spec.q, s: s } } function preferredCharsets(accept, provided) { // RFC 2616 sec 14.2: no header = * var accepts = parseAcceptCharset(accept === undefined ? '*' : accept || ''); if (!provided) { // sorted list of all charsets return accepts.filter(isQuality).sort(compareSpecs).map(function getCharset(spec) { return spec.charset; }); } var priorities = provided.map(function getPriority(type, index) { return getCharsetPriority(type, accepts, index); }); // sorted list of accepted charsets return priorities.filter(isQuality).sort(compareSpecs).map(function getCharset(priority) { return provided[priorities.indexOf(priority)]; }); } function compareSpecs(a, b) { return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; } function isQuality(spec) { return spec.q > 0; }
{ "pile_set_name": "Github" }
<#-- /** $id:null$ $author:wmzsoft@gmail.com #date:2013.08 **/ --> <!--table-toot.ftl begin--> <#if (parameters.footVisible!true)> <div style="float:left" id="${parameters.id!'test'}_info" role="status" aria-live="polite"> ${parameters.tagbundle['table-tfoot.totalpre']!}&nbsp;${parameters.count!0} &nbsp;${parameters.tagbundle['table-tfoot.totaltail']!} <input type='text' class='pageSelected' id='${parameters.id}_pagesize' name='pagesize' value='${parameters.pagesize!20}' SIZE='3' maxlength='3' onpaste="return pagePaste()" onblur="pageBlur(this,'${parameters.id}')" originValue='${parameters.pagesize!20}' onkeypress="return pageKeypress(this, event)"> &nbsp;( <#lt><span <#rt> <#if ((parameters.pagesize!'')=='20')> <#lt> class="pagesize-select" <#rt> </#if> <#lt> onclick="spanSetPageSize('${parameters.id}',20);">20</span>,<#rt> <#lt><span <#rt> <#if ((parameters.pagesize!'')=='50')> <#lt> class="pagesize-select" <#rt> </#if> <#lt> onclick="spanSetPageSize('${parameters.id}',50);">50</span>,<#rt> <#lt><span <#rt> <#if ((parameters.pagesize!'')=='80')> <#lt> class="pagesize-select" <#rt> </#if> <#lt> onclick="spanSetPageSize('${parameters.id}',80);">80</span>,<#rt> <#lt><span <#rt> <#if ((parameters.pagesize!'')=='100')> <#lt> class="pagesize-select" <#rt> </#if> <#lt> onclick="spanSetPageSize('${parameters.id}',100);">100</span><#rt> )&nbsp;${parameters.tagbundle['table-tfoot.items']!}<#t> </div> <div id="${parameters.id!'test'}_paginate" style="float:right"> ${parameters.pagenum!0}&nbsp;/&nbsp;${parameters.pagecount!0}${parameters.tagbundle['table-tfoot.cpagetail']!} <#if ((parameters.pagenum!1)>1)> <a href='javascript:pageFirst("${parameters.id}")' class="table-tfoot-page-first"></a> <a href='javascript:pagePre("${parameters.id}")' class="table-tfoot-page-pre"></a> </#if><#rt> <#if ((parameters.pagenum!1) < (parameters.pagecount!1))> <a href='javascript:pageNext("${parameters.id}")' class="table-tfoot-page-next"></a> <a href='javascript:pageLast("${parameters.id}")' class="table-tfoot-page-last"></a> </#if> ${parameters.tagbundle['table-tfoot.goto']!} <INPUT TYPE='text' id='${parameters.id}_topage' NAME='gotoPage' class="gotoPage" value='1' onpaste="return pagePaste()" onkeypress='pageGotoKeypress("${parameters.id}", event)' SIZE='3' maxlength='5'>${parameters.tagbundle['table-tfoot.cpagetail']!} <input type='button' value='GO' onclick='pageGoto("${parameters.id}")' class='btn_href_GO'> <a href="javascript:exportExcel('${parameters.id!x}');" title="导出Excel" class="expexcel"> <img border='0' src="${baseSkin}/images/excel.png"/> </a> <a href="javascript:exportWord('${parameters.id!x}');" title="导出Word" class="expword"> <img border='0' src="${baseSkin}/images/word.png"/> </a> <a href="javascript:custcolumn('${parameters.id!x}');" title="自定义列" class="custcolumn"> <img border='0' src="${baseSkin}/images/custom.jpg"/> </a> <a href="javascript:tableFullScreen('${parameters.id!x}');" title="全屏" class="detach"> <img border='0' src="${baseSkin}/images/full.png"/> </a> <input type="hidden" id="${parameters.id}_pagenum" name="pagenum" value="${parameters.pagenum!1}"> <input type="hidden" id="${parameters.id}_pagecount" name="pagecount" value="${parameters.pagecount!0}"> <input type="hidden" id="${parameters.id}_pagesort" name="orderby" value="${parameters.orderby!''}"> </div> </#if> <!--table-toot.ftl end-->
{ "pile_set_name": "Github" }
/* webymsg.c * Web Messenger Yahoo! * With and without HTTP transport * * $Id: $ * * Xplico - Internet Traffic Decoder * By Gianluca Costa <g.costa@xplico.org> * Copyright 2013 Gianluca Costa. Web: www.xplico.org * * * 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. */ #include <pcap.h> #include <arpa/inet.h> #include <string.h> #include <stdio.h> #include "proto.h" #include "dmemory.h" #include "etypes.h" #include "log.h" #include "pei.h" #include "http.h" #include "webymsg.h" static int prot_id; static int pei_url_id; static int pei_client_id; static int pei_host_id; static int pei_req_header_id; static int pei_req_body_id; static int pei_res_header_id; static int pei_res_body_id; static PktDissector HttpPktDis; /* this functions create the http pei for all http packets */ static int WebMsnYahooPei(packet* pkt) { http_msg *msg; pei *ppei; pei_component *cmpn; ppei = NULL; /* display info */ msg = (http_msg *)pkt->data; /* pei */ PeiNew(&ppei, prot_id); PeiCapTime(ppei, pkt->cap_sec); PeiMarker(ppei, pkt->serial); PeiStackFlow(ppei, pkt->stk); /* url */ PeiNewComponent(&cmpn, pei_url_id); PeiCompCapTime(cmpn, msg->start_cap); PeiCompCapEndTime(cmpn, msg->end_cap); PeiCompAddStingBuff(cmpn, msg->uri); PeiAddComponent(ppei, cmpn); /* clent */ PeiNewComponent(&cmpn, pei_client_id); PeiCompCapTime(cmpn, msg->start_cap); PeiCompCapEndTime(cmpn, msg->end_cap); PeiCompAddStingBuff(cmpn, msg->client); PeiAddComponent(ppei, cmpn); /* host */ PeiNewComponent(&cmpn, pei_host_id); PeiCompCapTime(cmpn, msg->start_cap); PeiCompCapEndTime(cmpn, msg->end_cap); PeiCompAddStingBuff(cmpn, msg->host); PeiAddComponent(ppei, cmpn); /* req hdr */ if (msg->req_hdr_file) { PeiNewComponent(&cmpn, pei_req_header_id); PeiCompCapTime(cmpn, msg->start_cap); PeiCompCapEndTime(cmpn, msg->end_cap); PeiAddComponent(ppei, cmpn); PeiCompAddFile(cmpn, NULL, msg->req_hdr_file, msg->req_hdr_size); if (msg->error && msg->req_body_size == 0 && msg->res_hdr_size == 0) { PeiCompError(cmpn, ELMT_ER_PARTIAL); } } /* req body */ if (msg->req_body_size) { PeiNewComponent(&cmpn, pei_req_body_id); PeiCompCapTime(cmpn, msg->start_cap); PeiCompCapEndTime(cmpn, msg->end_cap); PeiAddComponent(ppei, cmpn); PeiCompAddFile(cmpn, NULL, msg->req_body_file, msg->req_body_size); if (msg->error && msg->res_hdr_size == 0) { PeiCompError(cmpn, ELMT_ER_PARTIAL); } } /* res hdr */ if (msg->res_hdr_size) { PeiNewComponent(&cmpn, pei_res_header_id); PeiCompCapTime(cmpn, msg->start_cap); PeiCompCapEndTime(cmpn, msg->end_cap); PeiAddComponent(ppei, cmpn); PeiCompAddFile(cmpn, NULL, msg->res_hdr_file, msg->res_hdr_size); if (msg->error && msg->res_body_size == 0) { PeiCompError(cmpn, ELMT_ER_PARTIAL); } } /* res body */ if (msg->res_body_size) { PeiNewComponent(&cmpn, pei_res_body_id); PeiCompCapTime(cmpn, msg->start_cap); PeiCompCapEndTime(cmpn, msg->end_cap); PeiAddComponent(ppei, cmpn); PeiCompAddFile(cmpn, NULL, msg->res_body_file, msg->res_body_size); if (msg->error == 2) { PeiCompError(cmpn, ELMT_ER_HOLE); } else if (msg->error != 0) { PeiCompError(cmpn, ELMT_ER_PARTIAL); } } /* insert pei */ PeiIns(ppei); return 0; } static packet* WebMsnYahooDissector(packet *pkt) { http_msg *msg; bool ins; /* display info */ msg = (http_msg *)pkt->data; ins = FALSE; #ifdef XPL_CHECK_CODE if (msg->serial == 0) { LogPrintf(LV_FATAL, "WebMsnYahoo serial error"); exit(-1); } #endif if (msg->uri != NULL) { /* yahoo! web mail */ if (strstr(msg->uri, "&sid=") != NULL) { if (strstr(msg->uri, "/pushchannel/") != NULL || strstr(msg->uri, "?action=send-message&") != NULL) { /* send to manipulator */ WebMsnYahooPei(pkt); ins = TRUE; } } } if (ins == FALSE && HttpPktDis != NULL) { /* http pei generation and insertion */ HttpPktDis(pkt); } else { /* free memory */ HttpMsgFree(msg); PktFree(pkt); } return NULL; } int DissecRegist(const char *file_cfg) { proto_dep dep; pei_cmpt peic; memset(&dep, 0, sizeof(proto_dep)); memset(&peic, 0, sizeof(pei_cmpt)); /* protocol name */ ProtName("Yahoo! Web Messenger", "webymsg"); /* http dependence */ dep.name = "http"; dep.attr = "http.host"; dep.type = FT_STRING; dep.op = FT_OP_REX; dep.val.str = DMemMalloc(strlen(WMSNHOST_NAME_YAHOO_REX_1)+1); strcpy(dep.val.str, WMSNHOST_NAME_YAHOO_REX_1); ProtDep(&dep); dep.val.str = DMemMalloc(strlen(WMSNHOST_NAME_YAHOO_REX_2)+1); strcpy(dep.val.str, WMSNHOST_NAME_YAHOO_REX_2); ProtDep(&dep); /* PEI components */ peic.abbrev = "url"; peic.desc = "Uniform Resource Locator"; ProtPeiComponent(&peic); peic.abbrev = "client"; peic.desc = "Client"; ProtPeiComponent(&peic); peic.abbrev = "host"; peic.desc = "Host"; ProtPeiComponent(&peic); peic.abbrev = "req.header"; peic.desc = "Request header"; ProtPeiComponent(&peic); peic.abbrev = "req.body"; peic.desc = "Request body"; ProtPeiComponent(&peic); peic.abbrev = "res.header"; peic.desc = "Response header"; ProtPeiComponent(&peic); peic.abbrev = "res.body"; peic.desc = "Response body"; ProtPeiComponent(&peic); /* dissectors registration */ ProtDissectors(WebMsnYahooDissector, NULL, NULL, NULL); return 0; } int DissectInit(void) { int http_id; prot_id = ProtId("webymsg"); /* Http pei generator */ HttpPktDis = NULL; http_id = ProtId("http"); if (http_id != -1) { HttpPktDis = ProtPktDefaultDis(http_id); } /* pei id */ pei_url_id = ProtPeiComptId(prot_id, "url"); pei_client_id = ProtPeiComptId(prot_id, "client"); pei_host_id = ProtPeiComptId(prot_id, "host"); pei_req_header_id = ProtPeiComptId(prot_id, "req.header"); pei_req_body_id = ProtPeiComptId(prot_id, "req.body"); pei_res_header_id = ProtPeiComptId(prot_id, "res.header"); pei_res_body_id = ProtPeiComptId(prot_id, "res.body"); return 0; }
{ "pile_set_name": "Github" }
// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. syntax = "proto2"; import "extension_base/extension_base.proto"; import "extension_extra/extension_extra.proto"; package extension_user; option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/extension_user"; message UserMessage { optional string name = 1; optional string rank = 2; } // Extend with a message extend extension_base.BaseMessage { optional UserMessage user_message = 5; } // Extend with a foreign message extend extension_base.BaseMessage { optional extension_extra.ExtraMessage extra_message = 9; } // Extend with some primitive types extend extension_base.BaseMessage { optional int32 width = 6; optional int64 area = 7; } // Extend inside the scope of another type message LoudMessage { extend extension_base.BaseMessage { optional uint32 volume = 8; } extensions 100 to max; } // Extend inside the scope of another type, using a message. message LoginMessage { extend extension_base.BaseMessage { optional UserMessage user_message = 16; } } // Extend with a repeated field extend extension_base.BaseMessage { repeated Detail detail = 17; } message Detail { optional string color = 1; } // An extension of an extension message Announcement { optional string words = 1; extend LoudMessage { optional Announcement loud_ext = 100; } } // Something that can be put in a message set. message OldStyleParcel { extend extension_base.OldStyleMessage { optional OldStyleParcel message_set_extension = 2001; } required string name = 1; optional int32 height = 2; }
{ "pile_set_name": "Github" }
/** * Copyright 2015 Ram Sriharsha * * 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 magellan import com.fasterxml.jackson.databind.ObjectMapper import org.apache.spark.sql.types._ import org.scalatest.FunSuite class PointSuite extends FunSuite with TestSparkContext { test("bounding box") { val point = Point(1.0, 1.0) val BoundingBox(xmin, ymin, xmax, ymax) = point.boundingBox assert(xmin === 1.0) assert(ymin === 1.0) assert(xmax === 1.0) assert(ymax === 1.0) } test("serialization") { val point = Point(1.0, 1.0) val pointUDT = new PointUDT val BoundingBox(xmin, ymin, xmax, ymax) = point.boundingBox val row = pointUDT.serialize(point) assert(row.getInt(0) === point.getType()) assert(row.getDouble(1) === xmin) assert(row.getDouble(2) === ymin) assert(row.getDouble(3) === xmax) assert(row.getDouble(4) === ymax) val serializedPoint = pointUDT.deserialize(row) assert(point.equals(serializedPoint)) } test("point udf") { val sqlContext = this.sqlContext import sqlContext.implicits._ val points = sc.parallelize(Seq((-1.0, -1.0), (-1.0, 1.0), (1.0, -1.0))).toDF("x", "y") import org.apache.spark.sql.functions.udf val toPointUDF = udf{(x:Double,y:Double) => Point(x,y) } val point = points.withColumn("point", toPointUDF('x, 'y)) .select('point) .first()(0) .asInstanceOf[Point] assert(point.getX() === -1.0) assert(point.getY() === -1.0) } test("jackson serialization") { val s = new ObjectMapper().writeValueAsString(Point(1.0, 1.0)) assert(s.contains("boundingBox")) assert(s.contains("x")) assert(s.contains("y")) } test("within circle") { assert(Point(0.0, 0.0) withinCircle (Point(0.5, 0.5), 0.75)) assert(!(Point(0.0, 0.0) withinCircle (Point(0.5, 0.5), 0.5))) } test("buffer point") { val polygon = Point(0.0, 1.0).buffer(0.5) assert(polygon.getNumRings() === 1) // check that [0.0, 0.75] is within this polygon assert(polygon.contains(Point(0.0, 0.75))) // check that [0.4, 1.0] is within this polygon assert(polygon.contains(Point(0.4, 1.0))) // check that [0.6, 1.0] is outside this polygon assert(!polygon.contains(Point(0.6, 1.0))) } }
{ "pile_set_name": "Github" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.13"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>OpenMesh: OpenMesh/Examples/Tutorial10/stats.hh Source File</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); </script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> <link href="logo_align.css" rel="stylesheet" type="text/css"/> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectlogo"><img alt="Logo" src="rwth_vci_rgb.jpg"/></td> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">OpenMesh </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.13 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); </script> <div id="main-nav"></div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('a04053_source.html','');}); </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="header"> <div class="headertitle"> <div class="title">stats.hh</div> </div> </div><!--header--> <div class="contents"> <div class="fragment"><div class="line"><a name="l00001"></a><span class="lineno"> 1</span>&#160;<span class="preprocessor">#ifndef STATS_HH</span></div><div class="line"><a name="l00002"></a><span class="lineno"> 2</span>&#160;<span class="preprocessor">#define STATS_HH</span></div><div class="line"><a name="l00003"></a><span class="lineno"> 3</span>&#160;</div><div class="line"><a name="l00004"></a><span class="lineno"> 4</span>&#160;<span class="keyword">template</span> &lt;<span class="keyword">typename</span> Mesh&gt;</div><div class="line"><a name="l00005"></a><span class="lineno"> 5</span>&#160;<span class="keywordtype">void</span> mesh_stats( Mesh&amp; _m, <span class="keyword">const</span> std::string&amp; prefix = <span class="stringliteral">&quot;&quot;</span> )</div><div class="line"><a name="l00006"></a><span class="lineno"> 6</span>&#160;{</div><div class="line"><a name="l00007"></a><span class="lineno"> 7</span>&#160; std::cout &lt;&lt; prefix</div><div class="line"><a name="l00008"></a><span class="lineno"> 8</span>&#160; &lt;&lt; _m.n_vertices() &lt;&lt; <span class="stringliteral">&quot; vertices, &quot;</span></div><div class="line"><a name="l00009"></a><span class="lineno"> 9</span>&#160; &lt;&lt; _m.n_edges() &lt;&lt; <span class="stringliteral">&quot; edges, &quot;</span></div><div class="line"><a name="l00010"></a><span class="lineno"> 10</span>&#160; &lt;&lt; _m.n_faces() &lt;&lt; <span class="stringliteral">&quot; faces\n&quot;</span>;</div><div class="line"><a name="l00011"></a><span class="lineno"> 11</span>&#160;}</div><div class="line"><a name="l00012"></a><span class="lineno"> 12</span>&#160;</div><div class="line"><a name="l00013"></a><span class="lineno"> 13</span>&#160;<span class="keyword">template</span> &lt;<span class="keyword">typename</span> Mesh&gt;</div><div class="line"><a name="l00014"></a><span class="lineno"> 14</span>&#160;<span class="keywordtype">void</span> mesh_property_stats(Mesh&amp; _m)</div><div class="line"><a name="l00015"></a><span class="lineno"> 15</span>&#160;{</div><div class="line"><a name="l00016"></a><span class="lineno"> 16</span>&#160; std::cout &lt;&lt; <span class="stringliteral">&quot;Current set of properties:\n&quot;</span>;</div><div class="line"><a name="l00017"></a><span class="lineno"> 17</span>&#160; _m.property_stats(std::cout);</div><div class="line"><a name="l00018"></a><span class="lineno"> 18</span>&#160;}</div><div class="line"><a name="l00019"></a><span class="lineno"> 19</span>&#160;</div><div class="line"><a name="l00020"></a><span class="lineno"> 20</span>&#160;<span class="preprocessor">#endif</span></div></div><!-- fragment --></div><!-- contents --> </div><!-- doc-content --> <hr> <address> <small> <a href="http://www.rwth-graphics.de" style="text-decoration:none;"> </a> Project <b>OpenMesh</b>, &copy;&nbsp; Computer Graphics Group, RWTH Aachen. Documentation generated using <a class="el" href="http://www.doxygen.org/index.html"> <b>doxygen</b> </a>. </small> </address> </body> </html>
{ "pile_set_name": "Github" }
<?php /** * ------------------------------------ * Notify user being "@" * ------------------------------------ */ $I = new FunctionalTester($scenario); Route::enableFilters(); $I->wantTo('Notify a User when he/she is being AT on a newly Reply'); $SuperMan = $I->have('User', ['name' => 'SuperMan']); $user = $I->signIn(); $topic = $I->postATopic(['title' => 'My Awsome Topic.', 'user_id' => $user->id]); // another user leave a reply $randomUser = $I->signIn(); $I->amOnRoute('topics.show', $topic->id ); $I->fillField(['name' => 'body'], 'The Awsome Reply. @SuperMan'); $I->click('#reply-create-submit'); $I->see('The Awsome Reply. <a href="'.route('users.show', $SuperMan->id).'">@SuperMan</a>'); // sign in the author $user = $I->signIn($SuperMan); $I->seeRecord('users', [ 'id' => $user->id, 'notification_count' => 1 ]); $I->amOnRoute('notifications.index'); $I->see('My Awsome Topic.'); $I->see('The Awsome Reply. <a href="'.route('users.show', $SuperMan->id).'">@SuperMan</a>'); $I->see($randomUser->name); $I->seeRecord('users', [ 'id' => $user->id, 'notification_count' => 0 ]);
{ "pile_set_name": "Github" }
"""Tests focused on the data module.""" import datetime import numpy as np import pytest import torch from deepdow.data import (Compose, Dropout, FlexibleDataLoader, InRAMDataset, Multiply, Noise, RigidDataLoader) from deepdow.data.load import collate_uniform class TestCollateUniform: def test_incorrect_input(self): with pytest.raises(ValueError): collate_uniform([], n_assets_range=(-2, 0)) with pytest.raises(ValueError): collate_uniform([], lookback_range=(3, 1)) with pytest.raises(ValueError): collate_uniform([], horizon_range=(10, 10)) def test_dummy(self): n_samples = 14 max_n_assets = 10 max_lookback = 8 max_horizon = 5 n_channels = 2 batch = [(torch.zeros((n_channels, max_lookback, max_n_assets)), torch.ones((n_channels, max_horizon, max_n_assets)), datetime.datetime.now(), ['asset_{}'.format(i) for i in range(max_n_assets)]) for _ in range(n_samples)] X_batch, y_batch, timestamps_batch, asset_names_batch = collate_uniform(batch, n_assets_range=(5, 6), lookback_range=(4, 5), horizon_range=(3, 4)) assert torch.is_tensor(X_batch) assert torch.is_tensor(y_batch) assert X_batch.shape == (n_samples, n_channels, 4, 5) assert y_batch.shape == (n_samples, n_channels, 3, 5) assert len(timestamps_batch) == n_samples assert len(asset_names_batch) == 5 def test_replicable(self): random_state_a = 3 random_state_b = 5 n_samples = 14 max_n_assets = 10 max_lookback = 8 max_horizon = 5 n_channels = 2 batch = [(torch.rand((n_channels, max_lookback, max_n_assets)), torch.rand((n_channels, max_horizon, max_n_assets)), datetime.datetime.now(), ['asset_{}'.format(i) for i in range(max_n_assets)]) for _ in range(n_samples)] X_batch_1, y_batch_1, _, _ = collate_uniform(batch, random_state=random_state_a, n_assets_range=(4, 5), lookback_range=(4, 5), horizon_range=(3, 4)) X_batch_2, y_batch_2, _, _ = collate_uniform(batch, random_state=random_state_a, n_assets_range=(4, 5), lookback_range=(4, 5), horizon_range=(3, 4)) X_batch_3, y_batch_3, _, _ = collate_uniform(batch, random_state=random_state_b, n_assets_range=(4, 5), lookback_range=(4, 5), horizon_range=(3, 4)) assert torch.allclose(X_batch_1, X_batch_2) assert torch.allclose(y_batch_1, y_batch_2) assert not torch.allclose(X_batch_3, X_batch_1) assert not torch.allclose(y_batch_3, y_batch_1) def test_different(self): n_samples = 6 max_n_assets = 27 max_lookback = 15 max_horizon = 12 n_channels = 2 batch = [(torch.rand((n_channels, max_lookback, max_n_assets)), torch.rand((n_channels, max_horizon, max_n_assets)), datetime.datetime.now(), ['asset_{}'.format(i) for i in range(max_n_assets)]) for _ in range(n_samples)] n_trials = 10 n_assets_set = set() lookback_set = set() horizon_set = set() for _ in range(n_trials): X_batch, y_batch, timestamps_batch, asset_names_batch = collate_uniform(batch, n_assets_range=(2, max_n_assets), lookback_range=(2, max_lookback), horizon_range=(2, max_lookback)) n_assets_set.add(X_batch.shape[-1]) lookback_set.add(X_batch.shape[-2]) horizon_set.add(y_batch.shape[-2]) assert len(n_assets_set) > 1 assert len(lookback_set) > 1 assert len(horizon_set) > 1 class TestInRAMDataset: def test_incorrect_input(self): with pytest.raises(ValueError): InRAMDataset(np.zeros((2, 1, 3, 4)), np.zeros((3, 1, 5, 4))) with pytest.raises(ValueError): InRAMDataset(np.zeros((2, 1, 3, 4)), np.zeros((2, 2, 6, 4))) with pytest.raises(ValueError): InRAMDataset(np.zeros((2, 1, 3, 4)), np.zeros((2, 1, 3, 6))) @pytest.mark.parametrize('n_samples', [1, 3, 6]) def test_lenght(self, n_samples): dset = InRAMDataset(np.zeros((n_samples, 1, 3, 4)), np.zeros((n_samples, 1, 6, 4))) assert len(dset) == n_samples def test_get_item(self): n_samples = 3 n_channels = 3 X = np.zeros((n_samples, n_channels, 3, 4)) y = np.zeros((n_samples, n_channels, 6, 4)) for i in range(n_samples): X[i] = i y[i] = i dset = InRAMDataset(X, y) for i in range(n_samples): X_sample, y_sample, _, _ = dset[i] assert torch.is_tensor(X_sample) assert torch.is_tensor(y_sample) assert X_sample.shape == (n_channels, 3, 4) assert y_sample.shape == (n_channels, 6, 4) assert torch.allclose(X_sample, torch.ones_like(X_sample) * i) assert torch.allclose(y_sample, torch.ones_like(y_sample) * i) def test_transforms(self): n_samples = 13 n_channels = 2 lookback = 9 horizon = 10 n_assets = 6 X = np.random.normal(size=(n_samples, n_channels, lookback, n_assets)) / 100 y = np.random.normal(size=(n_samples, n_channels, horizon, n_assets)) / 100 dataset = InRAMDataset(X, y, transform=Compose([Noise(), Dropout(p=0.5), Multiply(c=100)])) X_sample, y_sample, timestamps_sample, asset_names = dataset[1] assert (X_sample == 0).sum() > 0 # dropout assert X_sample.max() > 1 # multiply 100 assert X_sample.min() < -1 # multiply 100 assert (y_sample == 0).sum() == 0 assert y_sample.max() < 1 assert y_sample.min() > -1 class TestFlexibleDataLoader: def test_wrong_construction(self, dataset_dummy): max_assets = dataset_dummy.n_assets max_lookback = dataset_dummy.lookback max_horizon = dataset_dummy.horizon with pytest.raises(ValueError): FlexibleDataLoader(dataset_dummy, indices=None, asset_ixs=list(range(len(dataset_dummy))), n_assets_range=(max_assets, max_assets + 1), lookback_range=(max_lookback, max_lookback + 1), horizon_range=(-2, max_horizon + 1)) with pytest.raises(ValueError): FlexibleDataLoader(dataset_dummy, indices=[-1], n_assets_range=(max_assets, max_assets + 1), lookback_range=(max_lookback, max_lookback + 1), horizon_range=(max_horizon, max_horizon + 1)) with pytest.raises(ValueError): FlexibleDataLoader(dataset_dummy, indices=None, n_assets_range=(max_assets, max_assets + 2), lookback_range=(max_lookback, max_lookback + 1), horizon_range=(max_horizon, max_horizon + 1)) with pytest.raises(ValueError): FlexibleDataLoader(dataset_dummy, indices=None, n_assets_range=(max_assets, max_assets + 1), lookback_range=(0, max_lookback + 1), horizon_range=(max_horizon, max_horizon + 1)) with pytest.raises(ValueError): FlexibleDataLoader(dataset_dummy, indices=None, n_assets_range=(max_assets, max_assets + 1), lookback_range=(max_lookback, max_lookback + 1), horizon_range=(-2, max_horizon + 1)) def test_basic(self, dataset_dummy): max_assets = dataset_dummy.n_assets max_lookback = dataset_dummy.lookback max_horizon = dataset_dummy.horizon dl = FlexibleDataLoader(dataset_dummy, indices=None, n_assets_range=(max_assets, max_assets + 1), lookback_range=(max_lookback, max_lookback + 1), horizon_range=(max_horizon, max_horizon + 1)) dl = FlexibleDataLoader(dataset_dummy) assert isinstance(dl.hparams, dict) def test_minimal(self, dataset_dummy): dl = FlexibleDataLoader(dataset_dummy, batch_size=2) res = next(iter(dl)) assert len(res) == 4 class TestRidigDataLoader: def test_wrong_construction(self, dataset_dummy): max_assets = dataset_dummy.n_assets max_lookback = dataset_dummy.lookback max_horizon = dataset_dummy.horizon with pytest.raises(ValueError): RigidDataLoader(dataset_dummy, indices=[-1]) with pytest.raises(ValueError): RigidDataLoader(dataset_dummy, asset_ixs=[max_assets + 1, max_assets + 2]) with pytest.raises(ValueError): RigidDataLoader(dataset_dummy, lookback=max_lookback + 1) with pytest.raises(ValueError): RigidDataLoader(dataset_dummy, horizon=max_horizon + 1) def test_basic(self, dataset_dummy): dl = RigidDataLoader(dataset_dummy) assert isinstance(dl.hparams, dict)
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <artifactId>oss-parent</artifactId> <groupId>org.sonatype.oss</groupId> <version>9</version> </parent> <prerequisites> <maven>${required.maven.version}</maven> </prerequisites> <groupId>com.lazerycode.jmeter</groupId> <artifactId>jmeter-maven-plugin</artifactId> <version>DEV-SNAPSHOT</version> <packaging>maven-plugin</packaging> <name>JMeter Maven Plugin</name> <description>A plugin to allow you to run Apache JMeter tests with Maven.</description> <url>https://jmeter.lazerycode.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <required.maven.version>3.5.2</required.maven.version> <supported.java.version>1.8</supported.java.version> <!--Dependency versions--> <assertj-core.version>3.15.0</assertj-core.version> <commons-io.version>2.6</commons-io.version> <jackson.version>2.11.0</jackson.version> <json-path.version>2.4.0</json-path.version> <junit.version>4.13</junit.version> <logback.version>1.2.3</logback.version> <maven-resolver.version>1.4.2</maven-resolver.version> <mockito-core.version>2.28.2</mockito-core.version> <slf4j-api.version>1.7.30</slf4j-api.version> <!--Plugin versions--> <maven-compiler-plugin.version>3.8.0</maven-compiler-plugin.version> <maven-enforcer-plugin.version>3.0.0-M3</maven-enforcer-plugin.version> <maven-invoker-plugin.version>3.2.0</maven-invoker-plugin.version> <maven-javadoc-plugin.version>3.0.1</maven-javadoc-plugin.version> <maven-source-plugin.version>3.0.1</maven-source-plugin.version> <maven-surefire-failsafe-plugin.version>2.22.2</maven-surefire-failsafe-plugin.version> <jacoco-maven-plugin.version>0.8.5</jacoco-maven-plugin.version> <nexus-staging-maven-plugin.version>1.6.8</nexus-staging-maven-plugin.version> <pgp-maven-plugin.version>1.1</pgp-maven-plugin.version> </properties> <licenses> <license> <name>Apache 2</name> <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url> <distribution>repo</distribution> <comments>A business-friendly OSS license</comments> </license> </licenses> <scm> <connection>scm:git:git@github.com:jmeter-maven-plugin/jmeter-maven-plugin.git</connection> <developerConnection>scm:git:git@github.com:jmeter-maven-plugin/jmeter-maven-plugin.git</developerConnection> <url>https://github.com/jmeter-maven-plugin/jmeter-maven-plugin</url> <tag>HEAD</tag> </scm> <issueManagement> <system>GitHub</system> <url>https://github.com/jmeter-maven-plugin/jmeter-maven-plugin/issues</url> </issueManagement> <ciManagement> <system>Travis CI</system> <url>https://travis-ci.org/jmeter-maven-plugin/jmeter-maven-plugin</url> </ciManagement> <mailingLists> <mailingList> <name>JMeter Maven Plugin Users</name> <post>maven-jmeter-plugin-users@googlegroups.com</post> <archive>https://groups.google.com/forum/?fromgroups#!forum/maven-jmeter-plugin-users</archive> </mailingList> <mailingList> <name>JMeter Maven Plugin Devs</name> <post>maven-jmeter-plugin-devs@googlegroups.com</post> <archive>https://groups.google.com/forum/?fromgroups#!forum/maven-jmeter-plugin-devs</archive> </mailingList> </mailingLists> <developers> <developer> <id>Ardesco</id> <name>Mark Collin</name> <timezone>GMT</timezone> <roles> <role>Comitter</role> </roles> </developer> <developer> <id>pmouawad</id> <name>Philippe Mouawad</name> <roles> <role>Comitter</role> </roles> <organizationUrl>https://www.ubik-ingenierie.com/blog/</organizationUrl> <url>https://ubikloadpack.com</url> <organization>Ubik-Ingenierie</organization> </developer> </developers> <contributors> <contributor> <name>Arne Franken</name> <timezone>CET</timezone> </contributor> <contributor> <name>Ron Alleva</name> </contributor> <contributor> <name>Tom Coupland</name> </contributor> <contributor> <name>Daniel Yokomizo</name> </contributor> <contributor> <name>Gerd Aschemann</name> </contributor> <contributor> <name>Yoann Ciabaud</name> </contributor> <contributor> <name>Tim McCune</name> </contributor> <contributor> <name>Jon Roberts</name> </contributor> <contributor> <name>Jarrod Ribble</name> </contributor> <contributor> <name>Fabrice Daugan</name> </contributor> <contributor> <name>Dmytro Pishchukhin</name> </contributor> <contributor> <name>Erik G. H. Meade</name> </contributor> <contributor> <name>Zmicier Zaleznicenka</name> </contributor> <contributor> <name>Michael Lex</name> </contributor> <contributor> <name>Mike Patel</name> </contributor> <contributor> <name>Peter Murray</name> </contributor> <contributor> <name>Sascha Theves</name> </contributor> <contributor> <name>gordon00</name> </contributor> <contributor> <name>Irek Pastusiak</name> </contributor> <contributor> <name>Nanne</name> </contributor> <contributor> <name>Pascal Treilhes</name> </contributor> <contributor> <name>https://github.com/kostd</name> </contributor> </contributors> <distributionManagement> <snapshotRepository> <id>sonatype-nexus-snapshots</id> <url>https://oss.sonatype.org/content/repositories/snapshots/</url> </snapshotRepository> </distributionManagement> <dependencies> <dependency> <groupId>org.apache.maven</groupId> <artifactId>maven-plugin-api</artifactId> <version>${required.maven.version}</version> </dependency> <dependency> <groupId>org.apache.maven</groupId> <artifactId>maven-core</artifactId> <version>${required.maven.version}</version> </dependency> <dependency> <groupId>org.apache.maven.plugin-tools</groupId> <artifactId>maven-plugin-annotations</artifactId> <version>${required.maven.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.maven.resolver</groupId> <artifactId>maven-resolver-api</artifactId> <version>${maven-resolver.version}</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>${commons-io.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-csv</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.jayway.jsonpath</groupId> <artifactId>json-path</artifactId> <version>${json-path.version}</version> </dependency> <!--Test Dependencies--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.assertj</groupId> <artifactId>assertj-core</artifactId> <version>${assertj-core.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>${mockito-core.version}</version> <scope>test</scope> </dependency> <!--Logging--> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j-api.version}</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-core</artifactId> <version>${logback.version}</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>${logback.version}</version> </dependency> </dependencies> <build> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>${maven-compiler-plugin.version}</version> <configuration> <source>${supported.java.version}</source> <target>${supported.java.version}</target> </configuration> <dependencies> <dependency> <groupId>org.ow2.asm</groupId> <artifactId>asm</artifactId> <version>6.2</version> </dependency> </dependencies> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-plugin-plugin</artifactId> <version>${required.maven.version}</version> <executions> <execution> <id>mojo-descriptor</id> <goals> <goal>descriptor</goal> </goals> </execution> <execution> <id>help-goal</id> <goals> <goal>helpmojo</goal> </goals> </execution> </executions> </plugin> <plugin> <artifactId>maven-enforcer-plugin</artifactId> <version>${maven-enforcer-plugin.version}</version> <executions> <execution> <id>enforce-maven-version</id> <goals> <goal>enforce</goal> </goals> <configuration> <rules> <requireMavenVersion> <version>${required.maven.version}</version> </requireMavenVersion> </rules> </configuration> </execution> </executions> </plugin> </plugins> </pluginManagement> </build> <profiles> <profile> <id>integration</id> <activation> <activeByDefault>true</activeByDefault> </activation> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-invoker-plugin</artifactId> <version>${maven-invoker-plugin.version}</version> <configuration> <skipInstallation>${skipTests}</skipInstallation> <skipInvocation>${skipTests}</skipInvocation> <cloneProjectsTo>${project.build.directory}/it</cloneProjectsTo> <settingsFile>src/it/settings.xml</settingsFile> <localRepositoryPath>${project.build.directory}/local-repo</localRepositoryPath> <postBuildHookScript>verify</postBuildHookScript> <streamLogs>true</streamLogs> <showErrors>true</showErrors> <mavenOpts>${argLine} -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn</mavenOpts> <properties> <jmeter.version>${jmeter.version}</jmeter.version> </properties> </configuration> <executions> <execution> <id>integration-test</id> <goals> <goal>install</goal> <goal>run</goal> </goals> </execution> <execution> <id>verify</id> <goals> <goal>verify</goal> </goals> </execution> </executions> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>${maven-surefire-failsafe-plugin.version}</version> <dependencies> <dependency> <groupId>org.ow2.asm</groupId> <artifactId>asm</artifactId> <version>6.2.1</version> </dependency> </dependencies> </plugin> <plugin> <artifactId>maven-failsafe-plugin</artifactId> <version>${maven-surefire-failsafe-plugin.version}</version> <executions> <execution> <id>integration-test</id> <goals> <goal>integration-test</goal> </goals> </execution> <execution> <id>verify</id> <goals> <goal>verify</goal> </goals> </execution> </executions> <configuration> <argLine>@{argLine}</argLine> </configuration> </plugin> <plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> <version>${jacoco-maven-plugin.version}</version> <executions> <execution> <id>pre-unit-test</id> <goals> <goal>prepare-agent</goal> </goals> </execution> <execution> <phase>pre-integration-test</phase> <goals> <goal>prepare-agent-integration</goal> </goals> </execution> <execution> <id>default-report</id> <phase>test</phase> <goals> <goal>report</goal> </goals> </execution> <execution> <id>default-report-integration</id> <phase>post-integration-test</phase> <goals> <goal>report-integration</goal> </goals> </execution> </executions> <configuration> <propertyName>argLine</propertyName> </configuration> </plugin> </plugins> </build> </profile> <profile> <id>release</id> <repositories> <repository> <id>sonatype-nexus-snapshots</id> <name>Sonatype Nexus Snapshots</name> <url>https://oss.sonatype.org/content/repositories/snapshots</url> <snapshots> <enabled>false</enabled> </snapshots> </repository> </repositories> <distributionManagement> <repository> <id>sonatype-nexus-staging</id> <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url> </repository> </distributionManagement> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <version>${maven-javadoc-plugin.version}</version> <executions> <execution> <id>attach-javadocs</id> <goals> <goal>jar</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-source-plugin</artifactId> <version>${maven-source-plugin.version}</version> <executions> <execution> <id>attach-sources</id> <goals> <goal>jar-no-fork</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.kohsuke</groupId> <artifactId>pgp-maven-plugin</artifactId> <version>${pgp-maven-plugin.version}</version> <configuration> <secretkey>keyfile:${gpg.key.location}</secretkey> <passphrase>literal:${gpg.passphrase}</passphrase> </configuration> <executions> <execution> <goals> <goal>sign</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.sonatype.plugins</groupId> <artifactId>nexus-staging-maven-plugin</artifactId> <version>${nexus-staging-maven-plugin.version}</version> <extensions>true</extensions> <configuration> <serverId>sonatype-nexus-staging</serverId> <nexusUrl>https://oss.sonatype.org/</nexusUrl> <autoReleaseAfterClose>true</autoReleaseAfterClose> <stagingProgressPauseDurationSeconds>10</stagingProgressPauseDurationSeconds> <stagingProgressTimeoutMinutes>10</stagingProgressTimeoutMinutes> </configuration> </plugin> <plugin> <artifactId>maven-enforcer-plugin</artifactId> <version>${maven-enforcer-plugin.version}</version> <executions> <execution> <id>enforce-maven-version</id> <goals> <goal>enforce</goal> </goals> <configuration> <rules> <requireMavenVersion> <version>${required.maven.version}</version> </requireMavenVersion> <requireJavaVersion> <version>${supported.java.version}}</version> </requireJavaVersion> </rules> </configuration> </execution> </executions> </plugin> </plugins> </build> </profile> </profiles> </project>
{ "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 net import ( "net" "net/url" "os" "reflect" "syscall" ) // IPNetEqual checks if the two input IPNets are representing the same subnet. // For example, // 10.0.0.1/24 and 10.0.0.0/24 are the same subnet. // 10.0.0.1/24 and 10.0.0.0/25 are not the same subnet. func IPNetEqual(ipnet1, ipnet2 *net.IPNet) bool { if ipnet1 == nil || ipnet2 == nil { return false } if reflect.DeepEqual(ipnet1.Mask, ipnet2.Mask) && ipnet1.Contains(ipnet2.IP) && ipnet2.Contains(ipnet1.IP) { return true } return false } // Returns if the given err is "connection reset by peer" error. func IsConnectionReset(err error) bool { if urlErr, ok := err.(*url.Error); ok { err = urlErr.Err } if opErr, ok := err.(*net.OpError); ok { err = opErr.Err } if osErr, ok := err.(*os.SyscallError); ok { err = osErr.Err } if errno, ok := err.(syscall.Errno); ok && errno == syscall.ECONNRESET { return true } return false }
{ "pile_set_name": "Github" }
class FixMaintainersWithAlumnusFalse < ActiveRecord::Migration[5.1] def up Maintainer.where(alumnus: "0").update_all(alumnus: nil) end def down raise ActiveRecord::IrreversibleMigration end end
{ "pile_set_name": "Github" }
# Contributor: Bart Ribbers <bribbers@disroot.org> # Maintainer: Bart Ribbers <bribbers@disroot.org> pkgname=calendarsupport pkgver=20.08.1 pkgrel=0 pkgdesc="Library providing calendar support" arch="all !ppc64le !s390x !armhf !mips !mips64" # Limited by akonadi-calendar-dev -> kmailtransport -> libkgapi -> qt5-qtwebengine url="https://kontact.kde.org" license="GPL-2.0-or-later AND Qt-GPL-exception-1.0 AND LGPL-2.0-or-later" depends_dev=" akonadi-calendar-dev akonadi-dev akonadi-mime-dev akonadi-notes-dev kcalendarcore-dev kcalutils-dev kcodecs-dev kguiaddons-dev kholidays-dev ki18n-dev kidentitymanagement-dev kio-dev kmime-dev pimcommon-dev qt5-qtbase-dev " makedepends="$depends_dev extra-cmake-modules qt5-qttools-dev qt5-qttools-static " checkdepends="xvfb-run" source="https://download.kde.org/stable/release-service/$pkgver/src/calendarsupport-$pkgver.tar.xz" subpackages="$pkgname-dev $pkgname-lang" build() { cmake -B build \ -DCMAKE_BUILD_TYPE=None \ -DCMAKE_INSTALL_PREFIX=/usr \ -DCMAKE_INSTALL_LIBDIR=lib cmake --build build } check() { cd build CTEST_OUTPUT_ON_FAILURE=TRUE xvfb-run ctest } package() { DESTDIR="$pkgdir" cmake --build build --target install } sha512sums="65849b524534b154ad45413ee35f6da2e9ce5edc4c3dc516f868adf70098793c609b726c4b484d9106c6b31fca830fd575b9671abb006173a00f2ccadc44551e calendarsupport-20.08.1.tar.xz"
{ "pile_set_name": "Github" }
<?php namespace PieCrust\Mock; use PieCrust\IPieCrust; use PieCrust\PieCrustConfiguration; class MockPluginLoader { public $plugins; public $formatters; public $templateEngines; public $dataProviders; public $fileSystems; public $processors; public $importers; public $commands; public $twigExtensions; public $bakerAssistants; public function __construct() { $this->plugins = array(); $this->formatters = array(); $this->templateEngines = array(); $this->dataProviders = array(); $this->fileSystems = array(); $this->processors = array(); $this->importers = array(); $this->commands = array(); $this->twigExtensions = array(); $this->bakerAssistants = array(); } public function getPlugins() { return $this->plugins; } public function getFormatters() { return $this->formatters; } public function getTemplateEngines() { return $this->templateEngines; } public function getDataProviders() { return $this->dataProviders; } public function getFileSystems() { return $this->fileSystems; } public function getProcessors() { return $this->processors; } public function getImporters() { return $this->importers; } public function getCommands() { return $this->commands; } public function getTwigExtensions() { return $this->twigExtensions; } public function getBakerAssistants() { return $this->bakerAssistants; } }
{ "pile_set_name": "Github" }
<?php class NamespaceCoverageNotPublicTest extends PHPUnit_Framework_TestCase { /** * @covers Foo\CoveredClass::<!public> */ public function testSomething() { $o = new Foo\CoveredClass; $o->publicMethod(); } }
{ "pile_set_name": "Github" }
cmake_minimum_required(VERSION 3.3) project(OpenGLESIMGTextureFilterCubic) if(IOS) message("Skipping OpenGLESIMGTextureFilterCubic : Not supported on iOS") return() endif() add_subdirectory(../../.. ${CMAKE_CURRENT_BINARY_DIR}/sdk) if(PVR_PREBUILT_DEPENDENCIES) find_package(PVRShell REQUIRED MODULE) find_package(PVRUtilsGles REQUIRED MODULE) endif() set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin") set_property(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} PROPERTY VS_STARTUP_PROJECT OpenGLESIMGTextureFilterCubic) set(SRC_FILES OpenGLESIMGTextureFilterCubic.cpp) set(ASSET_FOLDER ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/Assets_OpenGLESIMGTextureFilterCubic) # Adds an executable (or ndk library for Android) and necessary files like plists for Mac/iOS etc. add_platform_specific_executable(OpenGLESIMGTextureFilterCubic ${SRC_FILES}) #################################### ASSET FILES ########################################## # For platforms supporting it, will be packaged with the executable for runtime use. # Will be accessible from the app with their "relative path". One call per base path ### Textural shaders (OpenGL ES) ### add_assets_to_target(OpenGLESIMGTextureFilterCubic SOURCE_GROUP "shaders" ASSET_FOLDER ${ASSET_FOLDER} BASE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/ FILE_LIST FragShader.fsh VertShader.vsh) # Create and adds a Windows resource file (Resources.rc) with all the assets that have been added to the target with the previous functions add_assets_resource_file(OpenGLESIMGTextureFilterCubic) ########################################################################################### # Apply SDK example specific compile and linker options apply_example_compile_options_to_target(OpenGLESIMGTextureFilterCubic) target_link_libraries(OpenGLESIMGTextureFilterCubic PUBLIC PVRShell PVRUtilsGles )
{ "pile_set_name": "Github" }
LIBRARY libclamunrar_iface EXPORTS libclamunrar_iface_LTX_unrar_open EXPORTS libclamunrar_iface_LTX_unrar_peek_file_header EXPORTS libclamunrar_iface_LTX_unrar_extract_file EXPORTS libclamunrar_iface_LTX_unrar_skip_file EXPORTS libclamunrar_iface_LTX_unrar_close
{ "pile_set_name": "Github" }
/* * Copyright (c) 2010-2019 Evolveum and contributors * * This work is dual-licensed under the Apache License 2.0 * and European Union Public License. See LICENSE file for details. */ package com.evolveum.midpoint.web.component.assignment; import java.util.ArrayList; import java.util.List; import javax.xml.namespace.QName; import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; import org.apache.wicket.model.IModel; import com.evolveum.midpoint.gui.api.prism.wrapper.ItemWrapper; import com.evolveum.midpoint.gui.api.prism.wrapper.PrismContainerWrapper; import com.evolveum.midpoint.gui.impl.component.data.column.AbstractItemWrapperColumn.ColumnType; import com.evolveum.midpoint.gui.impl.component.data.column.PrismPropertyWrapperColumn; import com.evolveum.midpoint.gui.api.prism.wrapper.PrismContainerValueWrapper; import com.evolveum.midpoint.prism.PrismContainerDefinition; import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.query.ObjectQuery; import com.evolveum.midpoint.util.QNameUtil; import com.evolveum.midpoint.web.component.prism.ItemVisibility; import com.evolveum.midpoint.web.component.search.SearchFactory; import com.evolveum.midpoint.web.component.search.SearchItemDefinition; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; /** * Created by honchar. */ public class ConstructionAssignmentPanel extends AssignmentPanel { private static final long serialVersionUID = 1L; public ConstructionAssignmentPanel(String id, IModel<PrismContainerWrapper<AssignmentType>> assignmentContainerWrapperModel){ super(id, assignmentContainerWrapperModel); } @Override protected List<SearchItemDefinition> createSearchableItems(PrismContainerDefinition<AssignmentType> containerDef) { List<SearchItemDefinition> defs = super.createSearchableItems(containerDef); SearchFactory.addSearchRefDef(containerDef, ItemPath.create(AssignmentType.F_CONSTRUCTION, ConstructionType.F_RESOURCE_REF), defs, AreaCategoryType.ADMINISTRATION, getPageBase()); return defs; } @Override protected QName getAssignmentType(){ return ResourceType.COMPLEX_TYPE; } @Override protected List<IColumn<PrismContainerValueWrapper<AssignmentType>, String>> initColumns() { List<IColumn<PrismContainerValueWrapper<AssignmentType>, String>> columns = new ArrayList<>(); columns.add(new PrismPropertyWrapperColumn<AssignmentType, String>(getModel(), ItemPath.create(AssignmentType.F_CONSTRUCTION, ConstructionType.F_KIND), ColumnType.STRING, getPageBase())); columns.add(new PrismPropertyWrapperColumn<>(getModel(), ItemPath.create(AssignmentType.F_CONSTRUCTION, ConstructionType.F_INTENT), ColumnType.STRING, getPageBase())); return columns; } @Override protected ObjectQuery createObjectQuery(){ return getParentPage().getPrismContext().queryFor(AssignmentType.class) .exists(AssignmentType.F_CONSTRUCTION) .build(); } @Override protected ItemVisibility getTypedContainerVisibility(ItemWrapper<?, ?> wrapper) { if (QNameUtil.match(AssignmentType.F_TARGET_REF, wrapper.getItemName())) { return ItemVisibility.HIDDEN; } if (QNameUtil.match(AssignmentType.F_TENANT_REF, wrapper.getItemName())) { return ItemVisibility.HIDDEN; } if (QNameUtil.match(AssignmentType.F_ORG_REF, wrapper.getItemName())) { return ItemVisibility.HIDDEN; } if (QNameUtil.match(PolicyRuleType.COMPLEX_TYPE, wrapper.getTypeName())){ return ItemVisibility.HIDDEN; } if (QNameUtil.match(PersonaConstructionType.COMPLEX_TYPE, wrapper.getTypeName())){ return ItemVisibility.HIDDEN; } return ItemVisibility.AUTO; } @Override protected boolean getContainerReadability(ItemWrapper<?, ?> wrapper) { if (QNameUtil.match(ConstructionType.F_KIND, wrapper.getItemName())) { return false; } if (QNameUtil.match(ConstructionType.F_INTENT, wrapper.getItemName())) { return false; } return true; } }
{ "pile_set_name": "Github" }
using System; using Jasper.Runtime.Handlers; using LamarCodeGeneration; namespace Jasper.Attributes { /// <summary> /// Specify the maximum number of attempts to process a received message /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public class MaximumAttemptsAttribute : ModifyHandlerChainAttribute { private readonly int _attempts; public MaximumAttemptsAttribute(int attempts) { _attempts = attempts; } public override void Modify(HandlerChain chain, GenerationRules rules) { chain.Retries.MaximumAttempts = _attempts; } } }
{ "pile_set_name": "Github" }
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Jun 9 2015 22:53:21). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2014 by Steve Nygard. // #import <Foundation/NSScriptCommand.h> @interface GoForwardScriptCommand : NSScriptCommand { } - (id)performDefaultImplementation; @end
{ "pile_set_name": "Github" }
{% load forms %} {% input field="PatientConsultation.initials" %} {% datetimepicker field="PatientConsultation.when" %} {% textarea field="PatientConsultation.discussion" %}
{ "pile_set_name": "Github" }
/* * Copyright (C) 2013-2015 RoboVM AB * * 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.bugvm.apple.coremidi; /*<imports>*/ import java.io.*; import java.nio.*; import java.util.*; import com.bugvm.objc.*; import com.bugvm.objc.annotation.*; import com.bugvm.objc.block.*; import com.bugvm.rt.*; import com.bugvm.rt.annotation.*; import com.bugvm.rt.bro.*; import com.bugvm.rt.bro.annotation.*; import com.bugvm.rt.bro.ptr.*; import com.bugvm.apple.foundation.*; import com.bugvm.apple.corefoundation.*; /*</imports>*/ /*<javadoc>*/ /*</javadoc>*/ /*<annotations>*/@Library("CoreMIDI")/*</annotations>*/ /*<visibility>*/public/*</visibility>*/ class /*<name>*/MIDIThruConnection/*</name>*/ extends /*<extends>*/MIDIObject/*</extends>*/ /*<implements>*//*</implements>*/ { /*<ptr>*/public static class MIDIThruConnectionPtr extends Ptr<MIDIThruConnection, MIDIThruConnectionPtr> {}/*</ptr>*/ /*<bind>*/static { Bro.bind(MIDIThruConnection.class); }/*</bind>*/ /*<constants>*//*</constants>*/ /*<constructors>*//*</constructors>*/ /*<properties>*//*</properties>*/ /*<members>*//*</members>*/ /** * @since Available in iOS 4.2 and later. */ public static MIDIThruConnection create(String inPersistentOwnerID, NSData inConnectionParams) { MIDIThruConnectionPtr ptr = new MIDIThruConnectionPtr(); create(inPersistentOwnerID, inConnectionParams, ptr); return ptr.get(); } /** * @since Available in iOS 4.2 and later. */ public NSData getParams() { NSData.NSDataPtr ptr = new NSData.NSDataPtr(); getParams(ptr); return ptr.get(); } /** * @since Available in iOS 4.2 and later. */ public NSData find(String persistentOwnerID) { NSData.NSDataPtr ptr = new NSData.NSDataPtr(); find(persistentOwnerID, ptr); return ptr.get(); } /*<methods>*/ /** * @since Available in iOS 4.2 and later. */ @Bridge(symbol="MIDIThruConnectionCreate", optional=true) protected static native MIDIError create(String inPersistentOwnerID, NSData inConnectionParams, MIDIThruConnection.MIDIThruConnectionPtr outConnection); /** * @since Available in iOS 4.2 and later. */ @Bridge(symbol="MIDIThruConnectionDispose", optional=true) public native MIDIError dispose(); /** * @since Available in iOS 4.2 and later. */ @Bridge(symbol="MIDIThruConnectionGetParams", optional=true) protected native MIDIError getParams(NSData.NSDataPtr outConnectionParams); /** * @since Available in iOS 4.2 and later. */ @Bridge(symbol="MIDIThruConnectionSetParams", optional=true) public native MIDIError setParams(NSData inConnectionParams); /** * @since Available in iOS 4.2 and later. */ @Bridge(symbol="MIDIThruConnectionFind", optional=true) protected static native MIDIError find(String inPersistentOwnerID, NSData.NSDataPtr outConnectionList); /*</methods>*/ }
{ "pile_set_name": "Github" }
amd64=alpine:3.6 arm=arm32v6/alpine:3.6 arm64=arm64v8/alpine:3.6 ppc64le=ppc64le/alpine:3.6
{ "pile_set_name": "Github" }
/* SPDX-License-Identifier: GPL-2.0 */ #ifndef _FIPS_H #define _FIPS_H #ifdef CONFIG_CRYPTO_FIPS extern int fips_enabled; #else #define fips_enabled 0 #endif #endif
{ "pile_set_name": "Github" }
/* ** deko3d Example 03: Cube ** This example shows how to draw a basic rotating cube. ** New concepts in this example: ** - Setting up and using a depth buffer ** - Setting up uniform buffers ** - Basic 3D maths, including projection matrices ** - Updating uniforms with a dynamic command buffer ** - Adjusting resolution dynamically by recreating resources (720p handheld/1080p docked) ** - Depth buffer discard after a barrier */ // Sample Framework headers #include "SampleFramework/CApplication.h" #include "SampleFramework/CMemPool.h" #include "SampleFramework/CShader.h" #include "SampleFramework/CCmdMemRing.h" // C++ standard library headers #include <array> #include <optional> // GLM headers #define GLM_FORCE_DEFAULT_ALIGNED_GENTYPES // Enforces GLSL std140/std430 alignment rules for glm types #define GLM_FORCE_INTRINSICS // Enables usage of SIMD CPU instructions (requiring the above as well) #include <glm/vec3.hpp> #include <glm/vec4.hpp> #include <glm/mat4x4.hpp> #include <glm/gtc/matrix_transform.hpp> namespace { struct Vertex { float position[3]; float color[3]; }; constexpr std::array VertexAttribState = { DkVtxAttribState{ 0, 0, offsetof(Vertex, position), DkVtxAttribSize_3x32, DkVtxAttribType_Float, 0 }, DkVtxAttribState{ 0, 0, offsetof(Vertex, color), DkVtxAttribSize_3x32, DkVtxAttribType_Float, 0 }, }; constexpr std::array VertexBufferState = { DkVtxBufferState{ sizeof(Vertex), 0 }, }; constexpr std::array CubeVertexData = { // +X face Vertex{ { +1.0f, +1.0f, +1.0f }, { 1.0f, 0.0f, 0.0f } }, Vertex{ { +1.0f, -1.0f, +1.0f }, { 0.0f, 1.0f, 0.0f } }, Vertex{ { +1.0f, -1.0f, -1.0f }, { 0.0f, 0.0f, 1.0f } }, Vertex{ { +1.0f, +1.0f, -1.0f }, { 1.0f, 1.0f, 0.0f } }, // -X face Vertex{ { -1.0f, +1.0f, -1.0f }, { 1.0f, 0.0f, 0.0f } }, Vertex{ { -1.0f, -1.0f, -1.0f }, { 0.0f, 1.0f, 0.0f } }, Vertex{ { -1.0f, -1.0f, +1.0f }, { 0.0f, 0.0f, 1.0f } }, Vertex{ { -1.0f, +1.0f, +1.0f }, { 1.0f, 1.0f, 0.0f } }, // +Y face Vertex{ { -1.0f, +1.0f, -1.0f }, { 1.0f, 0.0f, 0.0f } }, Vertex{ { -1.0f, +1.0f, +1.0f }, { 0.0f, 1.0f, 0.0f } }, Vertex{ { +1.0f, +1.0f, +1.0f }, { 0.0f, 0.0f, 1.0f } }, Vertex{ { +1.0f, +1.0f, -1.0f }, { 1.0f, 1.0f, 0.0f } }, // -Y face Vertex{ { -1.0f, -1.0f, +1.0f }, { 1.0f, 0.0f, 0.0f } }, Vertex{ { -1.0f, -1.0f, -1.0f }, { 0.0f, 1.0f, 0.0f } }, Vertex{ { +1.0f, -1.0f, -1.0f }, { 0.0f, 0.0f, 1.0f } }, Vertex{ { +1.0f, -1.0f, +1.0f }, { 1.0f, 1.0f, 0.0f } }, // +Z face Vertex{ { -1.0f, +1.0f, +1.0f }, { 1.0f, 0.0f, 0.0f } }, Vertex{ { -1.0f, -1.0f, +1.0f }, { 0.0f, 1.0f, 0.0f } }, Vertex{ { +1.0f, -1.0f, +1.0f }, { 0.0f, 0.0f, 1.0f } }, Vertex{ { +1.0f, +1.0f, +1.0f }, { 1.0f, 1.0f, 0.0f } }, // -Z face Vertex{ { +1.0f, +1.0f, -1.0f }, { 1.0f, 0.0f, 0.0f } }, Vertex{ { +1.0f, -1.0f, -1.0f }, { 0.0f, 1.0f, 0.0f } }, Vertex{ { -1.0f, -1.0f, -1.0f }, { 0.0f, 0.0f, 1.0f } }, Vertex{ { -1.0f, +1.0f, -1.0f }, { 1.0f, 1.0f, 0.0f } }, }; struct Transformation { glm::mat4 mdlvMtx; glm::mat4 projMtx; }; inline float fractf(float x) { return x - floorf(x); } } class CExample03 final : public CApplication { static constexpr unsigned NumFramebuffers = 2; static constexpr unsigned StaticCmdSize = 0x10000; static constexpr unsigned DynamicCmdSize = 0x10000; dk::UniqueDevice device; dk::UniqueQueue queue; std::optional<CMemPool> pool_images; std::optional<CMemPool> pool_code; std::optional<CMemPool> pool_data; dk::UniqueCmdBuf cmdbuf; dk::UniqueCmdBuf dyncmd; CCmdMemRing<NumFramebuffers> dynmem; CShader vertexShader; CShader fragmentShader; Transformation transformState; CMemPool::Handle transformUniformBuffer; CMemPool::Handle vertexBuffer; uint32_t framebufferWidth; uint32_t framebufferHeight; CMemPool::Handle depthBuffer_mem; CMemPool::Handle framebuffers_mem[NumFramebuffers]; dk::Image depthBuffer; dk::Image framebuffers[NumFramebuffers]; DkCmdList framebuffer_cmdlists[NumFramebuffers]; dk::UniqueSwapchain swapchain; DkCmdList render_cmdlist; public: CExample03() { // Create the deko3d device device = dk::DeviceMaker{}.create(); // Create the main queue queue = dk::QueueMaker{device}.setFlags(DkQueueFlags_Graphics).create(); // Create the memory pools pool_images.emplace(device, DkMemBlockFlags_GpuCached | DkMemBlockFlags_Image, 16*1024*1024); pool_code.emplace(device, DkMemBlockFlags_CpuUncached | DkMemBlockFlags_GpuCached | DkMemBlockFlags_Code, 128*1024); pool_data.emplace(device, DkMemBlockFlags_CpuUncached | DkMemBlockFlags_GpuCached, 1*1024*1024); // Create the static command buffer and feed it freshly allocated memory cmdbuf = dk::CmdBufMaker{device}.create(); CMemPool::Handle cmdmem = pool_data->allocate(StaticCmdSize); cmdbuf.addMemory(cmdmem.getMemBlock(), cmdmem.getOffset(), cmdmem.getSize()); // Create the dynamic command buffer and allocate memory for it dyncmd = dk::CmdBufMaker{device}.create(); dynmem.allocate(*pool_data, DynamicCmdSize); // Load the shaders vertexShader.load(*pool_code, "romfs:/shaders/transform_vsh.dksh"); fragmentShader.load(*pool_code, "romfs:/shaders/color_fsh.dksh"); // Create the transformation uniform buffer transformUniformBuffer = pool_data->allocate(sizeof(transformState), DK_UNIFORM_BUF_ALIGNMENT); // Load the vertex buffer vertexBuffer = pool_data->allocate(sizeof(CubeVertexData), alignof(Vertex)); memcpy(vertexBuffer.getCpuAddr(), CubeVertexData.data(), vertexBuffer.getSize()); } ~CExample03() { // Destroy the framebuffer resources destroyFramebufferResources(); // Destroy the vertex buffer (not strictly needed in this case) vertexBuffer.destroy(); // Destroy the uniform buffer (not strictly needed in this case) transformUniformBuffer.destroy(); } void createFramebufferResources() { // Create layout for the depth buffer dk::ImageLayout layout_depthbuffer; dk::ImageLayoutMaker{device} .setFlags(DkImageFlags_UsageRender | DkImageFlags_HwCompression) .setFormat(DkImageFormat_Z24S8) .setDimensions(framebufferWidth, framebufferHeight) .initialize(layout_depthbuffer); // Create the depth buffer depthBuffer_mem = pool_images->allocate(layout_depthbuffer.getSize(), layout_depthbuffer.getAlignment()); depthBuffer.initialize(layout_depthbuffer, depthBuffer_mem.getMemBlock(), depthBuffer_mem.getOffset()); // Create layout for the framebuffers dk::ImageLayout layout_framebuffer; dk::ImageLayoutMaker{device} .setFlags(DkImageFlags_UsageRender | DkImageFlags_UsagePresent | DkImageFlags_HwCompression) .setFormat(DkImageFormat_RGBA8_Unorm) .setDimensions(framebufferWidth, framebufferHeight) .initialize(layout_framebuffer); // Create the framebuffers std::array<DkImage const*, NumFramebuffers> fb_array; uint64_t fb_size = layout_framebuffer.getSize(); uint32_t fb_align = layout_framebuffer.getAlignment(); for (unsigned i = 0; i < NumFramebuffers; i ++) { // Allocate a framebuffer framebuffers_mem[i] = pool_images->allocate(fb_size, fb_align); framebuffers[i].initialize(layout_framebuffer, framebuffers_mem[i].getMemBlock(), framebuffers_mem[i].getOffset()); // Generate a command list that binds it dk::ImageView colorTarget{ framebuffers[i] }, depthTarget{ depthBuffer }; cmdbuf.bindRenderTargets(&colorTarget, &depthTarget); framebuffer_cmdlists[i] = cmdbuf.finishList(); // Fill in the array for use later by the swapchain creation code fb_array[i] = &framebuffers[i]; } // Create the swapchain using the framebuffers swapchain = dk::SwapchainMaker{device, nwindowGetDefault(), fb_array}.create(); // Generate the main rendering cmdlist recordStaticCommands(); // Initialize the projection matrix transformState.projMtx = glm::perspectiveRH_ZO( glm::radians(40.0f), float(framebufferWidth)/float(framebufferHeight), 0.01f, 1000.0f); } void destroyFramebufferResources() { // Return early if we have nothing to destroy if (!swapchain) return; // Make sure the queue is idle before destroying anything queue.waitIdle(); // Clear the static cmdbuf, destroying the static cmdlists in the process cmdbuf.clear(); // Destroy the swapchain swapchain.destroy(); // Destroy the framebuffers for (unsigned i = 0; i < NumFramebuffers; i ++) framebuffers_mem[i].destroy(); // Destroy the depth buffer depthBuffer_mem.destroy(); } void recordStaticCommands() { // Initialize state structs with deko3d defaults dk::RasterizerState rasterizerState; dk::ColorState colorState; dk::ColorWriteState colorWriteState; dk::DepthStencilState depthStencilState; // Configure viewport and scissor cmdbuf.setViewports(0, { { 0.0f, 0.0f, (float)framebufferWidth, (float)framebufferHeight, 0.0f, 1.0f } }); cmdbuf.setScissors(0, { { 0, 0, framebufferWidth, framebufferHeight } }); // Clear the color and depth buffers cmdbuf.clearColor(0, DkColorMask_RGBA, 0.0f, 0.0f, 0.0f, 0.0f); cmdbuf.clearDepthStencil(true, 1.0f, 0xFF, 0); // Bind state required for drawing the cube cmdbuf.bindShaders(DkStageFlag_GraphicsMask, { vertexShader, fragmentShader }); cmdbuf.bindUniformBuffer(DkStage_Vertex, 0, transformUniformBuffer.getGpuAddr(), transformUniformBuffer.getSize()); cmdbuf.bindRasterizerState(rasterizerState); cmdbuf.bindColorState(colorState); cmdbuf.bindColorWriteState(colorWriteState); cmdbuf.bindDepthStencilState(depthStencilState); cmdbuf.bindVtxBuffer(0, vertexBuffer.getGpuAddr(), vertexBuffer.getSize()); cmdbuf.bindVtxAttribState(VertexAttribState); cmdbuf.bindVtxBufferState(VertexBufferState); // Draw the cube cmdbuf.draw(DkPrimitive_Quads, CubeVertexData.size(), 1, 0, 0); // Fragment barrier, to make sure we finish previous work before discarding the depth buffer cmdbuf.barrier(DkBarrier_Fragments, 0); // Discard the depth buffer since we don't need it anymore cmdbuf.discardDepthStencil(); // Finish off this command list render_cmdlist = cmdbuf.finishList(); } void render() { // Begin generating the dynamic command list, for commands that need to be sent only this frame specifically dynmem.begin(dyncmd); // Update the uniform buffer with the new transformation state (this data gets inlined in the command list) dyncmd.pushConstants( transformUniformBuffer.getGpuAddr(), transformUniformBuffer.getSize(), 0, sizeof(transformState), &transformState); // Finish off the dynamic command list, and submit it to the queue queue.submitCommands(dynmem.end(dyncmd)); // Acquire a framebuffer from the swapchain (and wait for it to be available) int slot = queue.acquireImage(swapchain); // Run the command list that attaches said framebuffer to the queue queue.submitCommands(framebuffer_cmdlists[slot]); // Run the main rendering command list queue.submitCommands(render_cmdlist); // Now that we are done rendering, present it to the screen queue.presentImage(swapchain, slot); } void onOperationMode(AppletOperationMode mode) override { // Destroy the framebuffer resources destroyFramebufferResources(); // Choose framebuffer size chooseFramebufferSize(framebufferWidth, framebufferHeight, mode); // Recreate the framebuffers and its associated resources createFramebufferResources(); } bool onFrame(u64 ns) override { hidScanInput(); u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO); if (kDown & KEY_PLUS) return false; float time = ns / 1000000000.0; // double precision division; followed by implicit cast to single precision float tau = glm::two_pi<float>(); float period1 = fractf(time/8.0f); float period2 = fractf(time/4.0f); // Generate the model-view matrix for this frame // Keep in mind that GLM transformation functions multiply to the right, so essentially we have: // mdlvMtx = Translate * RotateX * RotateY * Scale // This means that the Scale operation is applied first, then RotateY, and so on. transformState.mdlvMtx = glm::mat4{1.0f}; transformState.mdlvMtx = glm::translate(transformState.mdlvMtx, glm::vec3{0.0f, 0.0f, -3.0f}); transformState.mdlvMtx = glm::rotate(transformState.mdlvMtx, sinf(period2 * tau) * tau / 8.0f, glm::vec3{1.0f, 0.0f, 0.0f}); transformState.mdlvMtx = glm::rotate(transformState.mdlvMtx, -period1 * tau, glm::vec3{0.0f, 1.0f, 0.0f}); transformState.mdlvMtx = glm::scale(transformState.mdlvMtx, glm::vec3{0.5f}); render(); return true; } }; void Example03(void) { CExample03 app; app.run(); }
{ "pile_set_name": "Github" }
--- title: "Illusion of the eye" excerpt: "PaperFaces portrait of @robhampson drawn with Paper for iOS on an iPad." image: path: &image /assets/images/paperfaces-robhampson-twitter.jpg feature: *image thumbnail: /assets/images/paperfaces-robhampson-twitter-150.jpg categories: [paperfaces] tags: [portrait, illustration, Paper for iOS, black and white] last_modified_at: 2017-01-17T14:33:25-05:00 --- PaperFaces portrait of [@robhampson](https://twitter.com/robhampson). {% include_cached boilerplate/paperfaces-2.md %} {% figure caption:"Work in progress screen captures Made with Paper." class:"gallery-3-col" %} [![Work in process screenshot](/assets/images/paperfaces-robhampson-process-1-600.jpg)](/assets/images/paperfaces-robhampson-process-1-lg.jpg) [![Work in process screenshot](/assets/images/paperfaces-robhampson-process-2-600.jpg)](/assets/images/paperfaces-robhampson-process-2-lg.jpg) [![Work in process screenshot](/assets/images/paperfaces-robhampson-process-3-600.jpg)](/assets/images/paperfaces-robhampson-process-3-lg.jpg) [![Work in process screenshot](/assets/images/paperfaces-robhampson-process-4-600.jpg)](/assets/images/paperfaces-robhampson-process-4-lg.jpg) [![Work in process screenshot](/assets/images/paperfaces-robhampson-process-5-600.jpg)](/assets/images/paperfaces-robhampson-process-5-lg.jpg) [![Work in process screenshot](/assets/images/paperfaces-robhampson-process-5-600.jpg)](/assets/images/paperfaces-robhampson-process-5-lg.jpg) [![Work in process screenshot](/assets/images/paperfaces-robhampson-process-6-600.jpg)](/assets/images/paperfaces-robhampson-process-6-lg.jpg) {% endfigure %}
{ "pile_set_name": "Github" }
/* * Skeleton V1.1 * Copyright 2011, Dave Gamache * www.getskeleton.com * Free to use under the MIT license. * http://www.opensource.org/licenses/mit-license.php * 8/17/2011 */ /* Table of Contents ================================================== #Base 960 Grid #Tablet (Portrait) #Mobile (Portrait) #Mobile (Landscape) #Clearing */ /* #Base 960 Grid ================================================== */ .container { position: relative; width: 960px; margin: 0 auto; padding: 0; } .column, .columns { float: left; display: inline; margin-left: 10px; margin-right: 10px; } .row { margin-bottom: 20px; } /* Nested Column Classes */ .column.alpha, .columns.alpha { margin-left: 0; } .column.omega, .columns.omega { margin-right: 0; } /* Base Grid */ .container .one.column { width: 40px; } .container .two.columns { width: 100px; } .container .three.columns { width: 160px; } .container .four.columns { width: 220px; } .container .five.columns { width: 280px; } .container .six.columns { width: 340px; } .container .seven.columns { width: 400px; } .container .eight.columns { width: 460px; } .container .nine.columns { width: 520px; } .container .ten.columns { width: 580px; } .container .eleven.columns { width: 640px; } .container .twelve.columns { width: 700px; } .container .thirteen.columns { width: 760px; } .container .fourteen.columns { width: 820px; } .container .fifteen.columns { width: 880px; } .container .sixteen.columns { width: 940px; } .container .one-third.column { width: 300px; } .container .two-thirds.column { width: 620px; } /* Offsets */ .container .offset-by-one { padding-left: 60px; } .container .offset-by-two { padding-left: 120px; } .container .offset-by-three { padding-left: 180px; } .container .offset-by-four { padding-left: 240px; } .container .offset-by-five { padding-left: 300px; } .container .offset-by-six { padding-left: 360px; } .container .offset-by-seven { padding-left: 420px; } .container .offset-by-eight { padding-left: 480px; } .container .offset-by-nine { padding-left: 540px; } .container .offset-by-ten { padding-left: 600px; } .container .offset-by-eleven { padding-left: 660px; } .container .offset-by-twelve { padding-left: 720px; } .container .offset-by-thirteen { padding-left: 780px; } .container .offset-by-fourteen { padding-left: 840px; } .container .offset-by-fifteen { padding-left: 900px; } /* #Tablet (Portrait) ================================================== */ /* Note: Design for a width of 768px */ @media only screen and (min-width: 768px) and (max-width: 959px) { .container { width: 768px; } .container .column, .container .columns { margin-left: 10px; margin-right: 10px; } .column.alpha, .columns.alpha { margin-left: 0; margin-right: 10px; } .column.omega, .columns.omega { margin-right: 0; margin-left: 10px; } .container .one.column { width: 28px; } .container .two.columns { width: 76px; } .container .three.columns { width: 124px; } .container .four.columns { width: 172px; } .container .five.columns { width: 220px; } .container .six.columns { width: 268px; } .container .seven.columns { width: 316px; } .container .eight.columns { width: 364px; } .container .nine.columns { width: 412px; } .container .ten.columns { width: 460px; } .container .eleven.columns { width: 508px; } .container .twelve.columns { width: 556px; } .container .thirteen.columns { width: 604px; } .container .fourteen.columns { width: 652px; } .container .fifteen.columns { width: 700px; } .container .sixteen.columns { width: 748px; } .container .one-third.column { width: 236px; } .container .two-thirds.column { width: 492px; } /* Offsets */ .container .offset-by-one { padding-left: 48px; } .container .offset-by-two { padding-left: 96px; } .container .offset-by-three { padding-left: 144px; } .container .offset-by-four { padding-left: 192px; } .container .offset-by-five { padding-left: 240px; } .container .offset-by-six { padding-left: 288px; } .container .offset-by-seven { padding-left: 336px; } .container .offset-by-eight { padding-left: 348px; } .container .offset-by-nine { padding-left: 432px; } .container .offset-by-ten { padding-left: 480px; } .container .offset-by-eleven { padding-left: 528px; } .container .offset-by-twelve { padding-left: 576px; } .container .offset-by-thirteen { padding-left: 624px; } .container .offset-by-fourteen { padding-left: 672px; } .container .offset-by-fifteen { padding-left: 720px; } } /* #Mobile (Portrait) ================================================== */ /* Note: Design for a width of 320px */ @media only screen and (max-width: 767px) { .container { width: 300px; } .columns, .column { margin: 0; } .container .one.column, .container .two.columns, .container .three.columns, .container .four.columns, .container .five.columns, .container .six.columns, .container .seven.columns, .container .eight.columns, .container .nine.columns, .container .ten.columns, .container .eleven.columns, .container .twelve.columns, .container .thirteen.columns, .container .fourteen.columns, .container .fifteen.columns, .container .sixteen.columns, .container .one-third.column, .container .two-thirds.column { width: 300px; } /* Offsets */ .container .offset-by-one, .container .offset-by-two, .container .offset-by-three, .container .offset-by-four, .container .offset-by-five, .container .offset-by-six, .container .offset-by-seven, .container .offset-by-eight, .container .offset-by-nine, .container .offset-by-ten, .container .offset-by-eleven, .container .offset-by-twelve, .container .offset-by-thirteen, .container .offset-by-fourteen, .container .offset-by-fifteen { padding-left: 0; } } /* #Mobile (Landscape) ================================================== */ /* Note: Design for a width of 480px */ @media only screen and (min-width: 480px) and (max-width: 767px) { .container { width: 420px; } .columns, .column { margin: 0; } .container .one.column, .container .two.columns, .container .three.columns, .container .four.columns, .container .five.columns, .container .six.columns, .container .seven.columns, .container .eight.columns, .container .nine.columns, .container .ten.columns, .container .eleven.columns, .container .twelve.columns, .container .thirteen.columns, .container .fourteen.columns, .container .fifteen.columns, .container .sixteen.columns, .container .one-third.column, .container .two-thirds.column { width: 420px; } } /* #Clearing ================================================== */ /* Self Clearing Goodness */ .container:after { content: "\0020"; display: block; height: 0; clear: both; visibility: hidden; } /* Use clearfix class on parent to clear nested columns, or wrap each row of columns in a <div class="row"> */ .clearfix:before, .clearfix:after, .row:before, .row:after { content: '\0020'; display: block; overflow: hidden; visibility: hidden; width: 0; height: 0; } .row:after, .clearfix:after { clear: both; } .row, .clearfix { zoom: 1; } /* You can also use a <br class="clear" /> to clear columns */ .clear { clear: both; display: block; overflow: hidden; visibility: hidden; width: 0; height: 0; }
{ "pile_set_name": "Github" }
:imagesdir: ../../../images [[sahi-controller]] ==== Sahi Controller [#git-edit-section] :page-path: docs/manual/testdefinition/advanced-topics/sahi-controller.adoc git-link:{page-path}{git-view} | git-link:{page-path}{git-edit} TIP: Use the Sahi Controller to identify elements on the page to write and test Sahi methods! There are two ways to get Sahi instructions into your testcase `your-testcase.js`: * identify, copy &amp; paste from the Sahi Controller * record by the Sahi Controller, copy &amp; paste from the file, see <<sahi-recorder>> [[sahi-open-controller]] .Open the Sahi Controller Add to your testcase the following line, at position where you want to identify your HTML object: [source,js] ---- //.... your testcode env.sleep(9999); ---- Then start your test suite and the Sakuli test should appear and stop at that position for 9999 seconds. The "sleep" statement is a nice trick when writing long tests; wherever you put a 9999s sleep in, the test will execute until this position and wait. Think of it like a breakpoint when debugging a program. Now open the Sahi Controller (hold the `ALT` key on Windows or `CTRL + ALT` on Linux and doubleclick anywhere on the page) to open this window: image:tutorial_contoller.png[sahi_controller] [[sahi-controller-copy-paste]] .copy/paste code First, we want Sahi to check if there is for example the Sakuli Logo on the page. Hold the `CTRL` key and move the mouse pointer on the logo. Watch the Sahi Controller: it detects the HTML elements below the mouse pointer and generates the http://sahipro.com/docs/sahi-apis/accessor-apis.html#_image[accessor method for "image"] automatically: image:tutorial_logo_accessor.png[logo_accessor] Click on "Assert" to let Sahi autogenerate http://sahipro.com/docs/sahi-apis/assertions.html[assertion methods]: image:tutorial_assert2.png[assert] Just copy the second line (which checks the visibility of an element) into the clipboard and paste it into your testcase `your-testcase.js` before the `env.sleep(9999)` statement. Further, we want for example to assure that the contact form of the web page os displayed correctly. Move the mouse pointer down to the "Kontakt" link; Sahi should display the accessor `_image(&quot;Kontakt zu ConSol&quot;)` . This time use the "click" button on the controller . To execute a click; this also generates the complete http://sahipro.com/docs/sahi-apis/action-apis.html[browser action] statement . copy/paste also into the test case image:tutorial_click_action.png[click] In the end, Sahi should check that the appeared popup window contains the text "Schreiben Sie uns!". You guessed it - move the mouse pointer over this text and click the "Assert" button again. The fourth assertion is the right one, which we also paste into the test script: image:tutorial_contains_text.png[contains_text] Now remove the "sleep" statement from the script file; it should look now like that: [source,js] ---- _dynamicInclude($includeFolder); var testCase = new TestCase(60, 70); var env = new Environment() try{ //your code _assert(_isVisible(_image("sakuli.png"))); _click(_image("Kontakt zu conSol")); _assertContainsText("Schreiben Sie uns!", _heading3("Schreiben Sie uns!")); //env.sleep(9999); } catch (e) { testCase.handleException(e); } finally { testCase.saveResult(); } ---- TIP: Perhaps you want Sahi to highlight the items it is acting on: just use the `_highlight()` method from the http://sahipro.com/docs/sahi-apis/debug-helper-apis.html[debug helper API] to mark each element with a red border before accessing it: `_highlight(_image("sakuli.png"));`
{ "pile_set_name": "Github" }
// // Copyright © 2020 osy. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Parts taken from iSH: https://github.com/ish-app/ish/blob/master/app/AppGroup.m // Created by Theodore Dubois on 2/28/20. // Licensed under GNU General Public License 3.0 #import <Foundation/Foundation.h> #include <dlfcn.h> #include <errno.h> #include <mach/mach.h> #include <mach-o/loader.h> #include <mach-o/getsect.h> #include <pthread.h> #include <stdio.h> #include <string.h> #include <sys/mman.h> #include <sys/sysctl.h> #include <TargetConditionals.h> #include <unistd.h> #include "UTMJailbreak.h" struct cs_blob_index { uint32_t type; uint32_t offset; }; struct cs_superblob { uint32_t magic; uint32_t length; uint32_t count; struct cs_blob_index index[]; }; struct cs_entitlements { uint32_t magic; uint32_t length; char entitlements[]; }; extern int csops(pid_t pid, unsigned int ops, void * useraddr, size_t usersize); extern boolean_t exc_server(mach_msg_header_t *, mach_msg_header_t *); extern int ptrace(int request, pid_t pid, caddr_t addr, int data); #define CS_OPS_STATUS 0 /* return status */ #define CS_DEBUGGED 0x10000000 /* process is currently or has previously been debugged and allowed to run with invalid pages */ #define PT_TRACE_ME 0 /* child declares it's being traced */ #define PT_SIGEXC 12 /* signals as exceptions for current_proc */ kern_return_t catch_exception_raise(mach_port_t exception_port, mach_port_t thread, mach_port_t task, exception_type_t exception, exception_data_t code, mach_msg_type_number_t code_count) { fprintf(stderr, "Caught exception %d (this should be EXC_SOFTWARE), with code 0x%x (this should be EXC_SOFT_SIGNAL) and subcode %d. Forcing suicide.", exception, *code, code[1]); // _exit doesn't seem to work, but this does. ¯\_(ツ)_/¯ return KERN_FAILURE; } static void *exception_handler(void *argument) { mach_port_t port = *(mach_port_t *)argument; mach_msg_server(exc_server, 2048, port, 0); return NULL; } static bool am_i_being_debugged() { int flags; return !csops(getpid(), CS_OPS_STATUS, &flags, sizeof(flags)) && flags & CS_DEBUGGED; } static NSDictionary *parse_entitlements(const void *entitlements, size_t length) { char *copy = malloc(length); memcpy(copy, entitlements, length); // strip out psychic paper entitlement hiding if (@available(iOS 13.5, *)) { } else { static const char *needle = "<!---><!-->"; char *found = strnstr(copy, needle, length); if (found) { memset(found, ' ', strlen(needle)); } } NSData *data = [NSData dataWithBytes:copy length:length]; free(copy); return [NSPropertyListSerialization propertyListWithData:data options:NSPropertyListImmutable format:nil error:nil]; } static NSDictionary *app_entitlements(void) { // Inspired by codesign.c in Darwin sources for Security.framework // Find our mach-o header Dl_info dl_info; if (dladdr(app_entitlements, &dl_info) == 0) return nil; if (dl_info.dli_fbase == NULL) return nil; char *base = dl_info.dli_fbase; struct mach_header_64 *header = dl_info.dli_fbase; if (header->magic != MH_MAGIC_64) return nil; // Simulator executables have fake entitlements in the code signature. The real entitlements can be found in an __entitlements section. size_t entitlements_size; uint8_t *entitlements_data = getsectiondata(header, "__TEXT", "__entitlements", &entitlements_size); if (entitlements_data != NULL) { NSData *data = [NSData dataWithBytesNoCopy:entitlements_data length:entitlements_size freeWhenDone:NO]; return [NSPropertyListSerialization propertyListWithData:data options:NSPropertyListImmutable format:nil error:nil]; } // Find the LC_CODE_SIGNATURE struct load_command *lc = (void *) (base + sizeof(*header)); struct linkedit_data_command *cs_lc = NULL; for (uint32_t i = 0; i < header->ncmds; i++) { if (lc->cmd == LC_CODE_SIGNATURE) { cs_lc = (void *) lc; break; } lc = (void *) ((char *) lc + lc->cmdsize); } if (cs_lc == NULL) return nil; // Read the code signature off disk, as it's apparently not loaded into memory NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingFromURL:NSBundle.mainBundle.executableURL error:nil]; if (fileHandle == nil) return nil; [fileHandle seekToFileOffset:cs_lc->dataoff]; NSData *csData = [fileHandle readDataOfLength:cs_lc->datasize]; [fileHandle closeFile]; const struct cs_superblob *cs = csData.bytes; if (ntohl(cs->magic) != 0xfade0cc0) return nil; // Find the entitlements in the code signature for (uint32_t i = 0; i < ntohl(cs->count); i++) { struct cs_entitlements *ents = (void *) ((char *) cs + ntohl(cs->index[i].offset)); if (ntohl(ents->magic) == 0xfade7171) { return parse_entitlements(ents->entitlements, ntohl(ents->length) - offsetof(struct cs_entitlements, entitlements)); } } return nil; } bool jb_has_jit_entitlement(void) { static NSDictionary *entitlements = nil; if (!entitlements) { entitlements = app_entitlements(); } return [entitlements[@"dynamic-codesigning"] boolValue]; } bool jb_enable_ptrace_hack(void) { #if defined(NO_PTRACE_HACK) return false; #else bool debugged = am_i_being_debugged(); // Thanks to this comment: https://news.ycombinator.com/item?id=18431524 // We use this hack to allow mmap with PROT_EXEC (which usually requires the // dynamic-codesigning entitlement) by tricking the process into thinking // that Xcode is debugging it. We abuse the fact that JIT is needed to // debug the process. if (ptrace(PT_TRACE_ME, 0, NULL, 0) < 0) { return false; } // ptracing ourselves confuses the kernel and will cause bad things to // happen to the system (hangs…) if an exception or signal occurs. Setup // some "safety nets" so we can cause the process to exit in a somewhat sane // state. We only need to do this if the debugger isn't attached. (It'll do // this itself, and if we do it we'll interfere with its normal operation // anyways.) if (!debugged) { // First, ensure that signals are delivered as Mach software exceptions… ptrace(PT_SIGEXC, 0, NULL, 0); // …then ensure that this exception goes through our exception handler. // I think it's OK to just watch for EXC_SOFTWARE because the other // exceptions (e.g. EXC_BAD_ACCESS, EXC_BAD_INSTRUCTION, and friends) // will end up being delivered as signals anyways, and we can get them // once they're resent as a software exception. mach_port_t port = MACH_PORT_NULL; mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &port); mach_port_insert_right(mach_task_self(), port, port, MACH_MSG_TYPE_MAKE_SEND); task_set_exception_ports(mach_task_self(), EXC_MASK_SOFTWARE, port, EXCEPTION_DEFAULT, THREAD_STATE_NONE); pthread_t thread; pthread_create(&thread, NULL, exception_handler, (void *)&port); } return true; #endif }
{ "pile_set_name": "Github" }
<?php /* * 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 thrift.protocol */ namespace Thrift\Protocol; use Thrift\Protocol\TProtocol; use Thrift\Type\TType; use Thrift\Exception\TProtocolException; use Thrift\Factory\TStringFuncFactory; /** * Binary implementation of the Thrift protocol. * */ class TBinaryProtocol extends TProtocol { const VERSION_MASK = 0xffff0000; const VERSION_1 = 0x80010000; protected $strictRead_ = false; protected $strictWrite_ = true; public function __construct($trans, $strictRead=false, $strictWrite=true) { parent::__construct($trans); $this->strictRead_ = $strictRead; $this->strictWrite_ = $strictWrite; } public function writeMessageBegin($name, $type, $seqid) { if ($this->strictWrite_) { $version = self::VERSION_1 | $type; return $this->writeI32($version) + $this->writeString($name) + $this->writeI32($seqid); } else { return $this->writeString($name) + $this->writeByte($type) + $this->writeI32($seqid); } } public function writeMessageEnd() { return 0; } public function writeStructBegin($name) { return 0; } public function writeStructEnd() { return 0; } public function writeFieldBegin($fieldName, $fieldType, $fieldId) { return $this->writeByte($fieldType) + $this->writeI16($fieldId); } public function writeFieldEnd() { return 0; } public function writeFieldStop() { return $this->writeByte(TType::STOP); } public function writeMapBegin($keyType, $valType, $size) { return $this->writeByte($keyType) + $this->writeByte($valType) + $this->writeI32($size); } public function writeMapEnd() { return 0; } public function writeListBegin($elemType, $size) { return $this->writeByte($elemType) + $this->writeI32($size); } public function writeListEnd() { return 0; } public function writeSetBegin($elemType, $size) { return $this->writeByte($elemType) + $this->writeI32($size); } public function writeSetEnd() { return 0; } public function writeBool($value) { $data = pack('c', $value ? 1 : 0); $this->trans_->write($data, 1); return 1; } public function writeByte($value) { $data = pack('c', $value); $this->trans_->write($data, 1); return 1; } public function writeI16($value) { $data = pack('n', $value); $this->trans_->write($data, 2); return 2; } public function writeI32($value) { $data = pack('N', $value); $this->trans_->write($data, 4); return 4; } public function writeI64($value) { // If we are on a 32bit architecture we have to explicitly deal with // 64-bit twos-complement arithmetic since PHP wants to treat all ints // as signed and any int over 2^31 - 1 as a float if (PHP_INT_SIZE == 4) { $neg = $value < 0; if ($neg) { $value *= -1; } $hi = (int)($value / 4294967296); $lo = (int)$value; if ($neg) { $hi = ~$hi; $lo = ~$lo; if (($lo & (int)0xffffffff) == (int)0xffffffff) { $lo = 0; $hi++; } else { $lo++; } } $data = pack('N2', $hi, $lo); } else { $hi = $value >> 32; $lo = $value & 0xFFFFFFFF; $data = pack('N2', $hi, $lo); } $this->trans_->write($data, 8); return 8; } public function writeDouble($value) { $data = pack('d', $value); $this->trans_->write(strrev($data), 8); return 8; } public function writeString($value) { $len = TStringFuncFactory::create()->strlen($value); $result = $this->writeI32($len); if ($len) { $this->trans_->write($value, $len); } return $result + $len; } public function readMessageBegin(&$name, &$type, &$seqid) { $result = $this->readI32($sz); if ($sz < 0) { $version = (int) ($sz & self::VERSION_MASK); if ($version != (int) self::VERSION_1) { throw new TProtocolException('Bad version identifier: '.$sz, TProtocolException::BAD_VERSION); } $type = $sz & 0x000000ff; $result += $this->readString($name) + $this->readI32($seqid); } else { if ($this->strictRead_) { throw new TProtocolException('No version identifier, old protocol client?', TProtocolException::BAD_VERSION); } else { // Handle pre-versioned input $name = $this->trans_->readAll($sz); $result += $sz + $this->readByte($type) + $this->readI32($seqid); } } return $result; } public function readMessageEnd() { return 0; } public function readStructBegin(&$name) { $name = ''; return 0; } public function readStructEnd() { return 0; } public function readFieldBegin(&$name, &$fieldType, &$fieldId) { $result = $this->readByte($fieldType); if ($fieldType == TType::STOP) { $fieldId = 0; return $result; } $result += $this->readI16($fieldId); return $result; } public function readFieldEnd() { return 0; } public function readMapBegin(&$keyType, &$valType, &$size) { return $this->readByte($keyType) + $this->readByte($valType) + $this->readI32($size); } public function readMapEnd() { return 0; } public function readListBegin(&$elemType, &$size) { return $this->readByte($elemType) + $this->readI32($size); } public function readListEnd() { return 0; } public function readSetBegin(&$elemType, &$size) { return $this->readByte($elemType) + $this->readI32($size); } public function readSetEnd() { return 0; } public function readBool(&$value) { $data = $this->trans_->readAll(1); $arr = unpack('c', $data); $value = $arr[1] == 1; return 1; } public function readByte(&$value) { $data = $this->trans_->readAll(1); $arr = unpack('c', $data); $value = $arr[1]; return 1; } public function readI16(&$value) { $data = $this->trans_->readAll(2); $arr = unpack('n', $data); $value = $arr[1]; if ($value > 0x7fff) { $value = 0 - (($value - 1) ^ 0xffff); } return 2; } public function readI32(&$value) { $data = $this->trans_->readAll(4); $arr = unpack('N', $data); $value = $arr[1]; if ($value > 0x7fffffff) { $value = 0 - (($value - 1) ^ 0xffffffff); } return 4; } public function readI64(&$value) { $data = $this->trans_->readAll(8); $arr = unpack('N2', $data); // If we are on a 32bit architecture we have to explicitly deal with // 64-bit twos-complement arithmetic since PHP wants to treat all ints // as signed and any int over 2^31 - 1 as a float if (PHP_INT_SIZE == 4) { $hi = $arr[1]; $lo = $arr[2]; $isNeg = $hi < 0; // Check for a negative if ($isNeg) { $hi = ~$hi & (int)0xffffffff; $lo = ~$lo & (int)0xffffffff; if ($lo == (int)0xffffffff) { $hi++; $lo = 0; } else { $lo++; } } // Force 32bit words in excess of 2G to pe positive - we deal wigh sign // explicitly below if ($hi & (int)0x80000000) { $hi &= (int)0x7fffffff; $hi += 0x80000000; } if ($lo & (int)0x80000000) { $lo &= (int)0x7fffffff; $lo += 0x80000000; } $value = $hi * 4294967296 + $lo; if ($isNeg) { $value = 0 - $value; } } else { // Upcast negatives in LSB bit if ($arr[2] & 0x80000000) { $arr[2] = $arr[2] & 0xffffffff; } // Check for a negative if ($arr[1] & 0x80000000) { $arr[1] = $arr[1] & 0xffffffff; $arr[1] = $arr[1] ^ 0xffffffff; $arr[2] = $arr[2] ^ 0xffffffff; $value = 0 - $arr[1]*4294967296 - $arr[2] - 1; } else { $value = $arr[1]*4294967296 + $arr[2]; } } return 8; } public function readDouble(&$value) { $data = strrev($this->trans_->readAll(8)); $arr = unpack('d', $data); $value = $arr[1]; return 8; } public function readString(&$value) { $result = $this->readI32($len); if ($len) { $value = $this->trans_->readAll($len); } else { $value = ''; } return $result + $len; } }
{ "pile_set_name": "Github" }
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 15 2018 10:31:50). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard. // #import <objc/NSObject.h> @class SCRUIElement; __attribute__((visibility("hidden"))) @interface SCRChildrenHashNode : NSObject { SCRUIElement *_uiElement; unsigned long long *_childrenCount; unsigned long long _childrenHash; } - (void).cxx_destruct; @property(nonatomic) unsigned long long childrenHash; // @synthesize childrenHash=_childrenHash; @property(nonatomic) unsigned long long *childrenCount; // @synthesize childrenCount=_childrenCount; @property(retain, nonatomic) SCRUIElement *uiElement; // @synthesize uiElement=_uiElement; - (BOOL)didChildrenHashChange; - (id)initWithUIElement:(id)arg1 childrenHash:(unsigned long long)arg2; - (id)init; @end
{ "pile_set_name": "Github" }
/* Copyright 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. */ // Code generated by lister-gen. DO NOT EDIT. package v1beta1 import ( v1beta1 "k8s.io/api/storage/v1beta1" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/labels" "k8s.io/client-go/tools/cache" ) // CSIDriverLister helps list CSIDrivers. type CSIDriverLister interface { // List lists all CSIDrivers in the indexer. List(selector labels.Selector) (ret []*v1beta1.CSIDriver, err error) // Get retrieves the CSIDriver from the index for a given name. Get(name string) (*v1beta1.CSIDriver, error) CSIDriverListerExpansion } // cSIDriverLister implements the CSIDriverLister interface. type cSIDriverLister struct { indexer cache.Indexer } // NewCSIDriverLister returns a new CSIDriverLister. func NewCSIDriverLister(indexer cache.Indexer) CSIDriverLister { return &cSIDriverLister{indexer: indexer} } // List lists all CSIDrivers in the indexer. func (s *cSIDriverLister) List(selector labels.Selector) (ret []*v1beta1.CSIDriver, err error) { err = cache.ListAll(s.indexer, selector, func(m interface{}) { ret = append(ret, m.(*v1beta1.CSIDriver)) }) return ret, err } // Get retrieves the CSIDriver from the index for a given name. func (s *cSIDriverLister) Get(name string) (*v1beta1.CSIDriver, error) { obj, exists, err := s.indexer.GetByKey(name) if err != nil { return nil, err } if !exists { return nil, errors.NewNotFound(v1beta1.Resource("csidriver"), name) } return obj.(*v1beta1.CSIDriver), nil }
{ "pile_set_name": "Github" }
using Eto.Drawing; using swm = System.Windows.Media; namespace Eto.Wpf.Drawing { class FrozenBrushWrapper { public FrozenBrushWrapper(swm.Brush brush) { Brush = brush; SetFrozen(); } public swm.Brush Brush { get; } public swm.Brush FrozenBrush { get; private set; } public void SetFrozen() => FrozenBrush = (swm.Brush)Brush.GetAsFrozen(); } /// <summary> /// Handler for <see cref="ISolidBrush"/> /// </summary> /// <copyright>(c) 2012-2014 by Curtis Wensley</copyright> /// <license type="BSD-3">See LICENSE for full terms</license> public class SolidBrushHandler : SolidBrush.IHandler { static swm.SolidColorBrush Get(SolidBrush widget) => ((FrozenBrushWrapper)widget.ControlObject).Brush as swm.SolidColorBrush; static void SetFrozen(SolidBrush widget) => ((FrozenBrushWrapper)widget.ControlObject).SetFrozen(); public Color GetColor(SolidBrush widget) { return Get(widget).Color.ToEto(); } public void SetColor(SolidBrush widget, Color color) { Get(widget).Color = color.ToWpf(); SetFrozen(widget); } public object Create(Color color) { return new FrozenBrushWrapper(new swm.SolidColorBrush(color.ToWpf())); } } }
{ "pile_set_name": "Github" }
#!/bin/bash : << '--COMMENT--' Dependencies sudo apt-get install tree --COMMENT-- ## set file date ## find ~/.local/share/0ad/mods/hannibal -exec touch -t 201501220000 {} \; ## paths # pathRoot="/Daten/Dropbox/Projects/hannibal/" pathCode="/home/noiv/.local/share/0ad/mods/hannibal/simulation/ai/hannibal" pathDistri="/Daten/Dropbox/Projects/hannibal" pathDiffer="/home/noiv/Sources/prettydiff-master" ## files compiler="/home/noiv/Programs/closure-compiler/compiler.jar" echo echo "-- Start" echo ## STATIC cd $pathDistri cp LICENCE.txt "${pathDistri}/mods/hannibal/LICENCE.txt" cp README.md "${pathDistri}/mods/hannibal/README.md" cp readme.txt "${pathDistri}/mods/hannibal.readme.txt" cd $pathCode cp data.json "${pathDistri}/mods/hannibal/simulation/ai/hannibal/data.json" ## DYNAMIC cd $pathCode rm -f \ hannibal.m.js \ _debug.js ls _*.js | xargs cat > _.jss ls [a-z]*.js | xargs cat > az.jss cat _.jss az.jss > hannibal.m.js rm -f \ _.jss \ az.jss mv hannibal.m.js "${pathDistri}/mods/hannibal/simulation/ai/hannibal/hannibal.m.js" echo echo counting locs in hannibal.m.js ... cd "${pathDistri}/mods/hannibal/simulation/ai/hannibal/" cat hannibal.m.js | grep -v ^$ | wc -l ## java -jar compiler.jar --help ## real compress # --compilation_level SIMPLE_OPTIMIZATIONS \ # --language_out ES5_strict \ # --tracer_mode ALL \ # --language_in ECMASCRIPT6_STRICT \ # --language_out ECMASCRIPT6_STRICT \ echo echo compressing... cd "${pathDistri}/mods/hannibal/simulation/ai/hannibal/" # java -jar $compiler \ # --compilation_level WHITESPACE_ONLY \ # --js hannibal.m.js --js_output_file hannibal.js fileMini="${pathDistri}/mods/hannibal/simulation/ai/hannibal/hannibal.m.js" fileFina="${pathDistri}/mods/hannibal/simulation/ai/hannibal/hannibal.js" echo "${pathDiffer}/api/node-local.js source:'${fileMini}' mode:'minify' readmethod:'file' output:'hannibal.js'" js "${pathDiffer}/api/node-local.js source:'${fileMini}' mode:minify" ## source:'hannibal.m.js' mode:'minify' readmethod:'file' output:'hannibal.js'" ## fake compress # cd "${pathDistri}/mods/hannibal/simulation/ai/hannibal/" # cp hannibal.m.js hannibal.u.js # cp hannibal.u.js hannibal.p.js # cp hannibal.p.js hannibal.js ## clearup compress cd "${pathDistri}/mods/hannibal/simulation/ai/hannibal/" rm -f \ # hannibal.m.js \ hannibal.u.js \ hannibal.p.js ## ZIP echo echo zipping... cd "${pathDistri}/mods/" rm -f hannibal.zip zip hannibal.zip \ hannibal/mod.json \ hannibal/README.md \ hannibal/LICENCE.txt \ hannibal/simulation/ai/hannibal/data.json \ hannibal/simulation/ai/hannibal/hannibal.js ## CHECK cd "${pathDistri}/mods/" tree unzip -l hannibal.zip echo echo "-- Done --" echo
{ "pile_set_name": "Github" }
@ f2 res8: Future[String] = Future(Success($2a$17$O0fnZkDyZ1bsJknuXw.eG.9Mesh9W03ZnVPefgcTV...
{ "pile_set_name": "Github" }
/* * Copyright (c) 2003, 2020, 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. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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 sun.security.timestamp; import java.io.IOException; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.cert.X509Extension; import sun.security.util.DerValue; import sun.security.util.DerOutputStream; import sun.security.util.ObjectIdentifier; import sun.security.x509.AlgorithmId; /** * This class provides a timestamp request, as defined in * <a href="http://www.ietf.org/rfc/rfc3161.txt">RFC 3161</a>. * * The TimeStampReq ASN.1 type has the following definition: * <pre> * * TimeStampReq ::= SEQUENCE { * version INTEGER { v1(1) }, * messageImprint MessageImprint * -- a hash algorithm OID and the hash value of the data to be * -- time-stamped. * reqPolicy TSAPolicyId OPTIONAL, * nonce INTEGER OPTIONAL, * certReq BOOLEAN DEFAULT FALSE, * extensions [0] IMPLICIT Extensions OPTIONAL } * * MessageImprint ::= SEQUENCE { * hashAlgorithm AlgorithmIdentifier, * hashedMessage OCTET STRING } * * TSAPolicyId ::= OBJECT IDENTIFIER * * </pre> * * @since 1.5 * @author Vincent Ryan * @see Timestamper */ public class TSRequest { private int version = 1; private AlgorithmId hashAlgorithmId = null; private byte[] hashValue; private String policyId = null; private BigInteger nonce = null; private boolean returnCertificate = false; private X509Extension[] extensions = null; /** * Constructs a timestamp request for the supplied data. * * @param toBeTimeStamped The data to be timestamped. * @param messageDigest The MessageDigest of the hash algorithm to use. * @throws NoSuchAlgorithmException if the hash algorithm is not supported */ public TSRequest(String tSAPolicyID, byte[] toBeTimeStamped, MessageDigest messageDigest) throws NoSuchAlgorithmException { this.policyId = tSAPolicyID; this.hashAlgorithmId = AlgorithmId.get(messageDigest.getAlgorithm()); this.hashValue = messageDigest.digest(toBeTimeStamped); } public byte[] getHashedMessage() { return hashValue.clone(); } /** * Sets the Time-Stamp Protocol version. * * @param version The TSP version. */ public void setVersion(int version) { this.version = version; } /** * Sets an object identifier for the Time-Stamp Protocol policy. * * @param policyId The policy object identifier. */ public void setPolicyId(String policyId) { this.policyId = policyId; } /** * Sets a nonce. * A nonce is a single-use random number. * * @param nonce The nonce value. */ public void setNonce(BigInteger nonce) { this.nonce = nonce; } /** * Request that the TSA include its signing certificate in the response. * * @param returnCertificate True if the TSA should return its signing * certificate. By default it is not returned. */ public void requestCertificate(boolean returnCertificate) { this.returnCertificate = returnCertificate; } /** * Sets the Time-Stamp Protocol extensions. * * @param extensions The protocol extensions. */ public void setExtensions(X509Extension[] extensions) { this.extensions = extensions; } public byte[] encode() throws IOException { DerOutputStream request = new DerOutputStream(); // encode version request.putInteger(version); // encode messageImprint DerOutputStream messageImprint = new DerOutputStream(); hashAlgorithmId.encode(messageImprint); messageImprint.putOctetString(hashValue); request.write(DerValue.tag_Sequence, messageImprint); // encode optional elements if (policyId != null) { request.putOID(ObjectIdentifier.of(policyId)); } if (nonce != null) { request.putInteger(nonce); } if (returnCertificate) { request.putBoolean(true); } DerOutputStream out = new DerOutputStream(); out.write(DerValue.tag_Sequence, request); return out.toByteArray(); } }
{ "pile_set_name": "Github" }
package mage.cards.w; import java.util.UUID; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.condition.common.OpponentControlsPermanentCondition; import mage.abilities.decorator.ConditionalContinuousRuleModifyingEffect; import mage.abilities.effects.ContinuousRuleModifyingEffect; import mage.abilities.effects.common.DontUntapInControllersUntapStepSourceEffect; import mage.abilities.keyword.CantBeBlockedSourceAbility; import mage.constants.SubType; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.ComparisonType; import mage.constants.Zone; import mage.filter.common.FilterCreaturePermanent; /** * * @author jeffwadsworth */ public final class WalkingDream extends CardImpl { private static final String rule = "{this} doesn't untap during your untap step if an opponent controls two or more creatures."; public WalkingDream(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{3}{U}"); this.subtype.add(SubType.ILLUSION); this.power = new MageInt(3); this.toughness = new MageInt(3); // Walking Dream is unblockable. this.addAbility(new CantBeBlockedSourceAbility()); // Walking Dream doesn't untap during your untap step if an opponent controls two or more creatures. ContinuousRuleModifyingEffect dontUntap = new DontUntapInControllersUntapStepSourceEffect(false, true); dontUntap.setText(rule); Ability ability = new SimpleStaticAbility(Zone.BATTLEFIELD, new ConditionalContinuousRuleModifyingEffect( dontUntap, new OpponentControlsPermanentCondition( new FilterCreaturePermanent(), ComparisonType.MORE_THAN, 1))); this.addAbility(ability); } public WalkingDream(final WalkingDream card) { super(card); } @Override public WalkingDream copy() { return new WalkingDream(this); } }
{ "pile_set_name": "Github" }