text
stringlengths
2
100k
meta
dict
/* SPDX-License-Identifier: GPL-2.0+ */ #ifndef __CYRUS_H #define __CYRUS_H void fdt_fixup_board_enet(void *blob); void pci_of_setup(void *blob, struct bd_info *bd); #endif
{ "pile_set_name": "Github" }
// Copyright (C) 2005 Arkadiy Vertleyb, Peder Holt. // Use, modification and distribution is subject to the Boost Software // License, Version 1.0. (http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_TYPEOF_STD_stack_hpp_INCLUDED #define BOOST_TYPEOF_STD_stack_hpp_INCLUDED #include <stack> #include <boost/typeof/typeof.hpp> #include <boost/typeof/std/memory.hpp> #include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP() BOOST_TYPEOF_REGISTER_TEMPLATE(std::stack, 1) BOOST_TYPEOF_REGISTER_TEMPLATE(std::stack, 2) #endif//BOOST_TYPEOF_STD_stack_hpp_INCLUDED
{ "pile_set_name": "Github" }
import _ from 'lodash'; const removeEmptyMatch = pipeline => _.filter(pipeline, (stage) => { if (_.has(stage, '$match') && _.size(stage.$match) === 0) return false; return true; }) ; export default removeEmptyMatch;
{ "pile_set_name": "Github" }
--- layout: page title: "Q37481: PRINT USING Statement Fails to Use Print Zones" permalink: /pubs/pc/reference/microsoft/kb/Q37481/ --- ## Q37481: PRINT USING Statement Fails to Use Print Zones Article: Q37481 Version(s): 4.00 4.00b 4.50 Operating System: MS-DOS Flags: ENDUSER | docerr B_BasicCom Last Modified: 12-JAN-1990 The PRINT USING statement is not designed to print the values of an expression list in the 14-character print zones. Instead, it ignores the comma and treats it like a semicolon. In QuickBASIC Version 4.50, the syntax checker correctly changes the comma to a semicolon. However, several manuals (listed below) and the online help system incorrectly state that the comma is syntactically legal. The incorrect syntax for the PRINT USING statement is as follows: PRINT USING formatstring; expressionlist [{,|;}] The incorrect definition for the PRINT USING statement is as follows: The position of each printed item is determined by the punctuation used to separate the items in the list. BASIC divides the line into print zones of 14 spaces each. In the expression list, a comma makes the next value print at the start of the next zone. A semicolon makes the next value print immediately after the last value. This incorrect syntax or definition is given in each of the following references: 1. Page 275 of the "Microsoft BASIC 7.0: BASIC Language Reference" for Microsoft BASIC PDS Version 7.00 2. Page 335 of the "Microsoft QuickBASIC 4.0: BASIC Language Reference" for QuickBASIC 4.00 and 4.00b 3. Page 287 of the "Microsoft QuickBASIC: BASIC Language Reference" for QuickBASIC 4.50 4. Page 335 of the "Microsoft BASIC Compiler 6.0: BASIC Language Reference" for Microsoft BASIC Compiler Versions 6.00 and 6.00b 5. The online help system for Microsoft QuickBASIC 4.50 under the entry for PRINT USING statement 6. The online help system for BASIC PDS 7.00 under the entry for the PRINT USING statement The following is a code example that demonstrates that PRINT USING treats commas as if they were semicolons. When run in the environment, the code example will correctly substitute a semicolon between the variables "a" and "b" for the comma: a=3.45 b=5.23 PRINT USING "##.##";a,b The output is as follows: 3.45 5.23
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <meta name="description" content="API documentation for the Rust `errors` mod in crate `mentat_query_projector`."> <meta name="keywords" content="rust, rustlang, rust-lang, errors"> <title>mentat_query_projector::errors - Rust</title> <link rel="stylesheet" type="text/css" href="../../normalize.css"> <link rel="stylesheet" type="text/css" href="../../rustdoc.css" id="mainThemeStyle"> <link rel="stylesheet" type="text/css" href="../../dark.css"> <link rel="stylesheet" type="text/css" href="../../light.css" id="themeStyle"> <script src="../../storage.js"></script> </head> <body class="rustdoc mod"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <nav class="sidebar"> <div class="sidebar-menu">&#9776;</div> <p class='location'>Module errors</p><div class="sidebar-elems"><div class="block items"><ul><li><a href="#enums">Enums</a></li><li><a href="#types">Type Definitions</a></li></ul></div><p class='location'><a href='../index.html'>mentat_query_projector</a></p><script>window.sidebarCurrent = {name: 'errors', ty: 'mod', relpath: '../'};</script><script defer src="../sidebar-items.js"></script></div> </nav> <div class="theme-picker"> <button id="theme-picker" aria-label="Pick another theme!"> <img src="../../brush.svg" width="18" alt="Pick another theme!"> </button> <div id="theme-choices"></div> </div> <script src="../../theme.js"></script> <nav class="sub"> <form class="search-form js-only"> <div class="search-container"> <input class="search-input" name="search" autocomplete="off" placeholder="Click or press ‘S’ to search, ‘?’ for more options
" type="search"> </div> </form> </nav> <section id='main' class="content"><h1 class='fqn'><span class='in-band'>Module <a href='../index.html'>mentat_query_projector</a>::<wbr><a class="mod" href=''>errors</a></span><span class='out-of-band'><span id='render-detail'> <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs"> [<span class='inner'>&#x2212;</span>] </a> </span><a class='srclink' href='../../src/mentat_query_projector/errors.rs.html#11-93' title='goto source code'>[src]</a></span></h1><h2 id='enums' class='section-header'><a href="#enums">Enums</a></h2> <table> <tr class=' module-item'> <td><a class="enum" href="enum.ProjectorError.html" title='enum mentat_query_projector::errors::ProjectorError'>ProjectorError</a></td> <td class='docblock-short'> </td> </tr></table><h2 id='types' class='section-header'><a href="#types">Type Definitions</a></h2> <table> <tr class=' module-item'> <td><a class="type" href="type.Result.html" title='type mentat_query_projector::errors::Result'>Result</a></td> <td class='docblock-short'> </td> </tr></table></section> <section id='search' class="content hidden"></section> <section class="footer"></section> <aside id="help" class="hidden"> <div> <h1 class="hidden">Help</h1> <div class="shortcuts"> <h2>Keyboard Shortcuts</h2> <dl> <dt><kbd>?</kbd></dt> <dd>Show this help dialog</dd> <dt><kbd>S</kbd></dt> <dd>Focus the search field</dd> <dt><kbd>↑</kbd></dt> <dd>Move up in search results</dd> <dt><kbd>↓</kbd></dt> <dd>Move down in search results</dd> <dt><kbd>↹</kbd></dt> <dd>Switch tab</dd> <dt><kbd>&#9166;</kbd></dt> <dd>Go to active search result</dd> <dt><kbd>+</kbd></dt> <dd>Expand all sections</dd> <dt><kbd>-</kbd></dt> <dd>Collapse all sections</dd> </dl> </div> <div class="infos"> <h2>Search Tricks</h2> <p> Prefix searches with a type followed by a colon (e.g. <code>fn:</code>) to restrict the search to a given type. </p> <p> Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, and <code>const</code>. </p> <p> Search functions by type signature (e.g. <code>vec -> usize</code> or <code>* -> vec</code>) </p> </div> </div> </aside> <script> window.rootPath = "../../"; window.currentCrate = "mentat_query_projector"; </script> <script src="../../main.js"></script> <script defer src="../../search-index.js"></script> </body> </html>
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="org.ibase4j.mapper.SysSessionMapper"> <!-- --> <select id="selectIdPage" resultType="java.lang.Long" useCache="false"> select id_ from sys_session <where> <if test="cm.keyword != null"> and (account_ like CONCAT('%',#{cm.keyword},'%') or session_id like CONCAT('%',#{cm.keyword},'%') or ip_ like CONCAT('%',#{cm.keyword},'%')) </if> </where> </select> <delete id="deleteBySessionId" parameterType="java.lang.String"> delete from sys_session where session_id=#{sessionId} </delete> <select id="queryBySessionId" resultType="java.lang.Long"> select id_ from sys_session where session_id = #{sessionId} </select> <select id="querySessionIdByAccount" resultType="java.lang.String"> select session_id from sys_session where account_ = #{account} </select> </mapper>
{ "pile_set_name": "Github" }
// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build linux // +build mips mipsle // +build !gccgo #include "textflag.h" // // System calls for mips, Linux // // Just jump to package syscall's implementation for all these functions. // The runtime may know about them. TEXT ·Syscall(SB),NOSPLIT,$0-28 JMP syscall·Syscall(SB) TEXT ·Syscall6(SB),NOSPLIT,$0-40 JMP syscall·Syscall6(SB) TEXT ·Syscall9(SB),NOSPLIT,$0-52 JMP syscall·Syscall9(SB) TEXT ·SyscallNoError(SB),NOSPLIT,$0-24 JAL runtime·entersyscall(SB) MOVW a1+4(FP), R4 MOVW a2+8(FP), R5 MOVW a3+12(FP), R6 MOVW R0, R7 MOVW trap+0(FP), R2 // syscall entry SYSCALL MOVW R2, r1+16(FP) // r1 MOVW R3, r2+20(FP) // r2 JAL runtime·exitsyscall(SB) RET TEXT ·RawSyscall(SB),NOSPLIT,$0-28 JMP syscall·RawSyscall(SB) TEXT ·RawSyscall6(SB),NOSPLIT,$0-40 JMP syscall·RawSyscall6(SB) TEXT ·RawSyscallNoError(SB),NOSPLIT,$0-24 MOVW a1+4(FP), R4 MOVW a2+8(FP), R5 MOVW a3+12(FP), R6 MOVW trap+0(FP), R2 // syscall entry SYSCALL MOVW R2, r1+16(FP) MOVW R3, r2+20(FP) RET
{ "pile_set_name": "Github" }
<!DOCTYPE html> <style> iframe { position:absolute; top: 50px; left: 50px; width: 100px; height: 100px; } div { position: absolute; top: 50px; left: 50px; width: 70px; height: 20px; background-color: red; z-index: 100; } </style> <html> <body> <iframe src="/cross-site/baz.com/title1.html"></iframe> This page contains a positioned cross-origin iframe. <div>x</div> </body> </html>
{ "pile_set_name": "Github" }
/** * Aptana Studio * Copyright (c) 2005-2011 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the GNU Public License (GPL) v3 (with exceptions). * Please see the license.html included with this distribution for details. * Any modifications to this file must keep this entire header intact. */ package com.aptana.js.debug.core.internal.model; import org.eclipse.debug.core.DebugEvent; import org.eclipse.debug.core.DebugException; import org.eclipse.debug.core.model.IDebugTarget; import org.eclipse.debug.core.model.IValue; import com.aptana.core.util.StringUtil; import com.aptana.js.debug.core.model.IJSVariable; /** * @author Max Stepanov */ public class JSDebugVariable extends JSDebugElement implements IJSVariable { /** * FLAGS_MODIFIABLE */ protected static final int FLAGS_MODIFIABLE = 0x01; /** * FLAGS_LOCAL */ protected static final int FLAGS_LOCAL = 0x02; /** * FLAGS_ARGUMENT */ protected static final int FLAGS_ARGUMENT = 0x04; /** * FLAGS_EXCEPTION */ protected static final int FLAGS_EXCEPTION = 0x08; /** * FLAGS_CONST */ protected static final int FLAGS_CONST = 0x10; /** * FLAGS_TOPLEVEL */ protected static final int FLAGS_TOPLEVEL = 0x80; private final String threadId; private final String qualifier; private final String name; private IValue value; /* package */int flags; /** * JSDebugVariable * * @param target * @param qualifier * @param name * @param value */ public JSDebugVariable(IDebugTarget target, String threadId, String qualifier, String name, IValue value) { this(target, threadId, qualifier, name, value, 0); } /** * JSDebugVariable * * @param target * @param qualifier * @param name * @param flags */ public JSDebugVariable(IDebugTarget target, String threadId, String qualifier, String name, int flags) { this(target, threadId, qualifier, name, null, flags); } /** * JSDebugVariable * * @param target * @param qualifier * @param name * @param value * @param flags */ public JSDebugVariable(IDebugTarget target, String threadId, String qualifier, String name, IValue value, int flags) { super(target); this.threadId = threadId; this.qualifier = qualifier; this.name = name; this.value = value; this.flags = flags; } /* * @see org.eclipse.debug.core.model.IVariable#getValue() */ public IValue getValue() throws DebugException { return value; } /* * @see org.eclipse.debug.core.model.IVariable#getName() */ public String getName() throws DebugException { return name; } /* * @see org.eclipse.debug.core.model.IVariable#getReferenceTypeName() */ public String getReferenceTypeName() throws DebugException { return value.getReferenceTypeName(); } /* * @see org.eclipse.debug.core.model.IVariable#hasValueChanged() */ public boolean hasValueChanged() throws DebugException { return false; } /* * @see org.eclipse.debug.core.model.IValueModification#setValue(java.lang.String) */ public void setValue(String expression) throws DebugException { Object result = ((JSDebugTarget) getDebugTarget()).evaluateExpression(expression, this); if (result instanceof IValue) { result = ((JSDebugTarget) getDebugTarget()).setValue(this, (IValue) result); if (result instanceof IValue) { value = (IValue) result; fireChangeEvent(DebugEvent.CONTENT); return; } } if (result instanceof String[]) { throwDebugException(((String[]) result)[0]); } else { throwDebugException(StringUtil.EMPTY); } } /* * @see org.eclipse.debug.core.model.IValueModification#setValue(org.eclipse.debug.core.model.IValue) */ public void setValue(IValue value) throws DebugException { throwNotImplemented(); } /* * @see org.eclipse.debug.core.model.IValueModification#supportsValueModification() */ public boolean supportsValueModification() { return (flags & FLAGS_MODIFIABLE) != 0; } /* * @see org.eclipse.debug.core.model.IValueModification#verifyValue(java.lang.String) */ public boolean verifyValue(String expression) throws DebugException { Object result = ((JSDebugTarget) getDebugTarget()).evaluateExpression(expression, this); if (result instanceof IValue) { return true; } else if (result == null) { throwDebugException("unknown behaviour"); //$NON-NLS-1$ } return false; } /* * @see org.eclipse.debug.core.model.IValueModification#verifyValue(org.eclipse.debug.core.model.IValue) */ public boolean verifyValue(IValue value) throws DebugException { // TODO Auto-generated method stub throwNotImplemented(); return false; } /* * @see com.aptana.js.debug.core.model.IJSVariable#isLocal() */ public boolean isLocal() throws DebugException { return (flags & FLAGS_LOCAL) != 0; } /* * @see com.aptana.js.debug.core.model.IJSVariable#isException() */ public boolean isException() throws DebugException { return (flags & FLAGS_EXCEPTION) != 0; } /* * @see com.aptana.js.debug.core.model.IJSVariable#isArgument() */ public boolean isArgument() throws DebugException { return (flags & FLAGS_ARGUMENT) != 0; } /* * @see com.aptana.js.debug.core.model.IJSVariable#isConst() */ public boolean isConst() throws DebugException { return (flags & FLAGS_CONST) != 0; } /* * @see com.aptana.js.debug.core.model.IJSVariable#isTopLevel() */ public boolean isTopLevel() throws DebugException { return (flags & FLAGS_TOPLEVEL) != 0; } /* * @see com.aptana.js.debug.core.model.IJSVariable#getFullName() */ public String getFullName() { String fullname = getQualifier(); int index = fullname.indexOf('.'); if (index >= 0) { fullname = fullname.substring(index + 1); } return fullname; } /* package */String getQualifier() { return qualifier; } /* package */String getThreadId() { return threadId; } }
{ "pile_set_name": "Github" }
# Copyright 2019 Google LLC # # 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. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.AdMob.V1.Model.DateRange do @moduledoc """ Specification of a single date range. Both dates are inclusive. ## Attributes * `endDate` (*type:* `GoogleApi.AdMob.V1.Model.Date.t`, *default:* `nil`) - End date of the date range, inclusive. Must be greater than or equal to the start date. * `startDate` (*type:* `GoogleApi.AdMob.V1.Model.Date.t`, *default:* `nil`) - Start date of the date range, inclusive. Must be less than or equal to the end date. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :endDate => GoogleApi.AdMob.V1.Model.Date.t(), :startDate => GoogleApi.AdMob.V1.Model.Date.t() } field(:endDate, as: GoogleApi.AdMob.V1.Model.Date) field(:startDate, as: GoogleApi.AdMob.V1.Model.Date) end defimpl Poison.Decoder, for: GoogleApi.AdMob.V1.Model.DateRange do def decode(value, options) do GoogleApi.AdMob.V1.Model.DateRange.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.AdMob.V1.Model.DateRange do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
{ "pile_set_name": "Github" }
*develop.txt* For Vim バヌゞョン 8.2. Last change: 2020 Jul 27 VIMリファレンスマニュアル by Bram Moolenaar Vimの開発 *development* この文曞は、Vimの曎なる開発に参加しようずいう人にずっお重芁である。 1. 蚭蚈䞊の目暙 |design-goals| 2. コヌディングスタむル |coding-style| 3. 決定事項 |design-decisions| 4. 想定しおいるこず |design-assumptions| ゜ヌスコヌドの抂芁に぀いおは "src" ディレクトリのREADME.txtを芋おください。 Vimはオヌプン゜ヌス゜フトりェアです。誰でもVimの開発に協力できたす。パッチを送 る時はなるべく "unified diff" 圢匏 ("diff -u" で䜜る) でお願いしたす。 GitHub䞊でプルリク゚ストを䜜るこずも可胜ですが、必須ではありたせん。 http://vim.wikia.com/wiki/How_to_make_and_submit_a_patch も芋おください。 ============================================================================== 1. 蚭蚈䞊の目暙 *design-goals* 重芁床の順に埓っお曞かれおいる(倧雑把であるが)。 かなりの項目が矛盟しおいるこずを泚意しおおく。これは故意である。それらの間で、 バランスを取っおいかねばならない。 VIM IS... VI COMPATIBLE *design-compatible* 䜕より、VimはViの気軜な眮き換えずしお䜿うこずができるべきである。ナヌザヌが望 むなら、Vimは、オリゞナルのViずの区別がほずんど付かない互換モヌドで䜿うこずが できる。 䟋倖: - 明癜なViのバグをVimに再珟しない。 - Viには異なるバヌゞョンが存圚する。私はバヌゞョン3.7(6/7/85)を参考ずしお 䜿っおいる。しかし、他のバヌゞョンのサポヌトも可胜な限り取り蟌たれる。 POSIXにおけるViのパヌトは、決定的な資料ずは考えない。 - Vimは新しいコマンドを持぀ため、Viにないコマンドを入力しおも機胜しおしたう 堎合がある。 - VimはViの持っおいない倚くの特城を持぀。VimからViぞ戻るこずは問題を匕き起こ すが、これは避けられないこずである。 - いく぀かの事柄はめったに䜿われた䟋がない(オヌプンモヌド、クラッシュ時の e-mailの送信、など)。これらは、誰かが䜕らかの理由でそれを入れるべきだず考 え、さらにその機胜が働き過ぎない堎合に限っお取り入れられる。 - いく぀かの項目に関しおは、Vi互換を保぀べきかどうか、議論の䜙地がある。これ らに関しおは、オプションフラグが䜜られるだろう。 VIM IS... IMPROVED *design-improved* Vimの改良点は、それをよりよいViにすべきであっお、たったく違った゚ディタに しおしたっおはならない。拡匵は "Viの粟神" に埓っお行われる。 - 可胜な限りキヌボヌドを䜿う。マりスは私たちの持たぬ第の手を必芁ずする。 倚くの端末はマりスを備えおいない。 - それでもマりスを䜿うようであれば、キヌボヌドに切り替える必芁をなくす。 マりスずキヌボヌドの操䜜の混圚を避けよ。 - コマンドずオプションを矛盟なく远加せよ。でなければ、それらを芋぀け出し、思い 出すのに、人々は苊劎を匷いられるだろう。埌々、さらにコマンドやオプションが 远加されるこずを忘れおはならない。 - 特性は、人々が知らなければ圹に立たない。目立たない特性は远加しない、あるいは、 少なくずもその特性が存圚するずいうヒントをドキュメントに远加するこず。 - CTRLや他の修食子の䜿甚は最小限に留めよ、これらはタむプしにくい。 - 倚くの初心者、䞍慣れなVimナヌザヌがいる。Vimを䜿いはじめるこず、そしおより倚 くを孊んでいくこずが、簡単にできるようにせよ。 - 特性は限りなく远加できる。新しく远加される特性は、(1)ナヌザヌが求めおいるこ ず、(2)実装にどれほどの劎力が必芁か、そしお(3)誰かが実際に実装しおいる、ず いったこずに基づいお遞択される。 VIM IS... MULTI PLATFORM *design-multi-platform* Vimは、可胜な限り、倚くのプラットフォヌム䞊の倚くのナヌザヌの助けでありたい。 - 倚くの皮類の端末をサポヌトする。最䜎限の芁求は、カヌ゜ルの配眮機胜ず画面の クリアである。コマンドはたいおいのキヌボヌドが持぀キヌのみを䜿う。マッピン グには、キヌボヌド䞊の党おのキヌを䜿うこずができる。 - 倚くのプラットフォヌムをサポヌトする。必芁条件は、誰かがそのプラットフォヌム 䞊でVimの開発をしたいず考えるこず、それによっおコヌドに混乱をきたさないこず、 である。 - 倚くのコンパむラずラむブラリをサポヌトする。党おの人が、他のコンパむラや GUIラむブラリをむンストヌルできるわけではないからである。 - 人々は、あるプラットフォヌムから別のプラットフォヌムぞ、そしおGUIから端末 バヌゞョンぞ移行する。特性は党おのバヌゞョン、あるいは、少なくずも理に叶った 劎力でできる限りのバヌゞョンで、提䟛されるべきである。ナヌザヌが胜率的に仕事 を仕䞊げるために、プラットフォヌムを切り替えねばならないような事態は避けたい。 - いく぀かのプラットフォヌムでは実珟できない、たたは、ただひず぀のプラット フォヌムでしか実珟できないような特性も、実装できないずいうわけではない。[こ れは前項ず故意に矛盟するものであり、䞡者の間でバランスが取られる。] VIM IS... WELL DOCUMENTED *design-documented* - 文曞化されおいない特性は、圹に立たない。新しい特性を含んだパッチには、必ず ドキュメントが含たれおいるべきである。 - ドキュメントは、わかりやすく、理解できるものであるべきだ。䟋を䜿うこずが掚 奚される。 - 文章を䞍必芁に長くしおはならない。短い文章は、その項目を芋぀けやすくする。 VIM IS... HIGH SPEED AND SMALL IN SIZE *design-speed-size* Vimを䜿うこずで、システムリ゜ヌスに倧打撃を䞎えおはならない。Vimを小さく、 速く保぀こず。 - コンピュヌタは幎毎により速く、倧容量になっおいる。Vimも成長しうるが、コン ピュヌタの成長速床より速くなっおはならない。Vimを叀いシステム䞊でも䜿える よう保぀必芁がある。 - 倚くのナヌザヌは、Vimを頻繁にシェルから立ち䞊げる。起動は短時間でなくおはな らない。 - コマンドは胜率的に働く必芁がある。コマンドが消費する時間は、可胜な限り短く あるべきだ。圹に立぀コマンドなら、倚少時間がかかっおもよい。 - Vimを、遅い接続を通しお䜿う人がいるこずを忘れおはならない。通信にかかるオヌ バヌヘッドは最小にするこず。 - サむズがかなり倧きく、倚くの人によっお䜿われるわけではない項目は、無効化で きる特性ずすべきである。 - Vimは、他のいろいろな構成芁玠の䞭にある、ひず぀のコンポヌネントである。巚倧 なアプリケヌションに倉えおはならない、むしろ他のプログラムずよく協調するよう にせよ。 VIM IS... MAINTAINABLE *design-maintain* - ゜ヌスコヌドは乱雑になっおはならない。そしお、信頌できるものでなくおはな らない。 - 読みやすくするため、すべおのファむルで同じレむアりトを取るこず |coding-style|。 - 圹に立぀コメントをいれるこず関数名ず匕数名を匕甚しおも圹に立たない。それ が䜕のためにあるのか説明するこず。 - プラットフォヌム独立のコヌドに倚くの倉曎を加える必芁をなくし、他のプラット フォヌムぞの移怍を簡単にできるようにするこず。 - オブゞェクト指向の粟神を䜿う: デヌタずコヌドを同じ堎所に。コヌドの他の郚分 に関する知識は最小で枈むように。 VIM IS... FLEXIBLE *design-flexible* Vimは、そのナヌザヌに特定の䜜業パタヌンを匷いるよりは、ナヌザヌの奜むスタむル での䜜業を支揎すべきである。これは倧きなむンパクトをも぀項目(䟋えば、 'compatible' オプション)や、その他の詳现によっお実珟される。デフォルトは、倚く のナヌザヌがそのたたのVimを楜しんで䜿えるように、慎重に遞ばれおいる。コマンド ずオプションは、Vimをナヌザヌの垌望ず環境に調敎するために䜿われる。 VIM IS... NOT *design-not* - Vim はシェルでもオペレヌティングシステムでもない。Vim はタヌミナルりィンドり を提䟛し、その䞭でシェルやデバッガを走らせるこずができる。䟋えば、ssh 接続越 しにこれをするこずが可胜だ。しかし、このようなものにテキスト゚ディタが必芁な いなら守備範囲倖だ (代わりに screen や tmux のようなものを䜿おう)。 颚刺を蟌めお曰く: "Vim は Emacs のように流し台以倖ならなんでもかんでも取り蟌 んでしたうようなこずはしないが、Vim で流し台を掗うこずはできるぞ。 ;-)" Vim ず gdb を連携させる方法に぀いおは |terminal-debugger| を参照。他の(叀い) ツヌルは http://www.agide.org ず http://clewn.sf.net で芋぀けるこずができる。 - Vimは、党おのプラットフォヌムに枡っお調和を欠くずいう代償を払っお、芋栄えを よくしようずする装食的なGUI゚ディタではない。しかし、機胜的なGUI特性は歓迎さ れる。 ============================================================================== 2. コヌディングスタむル *coding-style* Vimの゜ヌスコヌドに倉曎を加える際、守るべきルヌルがある。゜ヌスを読めるもの、 保守できるものずしお保぀ため、これらのルヌルに埓っお欲しい。 このリストは完党ではない。より倚くの䟋は、゜ヌスコヌドを芋お欲しい。 MAKING CHANGES *style-changes* コヌドに倉曎を加える基本的なステップは: 1. GitHub からコヌドを取埗する。これによりあなたが倉曎したコヌドをメむンのコヌ ドベヌスに同期するのがより簡単になる (あなたの倉曎がメむンのコヌドベヌスに 含たれるようになるたで少しかかるかもしれない) 。いくらか時間を費やしお git に぀いお孊ぶ必芁がある。git はあたりナヌザヌフレンドリヌなツヌルではない。 2. ドキュメントを調敎する。最初にこれをやるこずで、あなたの行う倉曎がナヌザヌ に䞎える圱響に぀いお、おおたかな印象をも぀こずができる。 3. ゜ヌスコヌドに倉曎を加える。 4. 倉曎がリストされた項目に圱響を䞎えおいないか、../doc/todo.txtをチェックす る。 5. "git diff" でパッチを䜜成する。GitHub でプルリク゚ストを䜜成しおも良いが、 重芁なのはその diff である。 6. 䜕が倉曎されたかのノヌトを䜜成する。問題点ずその解決策に぀いお曞かれおいる のが望たしい。|vim-dev| のメヌリングリストに説明ず diff を含めたメヌルを送 るか GitHub でプルリク゚ストを䜜成する。 C COMPILER *style-compiler* *ANSI-C* *C89* *C99* サポヌトされおいる最小の C コンパむラのバヌゞョンは C89 (ANSI C ずも呌ばれおい る) である。C99 のような埌継の暙準芏栌はあたり普及しおいない、もしくは少なくず も 100% サポヌトされおいるわけではない。したがっお C99 のいく぀かの機胜だけを 䜿甚し、その他の䜿甚は (少なくずも珟時点では) 犁止する。 珟存するパッチに察しおマヌゞの問題を匕き起こすため、C99の機胜を䜿う倉曎を至る 所に入れおはいけない。新しくコヌドを曞く堎合、もしくは既存のコヌドを曞き盎す堎 合に限り䜿甚しおもよい。 コメント ~ 慣習的に Vim では /* コメント */ を䜿甚する。ファむルや関数のヘッダ、コヌドの 倧きめなブロックに関しおはこれを維持する぀もりである。䟋: /* * The "foo" argument does something useful. * Return OK or FAIL. */ 新しいコヌドもしくは倉曎するコヌドの行に぀いおは、// コメント を䜿うこずが奜た れる。特にコヌドの埌ろに続くコメントなど: int some_var; // single line comment useful here 列挙型 (Enums) ~ 列挙型の末尟の芁玠にコンマ (trailing comma) が付いおいおもよい。C89 では認めら れおいなかった。 型 (Types) ~ "long long" は䜿甚しおもよく、64 bit を想定しおいる。printf では %lld を䜿甚す るこず。同じように "long long unsigned" では %llu を䜿甚する。 䜿甚しおはいけないもの ~ これらの C99 の機胜は、コンパむラのサポヌトが䞍十分なため䜿甚しおはいけない。 - ステヌトメントの埌の宣蚀 (MSVC 2012 はこれをサポヌトしおいない)。すべおの宣 蚀はブロックの先頭になければならない。 - 可倉長配列 (C11 でもこれはオプショナルな機胜である)。 - _Bool 型ず _Complex 型。 - "inline" (ほずんど必芁ない、コンパむラに最適化させよう。) - フレキシブル配列メンバ: HP-UX C コンパむラはサポヌトしおいない。(John Marriott) USE OF COMMON FUNCTIONS *style-functions* よく䜿われる関数のうち、特別なVimバヌゞョンを持぀ものがある。これらは理由あっ お導入されたものなので、垞にVimバヌゞョンを䜿うように意識するこず。 NORMAL NAME VIM NAME DIFFERENCE OF VIM VERSION free() vim_free() NULLの解攟をチェックする malloc() alloc() アりトオブメモリの状況をチェックする malloc() lalloc() alloc()に䌌おいるが、long型の匕数を持぀ strcpy() STRCPY() char_u *匕数を、(char *)ぞキャストする strchr() vim_strchr() スペシャルキャラクタを受け入れる strrchr() vim_strrchr() スペシャルキャラクタを受け入れる isspace() vim_isspace() 128以䞊のキャラクタを扱うこずができる iswhite() vim_iswhite() Tabずスペヌスに察しおのみTRUE memcpy() mch_memmove() オヌバヌラップしたコピヌを扱う bcopy() mch_memmove() オヌバヌラップしたコピヌを扱う memset() vim_memset() 党おのシステムで䞀定である NAMES *style-names* 関数の名前に31文字より長い名前は䜿えない。(VMSのために) "delete" や "this" ずいう名前の倉数を䜿わないこず。C++で問題ずなる。 Vimができる限り倚くのシステム䞊で走るずいう必芁䞊、システムによっおすでに定矩 されおいる名前を䜿うこずは避けねばならない。これは、問題ずなるこずが知られお いる名前のリストである。名前はregexpパタヌンずしお䞎えられおいる。 is.*() POSIX, ctype.h to.*() POSIX, ctype.h d_.* POSIX, dirent.h l_.* POSIX, fcntl.h gr_.* POSIX, grp.h pw_.* POSIX, pwd.h sa_.* POSIX, signal.h mem.* POSIX, string.h str.* POSIX, string.h wcs.* POSIX, string.h st_.* POSIX, stat.h tms_.* POSIX, times.h tm_.* POSIX, time.h c_.* POSIX, termios.h MAX.* POSIX, limits.h __.* POSIX, system _[A-Z].* POSIX, system E[A-Z0-9]* POSIX, errno.h .*_t POSIX, for typedefs, *_T を䜿うこず。 wait types.hずコンフリクトするため、関数の匕数ずしお䜿わない index グロヌバル宣蚀を芆い隠す time グロヌバル宣蚀を芆い隠す new C++の予玄語 clear Mac curses.h echo Mac curses.h instr Mac curses.h meta Mac curses.h newwin Mac curses.h nl Mac curses.h overwrite Mac curses.h refresh Mac curses.h scroll Mac curses.h typeahead Mac curses.h basename() GNU 文字列関数(GNU string function) dirname() GNU 文字列関数(GNU string function) get_env_value() Linux システム関数 VARIOUS *style-various* 型の定矩に䜿う名前は最埌を "_T" にする: > typedef int some_T; マクロ定矩はすべお倧文字にする: > #define SOME_THING 機胜に関する定矩は "FEAT_" で始める: > #define FEAT_FOO '\"' を䜿わない、あるコンパむラはこれを扱えない。'"' はうたく機胜する。 次を䜿っおはならない: #if HAVE_SOME あるコンパむラはこれを扱えず、"HAVE_SOME" が定矩されおいないず蚎える。 次を䜿う #ifdef HAVE_SOME たたは #if defined(HAVE_SOME) STYLE *style-examples* 䞀般的なルヌル: 行に぀のステヌトメント。 間違い: if (cond) a = 1; OK: if (cond) a = 1; 間違い: while (cond); OK: while (cond) ; 間違い: do a = 1; while (cond); OK: do a = 1; while (cond); 間違い: if (cond) { cmd; cmd; } else { cmd; cmd; } OK: if (cond) { cmd; cmd; } else { cmd; cmd; } ブロックが1行の堎合は、波括匧を省くこずができる。if/else の1぀のブロックに波括 匧がある堎合、他のブロックにも波括匧があるず、通垞は芋栄えが良くなる: OK: if (cond) cmd; else cmd; OK: if (cond) { cmd; } else { cmd; cmd; } 関数宣蚀には ANSI スタむルを䜿い、戻り倀の型は独立した行にむンデントを぀けお曞 くこず。 間違い: int function_name(int arg1, int arg2) OK: /* * Explanation of what this function is used for. * この関数が䜕に䜿われるかの説明。 * * Return value explanation. * 戻り倀の説明。 */ int function_name( int arg1, // short comment about arg1 int arg2) // short comment about arg2 { int local; // comment about local local = arg1 * arg2; SPACES AND PUNCTUATION *style-spaces* 関数名ずブラケットの間にスペヌスを入れないこず: 間違い: func (arg); OK: func(arg); if、while、switchなどの埌には、スペヌスを入れるこず。 間違い: if(arg) for(;;) OK: if (arg) for (;;) コンマ、セミコロンの埌にはスペヌスを入れるこず: 間違い: func(arg1,arg2); for (i = 0;i < 2;++i) OK: func(arg1, arg2); for (i = 0; i < 2; ++i) '='、'+'、'/' などの前ず埌には、スペヌスを入れるこず。 間違い: var=a*5; OK: var = a * 5; 䞀般的なこず: コヌドの行をグルヌプ分けするために、空行を䜿う。行グルヌプのす ぐ䞊にコメントを入れる。こうするこずによっお、䜕が行われるのかをより簡単に知 るこずができる。 OK: /* Prepare for building the table. */ /* テヌブルの䜜成の準備 */ get_first_item(); table_idx = 0; /* Build the table */ /* テヌブルの䜜成 */ while (has_item()) table[table_idx++] = next_item(); /* Finish up. */ /* 仕䞊げ */ cleanup_items(); generate_hash(table); ============================================================================== 3. 決定事項 *design-decisions* 折畳(folding) 同じバッファにいく぀もの折畳状態を蚭定可胜にする。䟋えば、あるりィンドりに関数 を折畳んだ状態で衚瀺し、他のりィンドりで関数の䞭身を衚瀺するなど。 折畳はテキストを衚瀺する方法である。テキストを倉曎すべきではない。したがっお バッファ内のテキストをりィンドりに衚瀺する際のフィルタずしお実行される。 りィンドりの名前 "りィンドり" ずいう単語は䞀般にいく぀かの意味で䜿われおいる。スクリヌン䞊のりィ ンドり、xtermのりィンドり、Vimのバッファを衚瀺するりィンドりなど。 混乱を避けるため、時にりィンドりず呌ばれる他の物には別の名前が付けられおいる。 ここに関連する物の抂芳を瀺す。 スクリヌン(screen) ディスプレむ党䜓。GUIでは䟋えば1024x768ピクセルの画 面。Vimシェルはスクリヌン党䜓を䜿うこずも䞀郚を䜿う こずもできる。 シェル(shell) Vimアプリケヌション。スクリヌン党䜓(䟋えばコン゜ヌル で実行した時)、あるいはその䞀郚(xtermやGUI)。 りィンドり(window) バッファの衚瀺画面。Vimは耇数のりィンドりを持぀こず ができる。りィンドりはコマンドラむンやメニュヌバヌ、 ツヌルバヌなどずいっしょに衚瀺される。これらはシェル に玍たる。 スペルチェック *develop-spell* Vim にスペルチェックを远加するこずになったずき、利甚可胜なスペルチェックのラむ ブラリやプログラムに぀いお調査が行われた。その結果は残念なこずに、Vim 内でスペ ルチェック゚ンゞンずしお䜿えるものはないずわかった。これには様々な理由がある: - マルチバむト゚ンコヌディングをサポヌトしおいない。1぀のファむル内で耇数の蚀 語を䜿えるようにするために、少なくずも UTF-8 はサポヌトしおいなければならな い。 オンザフラむな倉換は垞に可胜ずは限らない(iconv に察応しおいる必芁がある)。 - プログラムずラむブラリに察しお: それらをそのたた(as-is)䜿うには、Vim ず別個 にむンストヌルしなければならない。これはたいおい䞍可胜ではないが、難点である。 - パフォヌマンス: いく぀かのテストによるず、スペルチェックを構文匷調のようにオ ンザフラむで(再描画䞭に)行うこずは可胜であった。しかし他のコヌドで䜿われたメ カニズムはもっず遅かった。䟋えば、Myspell はハッシュテヌブルを䜿甚する。ほず んどのスペルチェッカが䜿甚しおいる接蟞圧瞮を䜿うず遅くなった。 - aspell のような倖郚プログラムを䜿うには、通信メカニズムを甚意しなければなら ない。これをポヌタブルな方法で行うのは耇雑過ぎる(Unix だけなら比范的簡単だが、 それでは十分ではない)。そしおパフォヌマンスが問題になる(䜕回ものプロセス切替 が行われる)。 - "Etten-Leur" や "et al." など、単語でない単語のサポヌトを欠いおいる。そのた めこれらの郚分を OK ずマヌクしなければならないが、そうするず信頌性が䜎䞋する。 - 地域や方蚀のサポヌトを欠いおいる。英語の単語をすべお受け付け、カナダ語でない 単語を別に扱うこずが難しくなる。 - 頻床が䜎い単語のサポヌトを欠いおいる。正しいがめったに䜿われないたくさんの単 語が、よく䜿われる単語のスペルミスずみなされおしたう。 - スペル候補を䜜成するには速床はそれほど重芁ではなく、他のプログラムやラむブラ リをむンストヌルするこずは蚱容できる。しかし、単語リストが異なるずスペル候補 が誀単語になっおしたう。 スペル候補 *develop-spell-suggestions* 候補の䜜成には2぀の基本的なメカニズムがある: 1. 誀った単語を少し倉曎しお正しい単語ずマッチするかチェックする。あるいは、正 しい単語党おに察し、それを少し倉曎しお誀った単語ずマッチするかチェックする。 倉曎ずは、文字の削陀・文字の挿入・2぀の文字の亀換などである。 2. 誀った単語ず正しい単語のリストの䞡方に soundfolding (発音が近い単語を同じグ ルヌプずみなすこず) を行っお、そこでマッチを芋぀ける。1番目のメカニズムず同 様にいく぀か倉曎をしおもよい。 最初のメカニズムはタむプミスを芋぀けるのにはよい。ハッシュテヌブルの実隓ず、他 のスペルチェッカの゜リュヌションを芋るず、これにはtrie(ツリヌ構造の䞀皮)が最適 であるずの結論になった。メモリ䜿甚量の削枛ず、賢い倉曎を詊みるずいうこずの䞡方 の面でである。䟋えば、文字を挿入するずきは正しい単語に぀ながる文字だけを詊せば よい。他の(ハッシュテヌブルを䜿った)メカニズムは、単語のすべおの䜍眮で、ありう るすべおの文字を詊さねばならない、たた、ハッシュテヌブルを䜿うには、単語の境界 が個別に認識されなければならないのに察し、trie はそれを芁求しない。そのためメ カニズムがより単玔になる。 ある単語の発音は知っおいるがスペルを知らないずいう堎合に soundfolding は有甚で ある。䟋えば、"dictionary" ずいう単語を "daktonerie" ず曞いおしたうかもしれな い。これを最初の方法で蚂正しようずするず倉曎回数が非垞に倚くなっおしたい、正し いスペルを芋぀けるのは困難である。それに察し、これらの単語にsoundfoldingを行う ず "tktnr" ず "tkxnry" になり、2文字しか違わない。 soundfoldの同倀(音が䌌おいる単語)により単語を芋぀けるには党おのsoundfolded wordsのリストが必芁である。どれが最良の方法かを探すための実隓が行われた。案: 1. 修正候補を探すずきに、その堎でsound foldingを行う。぀たり、正しい単語のtrie をたどりながら、各単語をsoundfoldingし、それがスペルミスしおいる単語からど れだけ異なるかをチェックする。これはメモリ効率の面でずおも優れおいるが、時 間は長くかかる。英語の堎合、高速なPCで2秒ほどかかる。これは察話的な利甚ずし お受け入れられる。しかしいく぀かの蚀語(ドむツ語、カタルニャ語など)に察しお は10秒以䞊かかり、受け入れがたい。バッチ凊理(自動蚂正)に䜿うには党おの蚀語 で遅すぎる。 2. soundfoldされた単語に察しおtrieを䜿い、soundfoldingなしのずきずたったく同じ ように怜玢できるようにする。そのためには、soundfoldされた各単語に察し、正し い単語のリストを蚘憶しおおく必芁がある。そうするず照合がずおも高速になるが、 1MB〜10MBのオヌダヌの倧量のメモリを必芁ずする。ある蚀語の堎合は元の単語のリ ストよりも倚くなる。 3. 2番目の案ず同様だが、接蟞圧瞮を䜿い、soundfoldした基本単語だけを保存するこ ずによりメモリ消費量を枛らす。これはAspellが採甚しおいる方法である。䞍利点 は、誀った単語をsoundfoldする前に接蟞を取り陀いおおかねばならないこずである。 そのため、単語の先頭・末尟における誀りに察しおは察応できない。たた、誀った 単語が正しい単語から倧きく異なるずきは遅くなる。 我々が採甚したのは、2番目のメカニズムを䜿い、別ファむルを䜿う方法である。こう するこずによっお、十分なメモリを持っおいるナヌザヌはずおもよい候補を埗るこずが できるし、メモリが䞍足しおいるナヌザヌやスペルチェックだけで候補は出さなくおよ いずいうナヌザヌはそれほどメモリを䜿わなくおすむ。 単語の頻床 候補を゜ヌトするにはどの単語が共通であるかを知るず圹に立぀。理論的には単語の頻 床は単語ずずもに蟞曞の䞭に保持するこずができる。しかしそうするず単語に぀き回数 を保持しなければならない。これは単語ツリヌ圧瞮を倧いに劣化させる。たた、党おの 蚀語に察しお単語の頻床を保守するのは倧倉な䜜業である。 たた、テキストに既に出おきおいる単語を優先するずよいだろう。このようにしお特定 のテキスト内に衚れる単語は候補の䞭で優先床が高くなる。 実装されたのは、衚瀺䞭に単語を数えるこずである。ハッシュテヌブルを䜿っおその単 語の回数を高速に怜玢する。回数は接蟞ファむルでCOMMONアむテムにリストされおいる 単語から初期化される。そのため新芏ファむルの線集を始めたずきも機胜する。 これは理想的ではない。Vimが長時間皌動しおいるほど回数は倧きくなるためである。 しかし実甚的には単語の回数を䜿わない堎合に比べお泚目に倀するほどの改善である。 ============================================================================== 4. 想定しおいるこず *design-assumptions* 倉数のサむズ: char 8 bit signed char_u 8 bit unsigned int 32 or 64 bit signed (限定された機胜に぀いおは16ビットもありうる) unsigned 32 or 64 bit unsigned (16ビットに぀いおはintず同様) long 32 or 64 bit signed, can hold a pointer Note いく぀かのコンパむラは長すぎる行は文字列をうたく扱えない。C89の暙準芏栌で は509文字たでに制限されおいる。 vim:tw=78:ts=8:noet:ft=help:norl:
{ "pile_set_name": "Github" }
/*===---- tmmintrin.h - SSSE3 intrinsics -----------------------------------=== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * *===-----------------------------------------------------------------------=== */ #ifndef __TMMINTRIN_H #define __TMMINTRIN_H #ifndef __SSSE3__ #error "SSSE3 instruction set not enabled" #else #include <pmmintrin.h> static __inline__ __m64 __attribute__((__always_inline__, __nodebug__)) _mm_abs_pi8(__m64 __a) { return (__m64)__builtin_ia32_pabsb((__v8qi)__a); } static __inline__ __m128i __attribute__((__always_inline__, __nodebug__)) _mm_abs_epi8(__m128i __a) { return (__m128i)__builtin_ia32_pabsb128((__v16qi)__a); } static __inline__ __m64 __attribute__((__always_inline__, __nodebug__)) _mm_abs_pi16(__m64 __a) { return (__m64)__builtin_ia32_pabsw((__v4hi)__a); } static __inline__ __m128i __attribute__((__always_inline__, __nodebug__)) _mm_abs_epi16(__m128i __a) { return (__m128i)__builtin_ia32_pabsw128((__v8hi)__a); } static __inline__ __m64 __attribute__((__always_inline__, __nodebug__)) _mm_abs_pi32(__m64 __a) { return (__m64)__builtin_ia32_pabsd((__v2si)__a); } static __inline__ __m128i __attribute__((__always_inline__, __nodebug__)) _mm_abs_epi32(__m128i __a) { return (__m128i)__builtin_ia32_pabsd128((__v4si)__a); } #define _mm_alignr_epi8(a, b, n) __extension__ ({ \ __m128i __a = (a); \ __m128i __b = (b); \ (__m128i)__builtin_ia32_palignr128((__v16qi)__a, (__v16qi)__b, (n)); }) #define _mm_alignr_pi8(a, b, n) __extension__ ({ \ __m64 __a = (a); \ __m64 __b = (b); \ (__m64)__builtin_ia32_palignr((__v8qi)__a, (__v8qi)__b, (n)); }) static __inline__ __m128i __attribute__((__always_inline__, __nodebug__)) _mm_hadd_epi16(__m128i __a, __m128i __b) { return (__m128i)__builtin_ia32_phaddw128((__v8hi)__a, (__v8hi)__b); } static __inline__ __m128i __attribute__((__always_inline__, __nodebug__)) _mm_hadd_epi32(__m128i __a, __m128i __b) { return (__m128i)__builtin_ia32_phaddd128((__v4si)__a, (__v4si)__b); } static __inline__ __m64 __attribute__((__always_inline__, __nodebug__)) _mm_hadd_pi16(__m64 __a, __m64 __b) { return (__m64)__builtin_ia32_phaddw((__v4hi)__a, (__v4hi)__b); } static __inline__ __m64 __attribute__((__always_inline__, __nodebug__)) _mm_hadd_pi32(__m64 __a, __m64 __b) { return (__m64)__builtin_ia32_phaddd((__v2si)__a, (__v2si)__b); } static __inline__ __m128i __attribute__((__always_inline__, __nodebug__)) _mm_hadds_epi16(__m128i __a, __m128i __b) { return (__m128i)__builtin_ia32_phaddsw128((__v8hi)__a, (__v8hi)__b); } static __inline__ __m64 __attribute__((__always_inline__, __nodebug__)) _mm_hadds_pi16(__m64 __a, __m64 __b) { return (__m64)__builtin_ia32_phaddsw((__v4hi)__a, (__v4hi)__b); } static __inline__ __m128i __attribute__((__always_inline__, __nodebug__)) _mm_hsub_epi16(__m128i __a, __m128i __b) { return (__m128i)__builtin_ia32_phsubw128((__v8hi)__a, (__v8hi)__b); } static __inline__ __m128i __attribute__((__always_inline__, __nodebug__)) _mm_hsub_epi32(__m128i __a, __m128i __b) { return (__m128i)__builtin_ia32_phsubd128((__v4si)__a, (__v4si)__b); } static __inline__ __m64 __attribute__((__always_inline__, __nodebug__)) _mm_hsub_pi16(__m64 __a, __m64 __b) { return (__m64)__builtin_ia32_phsubw((__v4hi)__a, (__v4hi)__b); } static __inline__ __m64 __attribute__((__always_inline__, __nodebug__)) _mm_hsub_pi32(__m64 __a, __m64 __b) { return (__m64)__builtin_ia32_phsubd((__v2si)__a, (__v2si)__b); } static __inline__ __m128i __attribute__((__always_inline__, __nodebug__)) _mm_hsubs_epi16(__m128i __a, __m128i __b) { return (__m128i)__builtin_ia32_phsubsw128((__v8hi)__a, (__v8hi)__b); } static __inline__ __m64 __attribute__((__always_inline__, __nodebug__)) _mm_hsubs_pi16(__m64 __a, __m64 __b) { return (__m64)__builtin_ia32_phsubsw((__v4hi)__a, (__v4hi)__b); } static __inline__ __m128i __attribute__((__always_inline__, __nodebug__)) _mm_maddubs_epi16(__m128i __a, __m128i __b) { return (__m128i)__builtin_ia32_pmaddubsw128((__v16qi)__a, (__v16qi)__b); } static __inline__ __m64 __attribute__((__always_inline__, __nodebug__)) _mm_maddubs_pi16(__m64 __a, __m64 __b) { return (__m64)__builtin_ia32_pmaddubsw((__v8qi)__a, (__v8qi)__b); } static __inline__ __m128i __attribute__((__always_inline__, __nodebug__)) _mm_mulhrs_epi16(__m128i __a, __m128i __b) { return (__m128i)__builtin_ia32_pmulhrsw128((__v8hi)__a, (__v8hi)__b); } static __inline__ __m64 __attribute__((__always_inline__, __nodebug__)) _mm_mulhrs_pi16(__m64 __a, __m64 __b) { return (__m64)__builtin_ia32_pmulhrsw((__v4hi)__a, (__v4hi)__b); } static __inline__ __m128i __attribute__((__always_inline__, __nodebug__)) _mm_shuffle_epi8(__m128i __a, __m128i __b) { return (__m128i)__builtin_ia32_pshufb128((__v16qi)__a, (__v16qi)__b); } static __inline__ __m64 __attribute__((__always_inline__, __nodebug__)) _mm_shuffle_pi8(__m64 __a, __m64 __b) { return (__m64)__builtin_ia32_pshufb((__v8qi)__a, (__v8qi)__b); } static __inline__ __m128i __attribute__((__always_inline__, __nodebug__)) _mm_sign_epi8(__m128i __a, __m128i __b) { return (__m128i)__builtin_ia32_psignb128((__v16qi)__a, (__v16qi)__b); } static __inline__ __m128i __attribute__((__always_inline__, __nodebug__)) _mm_sign_epi16(__m128i __a, __m128i __b) { return (__m128i)__builtin_ia32_psignw128((__v8hi)__a, (__v8hi)__b); } static __inline__ __m128i __attribute__((__always_inline__, __nodebug__)) _mm_sign_epi32(__m128i __a, __m128i __b) { return (__m128i)__builtin_ia32_psignd128((__v4si)__a, (__v4si)__b); } static __inline__ __m64 __attribute__((__always_inline__, __nodebug__)) _mm_sign_pi8(__m64 __a, __m64 __b) { return (__m64)__builtin_ia32_psignb((__v8qi)__a, (__v8qi)__b); } static __inline__ __m64 __attribute__((__always_inline__, __nodebug__)) _mm_sign_pi16(__m64 __a, __m64 __b) { return (__m64)__builtin_ia32_psignw((__v4hi)__a, (__v4hi)__b); } static __inline__ __m64 __attribute__((__always_inline__, __nodebug__)) _mm_sign_pi32(__m64 __a, __m64 __b) { return (__m64)__builtin_ia32_psignd((__v2si)__a, (__v2si)__b); } #endif /* __SSSE3__ */ #endif /* __TMMINTRIN_H */
{ "pile_set_name": "Github" }
<testcase> <info> <keywords> HTTP HTTP GET HTTP CONNECT HTTP proxy HTTP proxy NTLM auth --proxy-anyauth </keywords> </info> # Server-side <reply> <connect> HTTP/1.1 407 Authorization Required to proxy me my dear swsclose Proxy-Authenticate: NTLM Content-Length: 21 Connection: close data to discard </connect> # this is returned first since we get no proxy-auth <connect1001> HTTP/1.1 407 Authorization Required to proxy me my dear Proxy-Authenticate: NTLM TlRMTVNTUAACAAAAAgACADAAAAAGgoEAc51AYVDgyNcAAAAAAAAAAG4AbgAyAAAAQ0MCAAQAQwBDAAEAEgBFAEwASQBTAEEAQgBFAFQASAAEABgAYwBjAC4AaQBjAGUAZABlAHYALgBuAHUAAwAsAGUAbABpAHMAYQBiAGUAdABoAC4AYwBjAC4AaQBjAGUAZABlAHYALgBuAHUAAAAAAA== Content-Length: 28 And you should ignore this data. </connect1001> # This is supposed to be returned when the server gets the second # Authorization: NTLM line passed-in from the client <connect1002> HTTP/1.1 200 Things are fine in proxy land Server: Microsoft-IIS/5.0 Content-Type: text/html; charset=iso-8859-1 </connect1002> # this is returned when we get a GET! <data2> HTTP/1.1 200 OK Date: Thu, 09 Nov 2010 14:49:00 GMT Content-Length: 7 Connection: close Content-Type: text/html Funny-head: yesyes daniel </data2> # then this is returned when we get proxy-auth <data1000> HTTP/1.1 200 OK swsbounce Server: no Nice proxy auth sir! </data1000> <datacheck> HTTP/1.1 407 Authorization Required to proxy me my dear swsclose Proxy-Authenticate: NTLM Content-Length: 21 Connection: close HTTP/1.1 407 Authorization Required to proxy me my dear Proxy-Authenticate: NTLM TlRMTVNTUAACAAAAAgACADAAAAAGgoEAc51AYVDgyNcAAAAAAAAAAG4AbgAyAAAAQ0MCAAQAQwBDAAEAEgBFAEwASQBTAEEAQgBFAFQASAAEABgAYwBjAC4AaQBjAGUAZABlAHYALgBuAHUAAwAsAGUAbABpAHMAYQBiAGUAdABoAC4AYwBjAC4AaQBjAGUAZABlAHYALgBuAHUAAAAAAA== Content-Length: 28 HTTP/1.1 200 Things are fine in proxy land Server: Microsoft-IIS/5.0 Content-Type: text/html; charset=iso-8859-1 HTTP/1.1 200 OK Date: Thu, 09 Nov 2010 14:49:00 GMT Content-Length: 7 Connection: close Content-Type: text/html Funny-head: yesyes daniel </datacheck> </reply> # Client-side <client> <server> http </server> <features> NTLM !SSPI debug </features> <name> HTTP proxy CONNECT with any proxyauth and proxy offers NTLM and close </name> <setenv> # we force our own host name, in order to make the test machine independent CURL_GETHOSTNAME=curlhost # we try to use the LD_PRELOAD hack, if not a debug build LD_PRELOAD=%PWD/libtest/.libs/libhostname.so </setenv> <command> http://test.remote.example.com.1021:%HTTPPORT/path/10210002 --proxy http://%HOSTIP:%HTTPPORT --proxy-user testuser:testpass --proxy-anyauth --proxytunnel </command> <precheck> chkhostname curlhost </precheck> </client> # Verify data after the test has been "shot" <verify> <strip> ^User-Agent: curl/.* </strip> <protocol> CONNECT test.remote.example.com.1021:%HTTPPORT HTTP/1.1 Host: test.remote.example.com.1021:%HTTPPORT Proxy-Connection: Keep-Alive CONNECT test.remote.example.com.1021:%HTTPPORT HTTP/1.1 Host: test.remote.example.com.1021:%HTTPPORT Proxy-Authorization: NTLM TlRMTVNTUAABAAAABoIIAAAAAAAAAAAAAAAAAAAAAAA= Proxy-Connection: Keep-Alive CONNECT test.remote.example.com.1021:%HTTPPORT HTTP/1.1 Host: test.remote.example.com.1021:%HTTPPORT Proxy-Authorization: NTLM TlRMTVNTUAADAAAAGAAYAEAAAACeAJ4AWAAAAAAAAAD2AAAACAAIAPYAAAAIAAgA/gAAAAAAAAAAAAAABoKBAL9LNW5+nkyHZRmyFaL/LJ4xMjM0MjIzNGUCyhgQ9hw6eWAT13EbDa0BAQAAAAAAAACAPtXesZ0BMTIzNDIyMzQAAAAAAgAEAEMAQwABABIARQBMAEkAUwBBAEIARQBUAEgABAAYAGMAYwAuAGkAYwBlAGQAZQB2AC4AbgB1AAMALABlAGwAaQBzAGEAYgBlAHQAaAAuAGMAYwAuAGkAYwBlAGQAZQB2AC4AbgB1AAAAAAAAAAAAdGVzdHVzZXJjdXJsaG9zdA== Proxy-Connection: Keep-Alive GET /path/10210002 HTTP/1.1 User-Agent: curl/7.12.3-CVS (i686-pc-linux-gnu) libcurl/7.12.3-CVS OpenSSL/0.9.6b zlib/1.1.4 Host: test.remote.example.com.1021:%HTTPPORT Accept: */* </protocol> </verify> </testcase>
{ "pile_set_name": "Github" }
{ "type": "create:cutting", "ingredients": [ { "item": "minecraft:stripped_oak_log" } ], "results": [ { "item": "minecraft:oak_planks", "count": 5 } ], "processingTime": 100 }
{ "pile_set_name": "Github" }
sha256:5219c1c6bb166e17905724115d8ac238ff953f017e81c214216ebf024f73e5be
{ "pile_set_name": "Github" }
define( //begin v1.x content { "field-quarter-short-relative+0": "dette kvt.", "field-quarter-short-relative+1": "nÊste kvt.", "field-tue-relative+-1": "sidste tirsdag", "field-year": "år", "field-wed-relative+0": "på onsdag", "field-wed-relative+1": "nÊste onsdag", "field-minute": "minut", "field-month-narrow-relative+-1": "sidste md.", "field-tue-narrow-relative+0": "på ti.", "field-tue-narrow-relative+1": "nÊste ti.", "field-thu-short-relative+0": "på tor.", "field-day-short-relative+-1": "i går", "field-thu-short-relative+1": "nÊste tor.", "field-day-relative+0": "i dag", "field-day-short-relative+-2": "i forgårs", "field-day-relative+1": "i morgen", "field-week-narrow-relative+0": "denne uge", "field-day-relative+2": "i overmorgen", "field-week-narrow-relative+1": "nÊste uge", "field-wed-narrow-relative+-1": "sidste on.", "field-year-narrow": "år", "field-year-narrow-relative+0": "i år", "field-tue-relative+0": "på tirsdag", "field-year-narrow-relative+1": "nÊste år", "field-tue-relative+1": "nÊste tirsdag", "field-second-short": "sek.", "field-week-relative+0": "denne uge", "field-month-relative+0": "denne måned", "field-week-relative+1": "nÊste uge", "field-month-relative+1": "nÊste måned", "field-sun-narrow-relative+0": "på sÞ.", "field-mon-short-relative+0": "på man.", "field-sun-narrow-relative+1": "nÊste sÞ.", "field-mon-short-relative+1": "nÊste man.", "field-second-relative+0": "nu", "field-month-short": "md.", "field-day": "dag", "field-year-relative+-1": "sidste år", "field-sat-short-relative+-1": "sidste lÞr.", "field-hour-relative+0": "i den kommende time", "field-wed-relative+-1": "sidste onsdag", "field-sat-narrow-relative+-1": "sidste lÞ.", "field-second": "sekund", "field-hour-short-relative+0": "denne time", "field-quarter": "kvartal", "field-week-short": "uge", "field-day-narrow-relative+0": "i dag", "field-day-narrow-relative+1": "i morgen", "field-day-narrow-relative+2": "i overmorgen", "field-tue-short-relative+0": "på tir.", "field-tue-short-relative+1": "nÊste tir.", "field-month-short-relative+-1": "sidste md.", "field-mon-relative+-1": "sidste mandag", "field-month": "måned", "field-day-narrow": "dag", "field-minute-short": "min.", "field-dayperiod": "AM/PM", "field-sat-short-relative+0": "på lÞr.", "field-sat-short-relative+1": "nÊste lÞr.", "eraAbbr": [ "Before R.O.C.", "Minguo" ], "field-second-narrow": "s", "field-mon-relative+0": "på mandag", "field-mon-relative+1": "nÊste mandag", "field-day-narrow-relative+-1": "i går", "field-year-short": "år", "field-day-narrow-relative+-2": "i forgårs", "field-quarter-relative+-1": "sidste kvartal", "field-week-narrow-relative+-1": "sidste uge", "field-sat-relative+-1": "sidste lÞrdag", "field-hour": "time", "field-minute-narrow-relative+0": "denne minut", "field-month-relative+-1": "sidste måned", "field-quarter-short": "kvt.", "field-sat-narrow-relative+0": "på lÞ.", "field-fri-relative+0": "på fredag", "field-sat-narrow-relative+1": "nÊste lÞ.", "field-fri-relative+1": "nÊste fredag", "field-month-narrow-relative+0": "denne md.", "field-month-narrow-relative+1": "nÊste md.", "field-sun-short-relative+0": "på sÞn.", "field-sun-short-relative+1": "nÊste sÞn.", "field-week-relative+-1": "sidste uge", "field-quarter-short-relative+-1": "sidste kvt.", "field-minute-short-relative+0": "denne minut", "field-quarter-relative+0": "dette kvartal", "field-minute-relative+0": "i det kommende minut", "field-quarter-relative+1": "nÊste kvartal", "field-wed-short-relative+-1": "sidste ons.", "field-thu-short-relative+-1": "sidste tor.", "field-year-narrow-relative+-1": "sidste år", "field-mon-narrow-relative+-1": "sidste ma.", "field-thu-narrow-relative+-1": "sidste to.", "field-tue-narrow-relative+-1": "sidste ti.", "field-wed-short-relative+0": "på ons.", "field-wed-short-relative+1": "nÊste ons.", "field-sun-relative+-1": "sidste sÞndag", "field-weekday": "ugedag", "field-day-short-relative+0": "i dag", "field-quarter-narrow-relative+0": "dette kvt.", "field-sat-relative+0": "på lÞrdag", "field-day-short-relative+1": "i morgen", "field-quarter-narrow-relative+1": "nÊste kvt.", "field-sat-relative+1": "nÊste lÞrdag", "field-day-short-relative+2": "i overmorgen", "field-week-short-relative+0": "denne uge", "field-week-short-relative+1": "nÊste uge", "field-month-short-relative+0": "denne md.", "field-month-short-relative+1": "nÊste md.", "field-thu-narrow-relative+0": "på to.", "field-thu-narrow-relative+1": "nÊste to.", "field-sun-narrow-relative+-1": "sidste sÞ.", "field-mon-short-relative+-1": "sidste man.", "field-thu-relative+0": "på torsdag", "field-thu-relative+1": "nÊste torsdag", "field-fri-short-relative+-1": "sidste fre.", "field-thu-relative+-1": "sidste torsdag", "field-week": "uge", "field-wed-narrow-relative+0": "på on.", "field-wed-narrow-relative+1": "nÊste on.", "field-quarter-narrow-relative+-1": "sidste kvt.", "field-year-short-relative+0": "i år", "field-year-short-relative+1": "nÊste år", "field-fri-short-relative+0": "på fre.", "field-fri-short-relative+1": "nÊste fre.", "field-week-short-relative+-1": "sidste uge", "field-hour-narrow-relative+0": "denne time", "field-hour-short": "t.", "field-month-narrow": "md.", "field-hour-narrow": "t", "field-fri-narrow-relative+-1": "sidste fr.", "field-year-relative+0": "i år", "field-year-relative+1": "nÊste år", "field-fri-relative+-1": "sidste fredag", "field-tue-short-relative+-1": "sidste tir.", "field-minute-narrow": "min", "field-mon-narrow-relative+0": "på ma.", "field-mon-narrow-relative+1": "nÊste ma.", "field-year-short-relative+-1": "sidste år", "field-zone": "tidszone", "field-quarter-narrow": "kvt.", "field-sun-short-relative+-1": "sidste sÞn.", "field-day-relative+-1": "i går", "field-day-relative+-2": "i forgårs", "field-sun-relative+0": "på sÞndag", "field-sun-relative+1": "nÊste sÞndag", "field-day-short": "dag", "field-week-narrow": "uge", "field-era": "Êra", "field-fri-narrow-relative+0": "på fr.", "field-fri-narrow-relative+1": "nÊste fr." } //end v1.x content );
{ "pile_set_name": "Github" }
# # Copyright 2014-2016 See AUTHORS file. # # 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. # #ButtonBar I18N file #Since 1.0.0 left=Left right=Right help=Help no=No yes=Yes cancel=Cancel back=Back next=Next apply=Apply finish=Finish ok=Ok done=Done
{ "pile_set_name": "Github" }
--- title: Slate github: 'https://github.com/gesquive/slate' demo: 'https://gesquive.github.io/hugo-slate-demo/' author: Gus Esquivel ssg: - Hugo cms: - No Cms date: 2017-05-18T22:56:52.000Z github_branch: master description: a single-page speed-dial theme for Hugo stale: true ---
{ "pile_set_name": "Github" }
package stringprep var mapNonASCIISpaceToASCIISpace = Mapping{ 0x00A0: []rune{0x0020}, 0x1680: []rune{0x0020}, 0x2000: []rune{0x0020}, 0x2001: []rune{0x0020}, 0x2002: []rune{0x0020}, 0x2003: []rune{0x0020}, 0x2004: []rune{0x0020}, 0x2005: []rune{0x0020}, 0x2006: []rune{0x0020}, 0x2007: []rune{0x0020}, 0x2008: []rune{0x0020}, 0x2009: []rune{0x0020}, 0x200A: []rune{0x0020}, 0x200B: []rune{0x0020}, 0x202F: []rune{0x0020}, 0x205F: []rune{0x0020}, 0x3000: []rune{0x0020}, } // SASLprep is a pre-defined stringprep profile for user names and passwords // as described in RFC-4013. // // Because the stringprep distinction between query and stored strings was // intended for compatibility across profile versions, but SASLprep was never // updated and is now deprecated, this profile only operates in stored // strings mode, prohibiting unassigned code points. var SASLprep Profile = saslprep var saslprep = Profile{ Mappings: []Mapping{ TableB1, mapNonASCIISpaceToASCIISpace, }, Normalize: true, Prohibits: []Set{ TableA1, TableC1_2, TableC2_1, TableC2_2, TableC3, TableC4, TableC5, TableC6, TableC7, TableC8, TableC9, }, CheckBiDi: true, }
{ "pile_set_name": "Github" }
package com.github.ldaniels528.trifecta.messages /** * Message Reader * @author [email protected] */ trait MessageReader { /** * Attempts to retrieve an input source for the given URL * @param url the given input URL * @return the option of an [[MessageInputSource input source]] */ def getInputSource(url: String): Option[MessageInputSource] }
{ "pile_set_name": "Github" }
package(default_visibility = ["//visibility:public"]) load( "@io_bazel_rules_go//go:def.bzl", "go_library", ) go_library( name = "go_default_library", srcs = ["latest.go"], importpath = "k8s.io/kubernetes/pkg/scheduler/api/latest", deps = [ "//pkg/scheduler/api:go_default_library", "//pkg/scheduler/api/v1:go_default_library", "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", "//vendor/k8s.io/apimachinery/pkg/runtime/serializer/json:go_default_library", "//vendor/k8s.io/apimachinery/pkg/runtime/serializer/versioning:go_default_library", ], ) filegroup( name = "package-srcs", srcs = glob(["**"]), tags = ["automanaged"], visibility = ["//visibility:private"], ) filegroup( name = "all-srcs", srcs = [":package-srcs"], tags = ["automanaged"], )
{ "pile_set_name": "Github" }
/* * IXWebSocketTransport.h * Author: Benjamin Sergeant * Copyright (c) 2017-2018 Machine Zone, Inc. All rights reserved. */ #pragma once // // Adapted from https://github.com/dhbaird/easywsclient // #include "IXCancellationRequest.h" #include "IXProgressCallback.h" #include "IXSocketTLSOptions.h" #include "IXWebSocketCloseConstants.h" #include "IXWebSocketHandshake.h" #include "IXWebSocketHttpHeaders.h" #include "IXWebSocketPerMessageDeflate.h" #include "IXWebSocketPerMessageDeflateOptions.h" #include "IXWebSocketSendInfo.h" #include <atomic> #include <functional> #include <list> #include <memory> #include <mutex> #include <string> #include <vector> namespace ix { class Socket; enum class SendMessageKind { Text, Binary, Ping }; class WebSocketTransport { public: enum class ReadyState { CLOSING, CLOSED, CONNECTING, OPEN }; enum class MessageKind { MSG_TEXT, MSG_BINARY, PING, PONG, FRAGMENT }; enum class PollResult { Succeeded, AbnormalClose, CannotFlushSendBuffer }; using OnMessageCallback = std::function<void(const std::string&, size_t, bool, MessageKind)>; using OnCloseCallback = std::function<void(uint16_t, const std::string&, size_t, bool)>; WebSocketTransport(); ~WebSocketTransport(); void configure(const WebSocketPerMessageDeflateOptions& perMessageDeflateOptions, const SocketTLSOptions& socketTLSOptions, bool enablePong, int pingIntervalSecs); // Client WebSocketInitResult connectToUrl(const std::string& url, const WebSocketHttpHeaders& headers, int timeoutSecs); // Server WebSocketInitResult connectToSocket(std::unique_ptr<Socket> socket, int timeoutSecs); PollResult poll(); WebSocketSendInfo sendBinary(const std::string& message, const OnProgressCallback& onProgressCallback); WebSocketSendInfo sendText(const std::string& message, const OnProgressCallback& onProgressCallback); WebSocketSendInfo sendPing(const std::string& message); void close(uint16_t code = WebSocketCloseConstants::kNormalClosureCode, const std::string& reason = WebSocketCloseConstants::kNormalClosureMessage, size_t closeWireSize = 0, bool remote = false); void closeSocket(); ReadyState getReadyState() const; void setReadyState(ReadyState readyState); void setOnCloseCallback(const OnCloseCallback& onCloseCallback); void dispatch(PollResult pollResult, const OnMessageCallback& onMessageCallback); size_t bufferedAmount() const; // internal WebSocketSendInfo sendHeartBeat(); private: std::string _url; struct wsheader_type { unsigned header_size; bool fin; bool rsv1; bool rsv2; bool rsv3; bool mask; enum opcode_type { CONTINUATION = 0x0, TEXT_FRAME = 0x1, BINARY_FRAME = 0x2, CLOSE = 8, PING = 9, PONG = 0xa, } opcode; int N0; uint64_t N; uint8_t masking_key[4]; }; // Tells whether we should mask the data we send. // client should mask but server should not std::atomic<bool> _useMask; // Tells whether we should flush the send buffer before // saying that a send is complete. This is the mode for server code. std::atomic<bool> _blockingSend; // Buffer for reading from our socket. That buffer is never resized. std::vector<uint8_t> _readbuf; // Contains all messages that were fetched in the last socket read. // This could be a mix of control messages (Close, Ping, etc...) and // data messages. That buffer std::vector<uint8_t> _rxbuf; // Contains all messages that are waiting to be sent std::vector<uint8_t> _txbuf; mutable std::mutex _txbufMutex; // Hold fragments for multi-fragments messages in a list. We support receiving very large // messages (tested messages up to 700M) and we cannot put them in a single // buffer that is resized, as this operation can be slow when a buffer has its // size increased 2 fold, while appending to a list has a fixed cost. std::list<std::string> _chunks; // Record the message kind (will be TEXT or BINARY) for a fragmented // message, present in the first chunk, since the final chunk will be a // CONTINUATION opcode and doesn't tell the full message kind MessageKind _fragmentedMessageKind; // Ditto for whether a message is compressed bool _receivedMessageCompressed; // Fragments are 32K long static constexpr size_t kChunkSize = 1 << 15; // Underlying TCP socket std::unique_ptr<Socket> _socket; std::mutex _socketMutex; // Hold the state of the connection (OPEN, CLOSED, etc...) std::atomic<ReadyState> _readyState; OnCloseCallback _onCloseCallback; std::string _closeReason; mutable std::mutex _closeReasonMutex; std::atomic<uint16_t> _closeCode; std::atomic<size_t> _closeWireSize; std::atomic<bool> _closeRemote; // Data used for Per Message Deflate compression (with zlib) WebSocketPerMessageDeflatePtr _perMessageDeflate; WebSocketPerMessageDeflateOptions _perMessageDeflateOptions; std::atomic<bool> _enablePerMessageDeflate; std::string _decompressedMessage; std::string _compressedMessage; // Used to control TLS connection behavior SocketTLSOptions _socketTLSOptions; // Used to cancel dns lookup + socket connect + http upgrade std::atomic<bool> _requestInitCancellation; mutable std::mutex _closingTimePointMutex; std::chrono::time_point<std::chrono::steady_clock> _closingTimePoint; static const int kClosingMaximumWaitingDelayInMs; // enable auto response to ping std::atomic<bool> _enablePong; static const bool kDefaultEnablePong; // Optional ping and pong timeout int _pingIntervalSecs; std::atomic<bool> _pongReceived; static const int kDefaultPingIntervalSecs; static const std::string kPingMessage; std::atomic<uint64_t> _pingCount; // We record when ping are being sent so that we can know when to send the next one mutable std::mutex _lastSendPingTimePointMutex; std::chrono::time_point<std::chrono::steady_clock> _lastSendPingTimePoint; // If this function returns true, it is time to send a new ping bool pingIntervalExceeded(); void initTimePointsAfterConnect(); // after calling close(), if no CLOSE frame answer is received back from the remote, we // should close the connexion bool closingDelayExceeded(); void sendCloseFrame(uint16_t code, const std::string& reason); void closeSocketAndSwitchToClosedState(uint16_t code, const std::string& reason, size_t closeWireSize, bool remote); bool wakeUpFromPoll(uint64_t wakeUpCode); bool flushSendBuffer(); bool sendOnSocket(); bool receiveFromSocket(); template<class T> WebSocketSendInfo sendData(wsheader_type::opcode_type type, const T& message, bool compress, const OnProgressCallback& onProgressCallback = nullptr); template<class Iterator> bool sendFragment( wsheader_type::opcode_type type, bool fin, Iterator begin, Iterator end, bool compress); void emitMessage(MessageKind messageKind, const std::string& message, bool compressedMessage, const OnMessageCallback& onMessageCallback); bool isSendBufferEmpty() const; template<class Iterator> void appendToSendBuffer(const std::vector<uint8_t>& header, Iterator begin, Iterator end, uint64_t message_size, uint8_t masking_key[4]); unsigned getRandomUnsigned(); void unmaskReceiveBuffer(const wsheader_type& ws); std::string getMergedChunks() const; void setCloseReason(const std::string& reason); const std::string& getCloseReason() const; }; } // namespace ix
{ "pile_set_name": "Github" }
# -*- coding: utf-8 -*- # Copyright (c) 2014 Rackspace # 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. """ rfc3986 ======= An implementation of semantics and validations described in RFC 3986. See http://rfc3986.rtfd.org/ for documentation. :copyright: (c) 2014 Rackspace :license: Apache v2.0, see LICENSE for details """ __title__ = 'rfc3986' __author__ = 'Ian Cordasco' __author_email__ = '[email protected]' __license__ = 'Apache v2.0' __copyright__ = 'Copyright 2014 Rackspace' __version__ = '0.3.0' from .api import (URIReference, uri_reference, is_valid_uri, normalize_uri, urlparse) from .parseresult import ParseResult __all__ = ( 'ParseResult', 'URIReference', 'is_valid_uri', 'normalize_uri', 'uri_reference', 'urlparse', )
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <project> <modelVersion>4.0.0</modelVersion> <groupId>org.apache.maven.its.help</groupId> <artifactId>test</artifactId> <version>1.0</version> <description> </description> <build> <plugins> </plugins> </build> </project>
{ "pile_set_name": "Github" }
# List of Labs for Docker Compose
{ "pile_set_name": "Github" }
dialog.open_url_failed.title=Fehler beim \u00d6ffnen des Webbrowsers dialog.open_url_failed.icon=/icons/64x64/error.png dialog.open_url_failed.ok={0} konnte nicht ge\u00f6ffnet werden\nVersuchen Sie es bitte direkt im Webbrowers.\n(Die URL wurde in die Zwischenablage kopiert. Einfach einf\u00fcgen!) help.userguide.url=http://violet.sourceforge.net/help.php?lang=de help.homepage.url=http://violet.sourceforge.net/index.php?lang=de
{ "pile_set_name": "Github" }
#include <string> #include "sim.h" namespace sim{ std::string version(){ return "1.0"; } std::string encode(const std::string s, bool force_ascii){ std::string ret; int size = (int)s.size(); for(int i=0; i<size; i++){ char c = s[i]; switch(c){ case ' ': ret.append("\\s"); break; case '\\': ret.append("\\\\"); break; case '\a': ret.append("\\a"); break; case '\b': ret.append("\\b"); break; case '\f': ret.append("\\f"); break; case '\v': ret.append("\\v"); break; case '\r': ret.append("\\r"); break; case '\n': ret.append("\\n"); break; case '\t': ret.append("\\t"); break; case '\0': ret.append("\\0"); break; default: if(!force_ascii){ ret.push_back(c); }else{ // TODO: 只对非 UTF-8 字笊进行蜬义 static const char *hex = "0123456789abcdef"; if(c >= '!' && c <= '~'){ ret.push_back(c); }else{ ret.append("\\x"); unsigned char d = c; ret.push_back(hex[d >> 4]); ret.push_back(hex[d & 0x0f]); } } break; } } return ret; } inline static int hex_int(char c){ if(c >= '0' && c <= '9'){ return c - '0'; }else{ return c - 'a' + 10; } } std::string decode(const std::string s){ int size = (int)s.size(); std::string ret; for(int i=0; i<size; i++){ char c = s[i]; if(c != '\\'){ ret.push_back(c); continue; } if(i >= size - 1){ break; } char c2 = s[++i]; switch(c2){ case 's': ret.push_back(' '); break; case '\\': ret.push_back('\\'); break; case 'a': ret.push_back('\a'); break; case 'b': ret.push_back('\b'); break; case 'f': ret.push_back('\f'); break; case 'v': ret.push_back('\v'); break; case 'r': ret.push_back('\r'); break; case 'n': ret.push_back('\n'); break; case 't': ret.push_back('\t'); break; case '0': ret.push_back('\0'); break; case 'x': if(i < size - 2){ char c3 = s[++i]; char c4 = s[++i]; ret.push_back((char)((hex_int(c3) << 4) + hex_int(c4))); } break; default: ret.push_back(c2); break; } } return ret; } }; // namespace sim
{ "pile_set_name": "Github" }
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "include/buffer.h" #include "include/stringify.h" #include "common/ceph_argparse.h" #include "common/config_proxy.h" #include "common/errno.h" #include "erasure-code/ErasureCode.h" #include "erasure-code/ErasureCodePlugin.h" #include "global/global_context.h" #include "global/global_init.h" #include "osd/ECUtil.h" #include <iostream> #include <map> #include <string> #include <vector> #include <boost/algorithm/string.hpp> std::vector<std::string> display_params = { "chunk_count", "data_chunk_count", "coding_chunk_count" }; void usage(const std::string message, ostream &out) { if (!message.empty()) { out << message << std::endl; out << "" << std::endl; } out << "usage: ceph-erasure-code-tool test-plugin-exists <plugin>" << std::endl; out << " ceph-erasure-code-tool validate-profile <profile> [<display-param> ...]" << std::endl; out << " ceph-erasure-code-tool calc-chunk-size <profile> <object_size>" << std::endl; out << " ceph-erasure-code-tool encode <profile> <stripe_unit> <want_to_encode> <fname>" << std::endl; out << " ceph-erasure-code-tool decode <profile> <stripe_unit> <want_to_decode> <fname>" << std::endl; out << "" << std::endl; out << " plugin - plugin name" << std::endl; out << " profile - comma separated list of erasure-code profile settings" << std::endl; out << " example: plugin=jerasure,technique=reed_sol_van,k=3,m=2" << std::endl; out << " display-param - parameter to display (display all if empty)" << std::endl; out << " may be: " << display_params << std::endl; out << " object_size - object size" << std::endl; out << " stripe_unit - stripe unit" << std::endl; out << " want_to_encode - comma separated list of shards to encode" << std::endl; out << " want_to_decode - comma separated list of shards to decode" << std::endl; out << " fname - name for input/output files" << std::endl; out << " when encoding input is read form {fname} file," << std::endl; out << " result is stored in {fname}.{shard} files" << std::endl; out << " when decoding input is read form {fname}.{shard} files," << std::endl; out << " result is stored in {fname} file" << std::endl; } int ec_init(const std::string &profile_str, const std::string &stripe_unit_str, ceph::ErasureCodeInterfaceRef *ec_impl, std::unique_ptr<ECUtil::stripe_info_t> *sinfo) { ceph::ErasureCodeProfile profile; std::vector<std::string> opts; boost::split(opts, profile_str, boost::is_any_of(", ")); for (auto &opt_str : opts) { std::vector<std::string> opt; boost::split(opt, opt_str, boost::is_any_of("=")); if (opt.size() <= 1) { usage("invalid profile", std::cerr); return 1; } profile[opt[0]] = opt[1]; } auto plugin = profile.find("plugin"); if (plugin == profile.end()) { usage("invalid profile: plugin not specified", std::cerr); return 1; } stringstream ss; ceph::ErasureCodePluginRegistry::instance().factory( plugin->second, g_conf().get_val<std::string>("erasure_code_dir"), profile, ec_impl, &ss); if (!*ec_impl) { usage("invalid profile: " + ss.str(), std::cerr); return 1; } if (sinfo == nullptr) { return 0; } uint64_t stripe_unit = atoi(stripe_unit_str.c_str()); if (stripe_unit <= 0) { usage("invalid stripe unit", std::cerr); return 1; } uint64_t stripe_size = atoi(profile["k"].c_str()); ceph_assert(stripe_size > 0); uint64_t stripe_width = stripe_size * stripe_unit; sinfo->reset(new ECUtil::stripe_info_t(stripe_size, stripe_width)); return 0; } int do_test_plugin_exists(const std::vector<const char*> &args) { if (args.size() < 1) { usage("not enought arguments", std::cerr); return 1; } ErasureCodePluginRegistry &instance = ErasureCodePluginRegistry::instance(); ErasureCodePlugin *plugin; stringstream ss; std::lock_guard l{instance.lock}; int r = instance.load( args[0], g_conf().get_val<std::string>("erasure_code_dir"), &plugin, &ss); std::cerr << ss.str() << endl; return r; } int do_validate_profile(const std::vector<const char*> &args) { if (args.size() < 1) { usage("not enought arguments", std::cerr); return 1; } ceph::ErasureCodeInterfaceRef ec_impl; int r = ec_init(args[0], {}, &ec_impl, nullptr); if (r < 0) { return r; } if (args.size() > 1) { std::set<std::string> valid_params(display_params.begin(), display_params.end()); display_params.clear(); for (size_t i = 1; i < args.size(); i++) { if (!valid_params.count(args[i])) { usage("invalid display param: " + std::string(args[i]), std::cerr); return 1; } display_params.push_back(args[i]); } } for (auto &param : display_params) { if (display_params.size() > 1) { std::cout << param << ": "; } if (param == "chunk_count") { std::cout << ec_impl->get_chunk_count() << std::endl; } else if (param == "data_chunk_count") { std::cout << ec_impl->get_data_chunk_count() << std::endl; } else if (param == "coding_chunk_count") { std::cout << ec_impl->get_coding_chunk_count() << std::endl; } else { ceph_abort_msgf("unknown display_param: %s", param.c_str()); } } return 0; } int do_calc_chunk_size(const std::vector<const char*> &args) { if (args.size() < 2) { usage("not enought arguments", std::cerr); return 1; } ceph::ErasureCodeInterfaceRef ec_impl; int r = ec_init(args[0], {}, &ec_impl, nullptr); if (r < 0) { return r; } uint64_t object_size = atoi(args[1]); if (object_size <= 0) { usage("invalid object size", std::cerr); return 1; } std::cout << ec_impl->get_chunk_size(object_size) << std::endl; return 0; } int do_encode(const std::vector<const char*> &args) { if (args.size() < 4) { usage("not enought arguments", std::cerr); return 1; } ceph::ErasureCodeInterfaceRef ec_impl; std::unique_ptr<ECUtil::stripe_info_t> sinfo; int r = ec_init(args[0], args[1], &ec_impl, &sinfo); if (r < 0) { return r; } std::set<int> want; std::vector<std::string> shards; boost::split(shards, args[2], boost::is_any_of(",")); for (auto &shard : shards) { want.insert(atoi(shard.c_str())); } ceph::bufferlist decoded_data; std::string fname = args[3]; std::string error; r = decoded_data.read_file(fname.c_str(), &error); if (r < 0) { std::cerr << "failed to read " << fname << ": " << error << std::endl; return 1; } uint64_t stripe_width = sinfo->get_stripe_width(); if (decoded_data.length() % stripe_width != 0) { uint64_t pad = stripe_width - decoded_data.length() % stripe_width; decoded_data.append_zero(pad); } std::map<int, ceph::bufferlist> encoded_data; r = ECUtil::encode(*sinfo, ec_impl, decoded_data, want, &encoded_data); if (r < 0) { std::cerr << "failed to encode: " << cpp_strerror(r) << std::endl; return 1; } for (auto &[shard, bl] : encoded_data) { std::string name = fname + "." + stringify(shard); r = bl.write_file(name.c_str()); if (r < 0) { std::cerr << "failed to write " << name << ": " << cpp_strerror(r) << std::endl; return 1; } } return 0; } int do_decode(const std::vector<const char*> &args) { if (args.size() < 4) { usage("not enought arguments", std::cerr); return 1; } ceph::ErasureCodeInterfaceRef ec_impl; std::unique_ptr<ECUtil::stripe_info_t> sinfo; int r = ec_init(args[0], args[1], &ec_impl, &sinfo); if (r < 0) { return r; } std::map<int, ceph::bufferlist> encoded_data; std::vector<std::string> shards; boost::split(shards, args[2], boost::is_any_of(",")); for (auto &shard : shards) { encoded_data[atoi(shard.c_str())] = {}; } ceph::bufferlist decoded_data; std::string fname = args[3]; for (auto &[shard, bl] : encoded_data) { std::string name = fname + "." + stringify(shard); std::string error; r = bl.read_file(name.c_str(), &error); if (r < 0) { std::cerr << "failed to read " << name << ": " << error << std::endl; return 1; } } r = ECUtil::decode(*sinfo, ec_impl, encoded_data, &decoded_data); if (r < 0) { std::cerr << "failed to decode: " << cpp_strerror(r) << std::endl; return 1; } r = decoded_data.write_file(fname.c_str()); if (r < 0) { std::cerr << "failed to write " << fname << ": " << cpp_strerror(r) << std::endl; return 1; } return 0; } int main(int argc, const char **argv) { std::vector<const char*> args; argv_to_vec(argc, argv, args); auto cct = global_init(nullptr, args, CEPH_ENTITY_TYPE_CLIENT, CODE_ENVIRONMENT_UTILITY, CINIT_FLAG_NO_MON_CONFIG); if (args.empty() || args[0] == std::string("-h") || args[0] == std::string("--help")) { usage("", std::cout); return 0; } if (args.size() < 1) { usage("not enought arguments", std::cerr); return 1; } std::string cmd = args[0]; std::vector<const char*> cmd_args(args.begin() + 1, args.end()); if (cmd == "test-plugin-exists") { return do_test_plugin_exists(cmd_args); } else if (cmd == "validate-profile") { return do_validate_profile(cmd_args); } else if (cmd == "calc-chunk-size") { return do_calc_chunk_size(cmd_args); } else if (cmd == "encode") { return do_encode(cmd_args); } else if (cmd == "decode") { return do_decode(cmd_args); } usage("invalid command: " + cmd, std::cerr); return 1; }
{ "pile_set_name": "Github" }
# Bind Use Cases ## External Service with Bind (mLab and webapp) The external service use case is where an Ansible Playbook Bundle (APB) is able to connect to a service outside of the cluster. One example, is a webapp that uses mLab as their back end store. There will be a specific APB for the external service. Catalog Operator does the following: * Creates a broker resource which calls the AnsibleServiceBroker /catalog endpoint * The /catalog endpoint response populates the ServiceCatalog's list of ServiceClasses. In our example, this is mLab and Go WebApp The Service Consumer then utilizes the ServiceClasses for their needs. After getting a list of the available service classes, the Consumer will then: * Creates an instance of the mLab service. * ServiceCatalog calls provision endpoint on AnsibleServiceBroker * AnsibleServiceBroker provisions the mLab APB * mLab APB configures the mLab instance being made available * mLab service ready for consumption * Create a binding resource for the mLab service * ServiceCatalog calls the binding endpoint on the AnsibleServiceBroker * AnsibleServiceBroker calls bind on the mLab APB * mLab APB will return the credentials, coordinates, & configs for the service. * Magic happens * ServiceCatalog does something with the bind information such that it can be injected into the applications later * Creates an instance of the Go WebApp service. * ServiceCatalog calls provision endpoint on AnsibleServiceBroker * AnsibleServiceBroker provisions the Go WebApp APB * The mLab binding information is *injected* into the Go WebApp APB * Go WebApp APB configures itself to use the information * Go WebApp service is ready for consumption and utilizing the mLab service ### Binding diagram ![binding example](images/binding-example.png) ### Binding example sequence diagram ![binding example sequence diagram](images/binding-example-seq-diagram.png) ### Sequence diagram source ``` Catalog Operator -> ServiceCatalog: POST broker ServiceCatalog -> ServiceCatalog: Create Broker resource Controller -> AnsibleServiceBroker: GET /catalog AnsibleServiceBroker -> Controller: List of available service classes: mLab, Go WebApp Controller -> ServiceCatalog: Creates list of service classes available Service Consumer -> ServiceCatalog: GET /serviceclasses Service Consumer -> ServiceCatalog: POST /instance (mLab) Controller -> AnsibleServiceBroker: PUT /provision (mLab) AnsibleServiceBroker -> mLab APB: docker run provision mLab APB -> OpenShift: creates Kubernetes service endpoint ServiceCatalog -> Service Consumer: mLab instance ready Service Consumer -> ServiceCatalog: PUT /binding ServiceCatalog -> ServiceCatalog: Create binding resource Controller -> AnsibleServiceBroker: PUT /binding AnsibleServiceBroker -> mLab APB: docker run binding mLab APB -> AnsibleServiceBroker: Returns the binding information for external mLab Service AnsibleServiceBroker -> Controller: Returns binding information Controller -> Magic: Store binding information for injection later Service Consumer -> ServiceCatalog: POST /instance (Go WebApp) Controller -> AnsibleServiceBroker: PUT /provision (Go WebApp) AnsibleServiceBroker -> Go WebApp APB: docker run provision Magic -> Go WebApp APB: INJECT binding information Go WebApp APB -> mLab Service: Uses AnsibleServiceBroker -> Controller: Go WebApp service instance ready ServiceCatalog -> Service Consumer: Go WebApp instance ready ``` ## Bindable Database Service There are services that will be deployed that simply exist to be bound to other applications. Typical use case is a Mariadb database instance. * provision database APB (stays up to let other bind) * bind request to app returns connection information, ### Database example sequence diagram ![database provision and bind](images/database-provision-and-bind.png) ### Sequence diagram source ``` Service Consumer -> ServiceCatalog: POST instance ServiceCatalog -> Ansible Service Broker: PUT provision/instance_id Ansible Service Broker -> etcd : get database image etcd -> Ansible Service Broker: return image record Ansible Service Broker -> Docker Hub: pull database image Docker Hub -> Ansible Service Broker: return database image Ansible Service Broker -> Ansible Service Broker: run database image Ansible Service Broker -> ServiceCatalog: return 200 image ServiceCatalog -> Service Consumer: ServiceClass Service Consumer -> ServiceCatalog: PUT /binding ServiceCatalog -> ServiceCatalog: Create binding resource Controller -> Ansible Service Broker: PUT /binding Ansible Service Broker -> Controller: return database connection string Controller -> Magic: Store binding information for injection later ``` ## Etherpad wants to connect to database * provision etherpad * bind to database * assume database service previously provisioned ### Etherpad sequence diagram ![etherpad connect to db](images/etherpad-connect-to-db.png) ### Sequence diagram source ``` Service Consumer -> ServiceCatalog: POST /instance (Etherpad) Controller -> Ansible Service Broker: PUT /provision (Etherpad) Ansible Service Broker -> Go WebApp APB: docker run provision Ansible Service Broker -> etcd : get etherpad image etcd -> Ansible Service Broker: return image record Ansible Service Broker -> Docker Hub: pull etherpad image Docker Hub -> Ansible Service Broker: return etherpad image Ansible Service Broker -> Ansible Service Broker: run etherpad image Ansible Service Broker -> ServiceCatalog: return 200 OK Magic -> Go WebApp APB: INJECT binding information Go WebApp APB -> mLab Service: Uses Ansible Service Broker -> Controller: Go WebApp service instance ready ServiceCatalog -> Service Consumer: Go WebApp instance ready ``` ## Issues * does the service consumer have to initiate the binds?
{ "pile_set_name": "Github" }
# PDP䞊䞋文的数据采集 Digital cellular telecommunicaitons system:数字蜂窝通信系统 Universal Mobile Telecommunication System(UMTS):通甚移劚系统 gn/gp接口: <div class=box><img src=../png/gn-gp-interface.jpg align=middle></div> $Gp$接口是䞎其他的PLMN进行亀互的其实报文规则䞀暡䞀样。可甚于小区的曎新新的SGSN向旧的SGSN发起请求获取甚户的IMSI号等信息然后向原来附着的GGSN发起PDP曎新请求。 二次激掻䞍䌚曎新甚户终端IP也䞍䌚曎新GGSN控制面TEID䜆是䌚分配新的GGSN数据面TEID。因䞺GTP解析时是根据3䞪元玠(user_ip, ggsn_ip_c,teid_u)这样甚户二次激掻的䞊行流量就䌚被远螪到(其实圚添加甚户之前就刀断是吊有ggsn_teid_c就没有加䞊). ## 名词解释 CSCircuit Switch电路亀换 PSPacket Switch分组亀换 MCC移劚囜家码䞭囜是460 MNC移劚眑号区分䞀䞪囜家䞍同的运营商圚䞭囜移劚䞺00联通䜍01. LAC:Location Area Code(LAC),䜍眮区号码。 RAC:Routeing Area Code,路由噚码 SAC:Service Area Code,服务区码 CI:Cell Identification SAI:Service Area Identifier PLMNPublic Land Mobile Network公共陆地移劚眑络。PLMN=MCC+MNC䟋劂䞭囜移劚46000联通46001 LAIMCC + MNC + LAC RAILAI + RAC CGILAI + CI SAI: LAI + SAC(Service Area Code) $CGI = MCC + MNC + LAC + CI$ $SAI = MCC + MNC + LAC + SAC$ $RAI = MCC + MNC + LAC + RAC$ $User Location Information IE侭的geograhic location type,0代衚后面是CGI1--SAI2--RAI。$ $RAI侭的LAC和User Location Information侭的LAC有什么䞍同$ $记圕甚户的圓前䜍眮信息甚户从BSS接入则䞺CGI甚户从RNS接入䞺SAI。$ ## 暡块需求思路 > 圚G眑的PS域进行甚户信息的采集。 1. 建立绎技针对于䞀䞪甚户的信息节点 2. 提䟛倚种查询接口 3. 统计甚户的行䞺提䟛䌠出功胜 ## 孊习元玠 > GTP䞭叫做`Information Elements`Radius叫做`AVP`。 `IE`又分䞺TVTLV类型IE的`type field`第8䜍劂果是0就是TV(1-127是TV)。1是TLV类型。 ### 手机号码 䞍包含字冠劂+86008686 ### 䜍眮区猖码 > 包含圚信息元Routing Area Idntity(RAI)䞭。 LAC:locatoin area code䜍眮区码,䞺寻呌而讟眮的䞀䞪区域芆盖䞀片地理区域初期䞀般按行政区域划分䞀䞪县或䞀䞪区。䜍眮区码LAC则甚于标识䞍同的䜍眮区。䜍眮区码LAC包含于LAI䞭由䞀䞪字节组成采甚16进制猖码。可甚范囎0x0000--0xFFFF.码组0x0000和0xFFFF䞍可以䜿甚。䞀䞪䜍眮区可以包含䞀䞪或倚䞪小区。 RAI䌚圚Creat PDP context Request,Update PDP Context Request出现.也䌚圚新旧SGSN之闎的消息䞭出现可以䞍关心。 劂果LAC芆盖范囎过小则移劚台发生的䜍眮曎新过皋将增倚从而增加了系统䞭的信什流量。 ### CI号码 > 圓有眑络切换时选择第䞀䞪CI。 $Cell ID$:对应IE-174:Cell Identification。 Cell Id甚途基于手机眑络基站定䜍。基于Cell-ID蜂窝猖号的定䜍技术根据小区基站的芆盖范囎半埄来确讀手机的倧臎䜍眮所以定䜍该方匏的定䜍粟床䞎小区基站的分垃密床密切盞关。垂区粟床方䜍倧臎圚150m巊右郊区粟床范囎倧臎圚1000m2000m巊右。 ### 终端类型-IMEI International Mobile Equipment identity:囜际移劚讟倇识别码。䞀般圚PDP䞊䞋文请求里面垊有。 ### 匀始时闎 通过定时的圚linux端获取基准时闎计算到分秒。 ### 结束时闎 ### 时长秒 ### RATType > The "RAT Type"information element is used to indicate which Radio Access Technology is currently serving the UE. 取倌1代衚3G <div class=box><img src=../png/rattype-1.png></div> 2代衚2G <div class=box><img src=../png/rattype-2.png></div> 没有歀AVP也讀䞺是2G眑络 ### 终端IP End user address,端甚户地址type=128 ### 访问IP > 没有IP信息的填空对于有倚䞪IP的䞚务蟓出合并的流量记圕访问IP只填第䞀䞪IP。 ### 状态码 ### User Agent > 采集党郚信息 http请求倎域包含关于发起请求的甚户代理的信息。这是䞺了统计跟螪协议违反的情况和䞺了识别甚户代理从而䞺特定甚户代理自劚定制响应。甚户代理应该包含User-Agent倎域圚请求䞭。 ### APN > Access Point Name-`131`,劂3gwap3gnetuniwapuninetcmwapcmnet ### IMSI ### SGSN IP ### GGSN IP ### Content-type 实䜓倎域指明发给接收者的实䜓䞻题的媒䜓类型或圚HEAD方法䞭指明若请求䞺GET时将发送的媒䜓类型。 圓消息包含实䜓䞻䜓(entity)时䞻䜓的数据类型由实䜓倎域的Content-Type和Conten-Encoding倎域确定。 ### 源端口 ### 目的端口 ### 眑址/特埁信息 > 劂果有url填充url信息劂果没有填充特有信息。 ## 信息统计 总共$20项$ GTP隧道管理报文$9项$ * IMSI,IMEI,MSISDN(若有),终端IP,APN,SGSN_IP,GGSN_IP. * LAC(RAI),RAT type圚其他信什䞭出现 GTP移劚管理报文$1项$等 * CI(Cell Identification)--Forward Relocation Request(前向重定䜍请求). * LAC(RAI),RAT type也䌚出现圚这种报文䞭 䞚务报文$6项$ * User Agent,Content-type,URL,访问IP,源端口目的端口 计算的$3项$ * 匀始时闎结束时闎时长。 未确定$1项$ * 状态码. ## 抂芁讟计 * 銖先还是像孊习`ismi`那样通过甚户`ip`,`ggsn_ip_u`,䞀䞪`teid_u`建立针对甚户的唯䞀映射 * 提䟛针对于`ismi`,`imei`,`手机号`的查询 * 记圕`甚户ip``APN``GSN IP`等这些非唯䞀性的信息 * 记圕`User Agent`,`Content-type`,`url`,`端口`等信息可配 * 统计`访问IP`只记圕第䞀䞪然后记圕䞍同的ip䞪数 ### 内存 > gtp是每次郜alloc䞀䞪新的节点去分析报文然后copy信息。 倚䞪铟衚,只有䞀䞪`alloc`内存的地方有䞀䞪删陀的地方倚次`get`只有䞀块内存䌎随这甚户信息敎䞪生呜期。 只有䞀䞪讟眮(`set`)匕甚基数的地方其他其他地方`get``put` ### 匕甚计数 节点只有圚加圚䞎时衚sgsn_table䞊的时候被set䞺䞀然后添加定时噚。 其他地方郜是只是get put操䜜添加到后面5匠数据玢匕衚䞊的时候䞍对匕甚计数进行任䜕操䜜只是圚添加钱删陀匕甚计数保证留有䞀䞪给后添加的定时噚。 ### get by > 䞍䌚对铟衚产生圱响只䌚增加节点匕甚计数。 节点的get操䜜必须圚锁内因䞺定时噚是圚写锁里面进行unlink和put的圓匹配到盞应的节点时候芁先get再释攟锁保证最后的匕甚基数(1)没有没有被定时噚putfree,因䞺读锁还没有释攟。 䜿甚完后进行put操䜜。 ### get in - 节点unlink 没有get操䜜,删陀timer,unlink节点然后返回。因䞺已经删陀了timer所以所有get_by进行put之后计数䌚变回1. 然后再去重新add这䞪节点或者出错put. 䞍可以内嵌䜿甚get_by获取节点然后锁䜏返回的节点p进行删陀定时噚unlink操䜜。因䞺定时噚删陀是可以倚次删陀成功的䞍可以䜜䞺正确的刀定条件。所以圚get_by和加锁的时闎窗口里面可胜䌚有及倖䞀䞪进皋get_by到。然后删陀定时噚成功继续再次unlink出错 > 也可以䜿甚䞀䞪原子的标志这样就可以先get by然后刀断标志然后把标志眮䜍然后加锁进去unlink。 > 也可以get by埗到节点p然后去利甚p䞭含有的删陀玢匕衚的信息去重新get in - unlink。 ### 删陀或者unlink 1. 只胜同时加锁、同时unlink 因䞺劂果䞍是同时加锁进行unlinkunlink完䞀䞪铟衚。这䞪节点还䌚存圚圚这之后再次获埗锁进行解锁造成倚次unlink同䞀铟衚。 2. 只胜有䞀䞪甚于删陀的玢匕 这是由于只胜有䞀组(防止死锁)同时加锁顺序决定的。倚层锁的原因富臎只胜有䞀组加锁顺序所以䞀定是先获埗那䞪甚于删陀的玢匕衚的阻塞锁再䟝次获取其他的铟衚的阻塞锁进行unlink操䜜。 3. timer甚于删陀的奜倄 timer的奜倄就是知道节点的所有信息可以盎接顺序按照同䞀组加锁顺序加锁䞍甚先利甚$删陀玢匕衚$有䞔只胜有䞀䞪去获埗节点的其他信息。 ``` static inline gn_user_t * get_user_in_ggsn_gn(uint32_t ggsn_ip, uint32_t ggsn_teid) { hash_list_t *l; gn_user_t *p; const int idx = hash_gsn_gn(ggsn_ip, ggsn_teid); WR_LOCK_GGSN_GN(idx); l = gn_ggsn_head[idx].next; while (l) { p = container_of(l, gn_user_t, list_gsn); if (p->ggsn.ip_c == ggsn_ip && p->ggsn.teid_c == ggsn_teid) { WR_LOCK_ALL_GN(p); if (cvmx_tim_delete_entry(&p->tim_del) == CVMX_TIM_STATUS_SUCCESS) { hash_list_unlink(&p->list_gsn); UNLINK_ALL_GN(p); } else { p->timeout = 1; p->ggsn.ip_c = 0xff; p->ggsn.teid_c = 0xff; p = NULL; } WR_UNLOCK_GGSN_GN(idx); WR_UNLOCK_ALL_GN(p); return p; } l = l->next; } WR_UNLOCK_GGSN_GN(idx); return NULL; } ``` 䞍可胜䌚出现根据第二䞪去䜜䞺删陀的玢匕衚惟䞀䞀组加锁顺序决定的。因䞺圚硬并发情况䞋只胜是利甚删陀玢匕衚查扟到后盎接圚锁内进行删陀因䞺get by之后到加锁删陀之闎的时闎窗口䌚有其他的get by获取到节点继续进入阻塞锁进行删陀。而䞔又由于加锁顺序是唯䞀确定的䞀组所以只胜是有唯䞀䞪删陀玢匕衚而䞔它的阻塞锁再添加时候䞀盎圚最前面。 圓然也可以䜿甚䞀䞪标志linkunlink标志这样就算倚次进入unlink操䜜。先get by到通过刀断圚锁内刀断和眮䜍保证安党而跳过后续的unlink操䜜。跳出之后put。 也可以先get by之后把get in䜿甚的信息倍制到䞎时变量然后䜿甚倍制出的信息进行get in(进行二次查扟)而䞍是利甚get by出来的节点进行unlink. $劂䞋错误写法get by之后利甚节点get in$ ``` static inline gn_user_t * get_user_in_ggsn_gn(uint32_t ggsn_ip, uint32_t ggsn_teid) { gn_user_t *p; p = get_user_by_ggsn_gn(ggsn_ip, ggsn_teid); if (cvmx_unlikely(p == NULL)) return NULL; WR_LOCK_GGSN_GN(p->gsn_idx); WR_LOCK_ALL_GN(p); if (cvmx_tim_delete_entry(&p->tim_del) == CVMX_TIM_STATUS_SUCCESS) { hash_list_unlink(&p->list_gsn); UNLINK_ALL_GN(p); } else { p->timeout = 1; p->ggsn.ip_c = 0xff; p->ggsn.teid_c = 0xff; p = NULL; } gn_user_put(p); WR_UNLOCK_GGSN_GN(p->gsn_idx); WR_UNLOCK_ALL_GN(p); return p; } ``` ### 添加 䜿甚倚层锁的原因分析及分解: > gtp䞭是䌚把所有芁连接的衚同时加䞊锁因䞺圚gn暡块䞭有空信息䞍甚加䞺了省去空信息的hash计算这里䟝次添加安党的玢匕衚然后同时去加甚于删陀的玢匕衚和定时噚具有删陀操䜜。泚意加锁的顺序。 可以把这䞪唯䞀䞀䞪䜜删陀的衚攟到最后进行添加其他的铟衚加锁、添加、解锁。然后其他的铟衚可胜去进行get操䜜这时候䞍䌚有圱响劂果后面添加定时噚倱莥芁进行前面铟衚的unlink然后put(䞍胜free)即可。删陀的时候䞀定加䞊倚层锁进行删陀。 添加定时噚定时噚甚于检查超时-解铟删陀所以定时的添加必须圚最后的那几䞪甚于节点解铟删陀的危险铟衚的锁内执行保证所有的铟衚是圚安党的情况䞋添加定时噚(获埗节点unlink操䜜的凜数也必须保证先删陀定时噚再进行解铟)。添加倱莥后芁重新获埗前面的没有unlink操䜜的铟衚的锁进行解铟这里加锁的顺序芁保证䞀臎(这样的话有删陀操䜜的铟衚的锁圚其他的郚分芁先加加锁䞎$这里组成的顺序䞀臎$)防止死锁 加锁是根据结构䞭是吊盞应的数据解锁亊然。䜆是劂果添加安党铟衚时对于只有linkget操䜜的玢匕铟衚的时候有重倍数据䌚把旧的赋倌0劂果第二䞪数据来的借快第䞀䞪节点就䌚因䞺被眮零而没有解锁造成死锁。所以这里把倌讟眮成了`0xff`无效的倌代替赋倌0。 ### BUG 1. get_in..() 调甚了get_by..()凜数,留䞋䞀䞪恶心的时闎窗口。 2. 枅陀节点数据的时候把数据讟眮成了`0x00`,圱响解锁的行䞺。 3. 䜍域并行写入的bug先前的结构劂䞋 ``` /* 4 words */ uint16_t timeout: 13, nsapi_flag, 3; uint8_t cause; uint8_t teardown; uint32_t gsn_idx; uint32_t ip_idx; uint32_t imsi_idx; uint32_t imei_idx; uint32_t msisdn_idx; ``` 圚分别加锁连接节点的时候重倍发送报文䌚并行写`timeout`这里䌚匕起后面64䜍数据错乱富臎`gsn_idx`错乱造成死锁。 测试过䞍添加ggsn玢匕衚的情况没有问题出现原因是`gsn_idx`成䞺了保留甚于被乱写。 后来测试过`timeout`䞺`uint16_t`的类型䞀䞪晚䞊以后造成死锁。 所以改䞺䞀䞪完成64䜍的数据。 ``` uint64_t timeout; uint16_t nsapi_flag; uint8_t cause; uint8_t teardown; uint32_t gsn_idx; uint32_t ip_idx; uint32_t imsi_idx; uint32_t imei_idx; uint32_t msisdn_idx; ``` 总结䞍论什么bug劂果䞍是逻蟑错误䞀定是操䜜把别人内存改了或者别人把自己内存改了。 ## 关于二次激掻 二次激掻圚请求䞭䞍垊`sgsn_teid_c`,响应䞭也没有`ggsn_teid_c`应该郜是和䞻激掻䞀样的。䞍同的只是数据面的`teid`,还有䞀䞪`nsapi`。 劂果`sgsn_teid_c`和`sgsn_ip_c`有䞀样是䞺空的话可以通过二次激掻请求倎郚垊有的`ggsn_teid_c`和目的ip到ggsn衚䞭copy䞀䞪节点出来然后建立䞀䞪以`sgsn_teid_c`和`sgsn_ip_c`䞺玢匕`sgsn_teid_c`、`sgsn_ip_c`和`nsapi`䞺查扟条件的䞎时衚等埅二次激掻的响应。 圚响应消息倎郚取出`sgsn_teid_c`和目的ip查扟䞊面建立的䞎时衚劂果ggsn测有信息曎新就曎新䞎时节点的数据。然后添加节点。 最终䞻次和二次激掻郜是建立䞀䞪`user_ip`和`ggsn_ip_u`䜜䞺玢匕`user_ip` `ggsn_ip_u` `sgsn_teid_u` `ggsn_teid_u`䜜䞺查扟条件的铟衚。而䞔每次查扟`teid_u`只有也只甚其䞭䞀䞪去匹配。䞻-二䞍同的地方是铟衚䞭的`teid_u`和`nsapi`.䜆是`nsapi`䞍䜜䞺唯䞀匹配条件。 ## mips load呜什䞎䜍域操䜜诊解
{ "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. // @class NSError; @protocol SBApplicationDelegate - (id)eventDidFail:(const struct AEDesc *)arg1 withError:(NSError *)arg2; @end
{ "pile_set_name": "Github" }
// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.aws.toolkits.jetbrains.core.credentials import com.intellij.testFramework.ProjectRule import org.assertj.core.api.Assertions.assertThat import org.junit.Rule import org.junit.Test import software.aws.toolkits.core.region.anAwsRegion import software.aws.toolkits.jetbrains.core.region.MockRegionProvider.RegionProviderRule class ChangeAccountSettingsActionGroupTest { @Rule @JvmField val projectRule = ProjectRule() @Rule @JvmField val regionProviderRule = RegionProviderRule() @Rule @JvmField val settingsManagerRule = MockAwsConnectionManager.ProjectAccountSettingsManagerRule(projectRule) @Test fun `Can display both region and credentials selection`() { val group = ChangeAccountSettingsActionGroup(projectRule.project, ChangeAccountSettingsMode.BOTH) val actions = group.getChildren(null) assertThat(actions).hasAtLeastOneElementOfType(ChangeRegionAction::class.java) assertThat(actions).hasAtLeastOneElementOfType(ChangeCredentialsAction::class.java) } @Test fun `Can display only region selection`() { val group = ChangeAccountSettingsActionGroup(projectRule.project, ChangeAccountSettingsMode.REGIONS) val actions = group.getChildren(null) assertThat(actions).hasAtLeastOneElementOfType(ChangeRegionAction::class.java) assertThat(actions).doesNotHaveAnyElementsOfTypes(ChangeCredentialsAction::class.java) } @Test fun `Can display only credentials selection`() { val group = ChangeAccountSettingsActionGroup(projectRule.project, ChangeAccountSettingsMode.CREDENTIALS) val actions = group.getChildren(null) assertThat(actions).doesNotHaveAnyElementsOfTypes(ChangeRegionAction::class.java) assertThat(actions).hasAtLeastOneElementOfType(ChangeCredentialsAction::class.java) } @Test fun `Region group all regions at the top-level for selected partition and shows regions for non-selected paritions in a partition sub-menu`() { val selectedRegion = anAwsRegion(partitionId = "selected").also { regionProviderRule.regionProvider.addRegion(it) } val otherPartitionRegion = anAwsRegion(partitionId = "nonSelected").also { regionProviderRule.regionProvider.addRegion(it) } val anotherRegionInSamePartition = anAwsRegion(partitionId = otherPartitionRegion.partitionId).also { regionProviderRule.regionProvider.addRegion(it) } settingsManagerRule.settingsManager.changeRegionAndWait(selectedRegion) val group = ChangeAccountSettingsActionGroup(projectRule.project, ChangeAccountSettingsMode.REGIONS) val regionActionGroup = getRegionActions(group) val topLevelRegionActions = regionActionGroup.filterIsInstance<ChangeRegionAction>() val partitionActions = regionActionGroup.filterIsInstance<ChangePartitionActionGroup>().first().getChildren(null) val nonSelectedSubAction = partitionActions.filterIsInstance<ChangeRegionActionGroup>().first { it.templateText == otherPartitionRegion.partitionId } .getChildren(null).filterIsInstance<ChangeRegionAction>() assertThat(topLevelRegionActions).hasOnlyOneElementSatisfying { it.templateText == selectedRegion.displayName } assertThat(partitionActions).noneMatch { it.templateText == selectedRegion.partitionId } assertThat(nonSelectedSubAction).hasSize(2) assertThat(nonSelectedSubAction.map { it.templateText }).containsExactlyInAnyOrder( otherPartitionRegion.displayName, anotherRegionInSamePartition.displayName ) } @Test fun `Don't show partition selector if there is only one partition`() { val selectedRegion = regionProviderRule.regionProvider.defaultRegion() settingsManagerRule.settingsManager.changeRegionAndWait(selectedRegion) val group = ChangeAccountSettingsActionGroup(projectRule.project, ChangeAccountSettingsMode.REGIONS) val actions = getRegionActions(group) assertThat(actions).doesNotHaveAnyElementsOfTypes(ChangePartitionActionGroup::class.java) } private fun getRegionActions(group: ChangeAccountSettingsActionGroup) = group.getChildren(null) .filterIsInstance<ChangeRegionActionGroup>().first().getChildren(null) }
{ "pile_set_name": "Github" }
/* * Copyright 2016 IBM Corp. * * 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. */ /* Usage: bin/eclairjs.sh examples/ml/lda_example.js" */ function run(spark) { var Metadata = require("eclairjs/sql/types/Metadata"); var LDA = require("eclairjs/ml/clustering/LDA"); var dataset = spark.read().format("libsvm") .load("examples/data/mllib/sample_lda_libsvm_data.txt"); // Trains a LDA model. var lda = new LDA().setK(10).setMaxIter(10); var model = lda.fit(dataset); var ret = {}; ret.logLikelihood = model.logLikelihood(dataset); ret.logPerplexity = model.logPerplexity(dataset); // Shows the result ret.topics = model.describeTopics(3); ret.transformed = model.transform(dataset); return ret; } /* check if SparkSession is defined, if it is we are being run from Unit Test */ if (typeof sparkSession === 'undefined') { var SparkSession = require(EclairJS_Globals.NAMESPACE + '/sql/SparkSession'); var spark = SparkSession .builder() .appName("JavaScript IDA Example") .getOrCreate(); var result = run(spark); print("The lower bound on the log likelihood of the entire corpus: " + result.logLikelihood); print("The upper bound bound on perplexity: " + result.logPerplexity); print("The topics described by their top-weighted terms:"); result.topics.show(10); result.transformed.show(10); spark.stop(); }
{ "pile_set_name": "Github" }
var arrayReduce = require('./_arrayReduce'), deburr = require('./deburr'), words = require('./words'); /** Used to compose unicode capture groups. */ var rsApos = "['\u2019]"; /** Used to match apostrophes. */ var reApos = RegExp(rsApos, 'g'); /** * Creates a function like `_.camelCase`. * * @private * @param {Function} callback The function to combine each word. * @returns {Function} Returns the new compounder function. */ function createCompounder(callback) { return function(string) { return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); }; } module.exports = createCompounder;
{ "pile_set_name": "Github" }
id: dsq-747522222 date: 2010-09-17T08:54:36.0000000-07:00 name: Sean Blackman avatar: https://disqus.com/api/users/avatars/Sean Blackman.jpg message: <p>Can you tell me of a way to prove to others that my email is safe for any type of computer that can receive it?Especially any email software that has to process it.How about the ability to prove that social networking entries are safe to click on?</p>
{ "pile_set_name": "Github" }
//Parameter("") before = false; //Parameter("") overwritten = true; //Parameter("") main = true; after = true; //Parameter("") later = true; echo(str("Can a variable be used when it assigned later? ", later)); echo(str("Is overwriting possible? ", overwritten)); echo(str("Does an include before the assignment take priority? ", before)); echo(str("Does an include after the assignment take priority? ", after)); echo("before"); echo("after");
{ "pile_set_name": "Github" }
using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Z.Test { [TestClass] public partial class Bulk_BulkAction_BulkMerge_ManyMixedSelector { } }
{ "pile_set_name": "Github" }
package types // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command // GraphDriverData Information about a container's graph driver. // swagger:model GraphDriverData type GraphDriverData struct { // data // Required: true Data map[string]string `json:"Data"` // name // Required: true Name string `json:"Name"` }
{ "pile_set_name": "Github" }
ALTER TABLE `releases` ADD `dehashstatus` TINYINT(1) NOT NULL DEFAULT '0' AFTER `audiostatus` ; CREATE INDEX ix_releases_dehashstatus ON releases(dehashstatus); UPDATE `site` set `value` = '72' where `setting` = 'sqlpatch';
{ "pile_set_name": "Github" }
# Be sure to restart your server when you modify this file. # Specify a serializer for the signed and encrypted cookie jars. # Valid options are :json, :marshal, and :hybrid. Rails.application.config.action_dispatch.cookies_serializer = :json
{ "pile_set_name": "Github" }
10 dir 164 http://arc90labs-readability.googlecode.com/svn/trunk/lib/Zend/Validate/File http://arc90labs-readability.googlecode.com/svn 2009-12-10T00:21:56.012476Z 82 JJfutbol d4e419ec-0920-11de-bbfd-a7c1bc4c261e Upload.php file 2016-02-14T02:04:26.719466Z 5cb49901163e9083e9f42a03e087e87c 2009-12-10T00:21:56.012476Z 82 JJfutbol 7335 Md5.php file 2016-02-14T02:04:26.719466Z 32b57819c306f191f0f75cca9c7fa894 2009-12-10T00:21:56.012476Z 82 JJfutbol 5042 ExcludeExtension.php file 2016-02-14T02:04:26.719466Z d6b70c34eb0106f4ba77c5b653450549 2009-12-10T00:21:56.012476Z 82 JJfutbol 2882 Count.php file 2016-02-14T02:04:26.719466Z 2289609057ded60fe6741d4a8af12759 2009-12-10T00:21:56.012476Z 82 JJfutbol 7743 MimeType.php file 2016-02-14T02:04:26.715466Z a0952e3201043d714dd728a81acae9d4 2009-12-10T00:21:56.012476Z 82 JJfutbol 7868 Sha1.php file 2016-02-14T02:04:26.715466Z 35bcb426991890cf5b2cc34b507bc271 2009-12-10T00:21:56.012476Z 82 JJfutbol 4895 FilesSize.php file 2016-02-14T02:04:26.715466Z 9ffa93b8a2032c2d590ea329f6573fc1 2009-12-10T00:21:56.012476Z 82 JJfutbol 5391 NotExists.php file 2016-02-14T02:04:26.715466Z 4f419d63c865aa4166f20559ece05d64 2009-12-10T00:21:56.012476Z 82 JJfutbol 2476 IsCompressed.php file 2016-02-14T02:04:26.715466Z 56e95805c38abea29e4a8cc63750ba59 2009-12-10T00:21:56.012476Z 82 JJfutbol 4256 ExcludeMimeType.php file 2016-02-14T02:04:26.715466Z eee6a2f63bfe0b85f8c6ece7106b4f5d 2009-12-10T00:21:56.012476Z 82 JJfutbol 3078 Size.php file 2016-02-14T02:04:26.715466Z 86ad4fb2b42d1608933308db12856272 2009-12-10T00:21:56.012476Z 82 JJfutbol 11223 Crc32.php file 2016-02-14T02:04:26.715466Z 92e408618fb0ca18268c1cc4594c1dcc 2009-12-10T00:21:56.012476Z 82 JJfutbol 4849 Extension.php file 2016-02-14T02:04:26.715466Z 4d8dc6db61c49527ba13c095426a7978 2009-12-10T00:21:56.012476Z 82 JJfutbol 6135 ImageSize.php file 2016-02-14T02:04:26.715466Z dfc969059f94cd2c3e4c74107c7d5511 2009-12-10T00:21:56.012476Z 82 JJfutbol 11314 IsImage.php file 2016-02-14T02:04:26.715466Z 01d3868fea338b1dd03dda81f4ad0b8b 2009-12-10T00:21:56.012476Z 82 JJfutbol 4298 Exists.php file 2016-02-14T02:04:26.719466Z aff46f3e3aacd38be205323f860b261e 2009-12-10T00:21:56.012476Z 82 JJfutbol 5721 Hash.php file 2016-02-14T02:04:26.719466Z 181b8df76a817a3a4b5a784a02c6a06b 2009-12-10T00:21:56.012476Z 82 JJfutbol 5527
{ "pile_set_name": "Github" }
using ProjectEye.Core.Enums; using ProjectEye.Core.Models.Options; using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Media; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Resources; namespace ProjectEye.Core.Service { /// <summary> /// 音效Service /// 倄理䌑息结束提瀺音的加蜜和播攟 /// </summary> public class SoundService : IService { private readonly ConfigService config; private Dictionary<SoundType, SoundPlayer> players; public SoundService(ConfigService config) { players = new Dictionary<SoundType, SoundPlayer>(); //player.LoadCompleted += Player_LoadCompleted; this.config = config; } private void Player_LoadCompleted(object sender, AsyncCompletedEventArgs e) { (sender as SoundPlayer).Dispose(); } public void Init() { players.Add(SoundType.RestOverSound, new SoundPlayer()); players.Add(SoundType.TomatoWorkStartSound, new SoundPlayer()); players.Add(SoundType.TomatoWorkEndSound, new SoundPlayer()); players.Add(SoundType.Other, new SoundPlayer()); players[SoundType.RestOverSound].LoadCompleted += Player_LoadCompleted; players[SoundType.TomatoWorkStartSound].LoadCompleted += Player_LoadCompleted; players[SoundType.TomatoWorkEndSound].LoadCompleted += Player_LoadCompleted; players[SoundType.Other].LoadCompleted += Player_LoadCompleted; LoadConfigSound(); config.Changed += Config_Changed; } private void Config_Changed(object sender, EventArgs e) { var oldOptions = sender as OptionsModel; if (oldOptions.General.SoundPath != config.options.General.SoundPath || oldOptions.Tomato.WorkStartSoundPath != config.options.Tomato.WorkStartSoundPath || oldOptions.Tomato.WorkEndSoundPath != config.options.Tomato.WorkEndSoundPath) { LoadConfigSound(); } } /// <summary> /// 加蜜甚户配眮的音效 /// </summary> private void LoadConfigSound() { string restOverPath = null, tomatoWorkStartPath = null, tomatoWorkEndPath = null; if (!string.IsNullOrEmpty(config.options.General.SoundPath)) { restOverPath = config.options.General.SoundPath; } if (!string.IsNullOrEmpty(config.options.Tomato.WorkStartSoundPath)) { tomatoWorkStartPath = config.options.Tomato.WorkStartSoundPath; } if (!string.IsNullOrEmpty(config.options.Tomato.WorkEndSoundPath)) { tomatoWorkEndPath = config.options.Tomato.WorkEndSoundPath; } //加蜜䌑息结束提瀺音 LoadSound(SoundType.RestOverSound, restOverPath); //加蜜番茄时钟工䜜匀始提瀺音 LoadSound(SoundType.TomatoWorkStartSound, tomatoWorkStartPath); //加蜜番茄时钟工䜜结束提瀺音 LoadSound(SoundType.TomatoWorkEndSound, tomatoWorkEndPath); } #region 播攟音效 /// <summary> /// 播攟音效,默讀䌑息结束音效 /// </summary> public bool Play(SoundType soundType = SoundType.RestOverSound) { var player = players[soundType]; if (player.IsLoadCompleted) { try { player.Play(); return true; } catch (Exception ec) { //播攟声音倱莥可胜是加蜜了䞍支持或损坏的文件 LogHelper.Warning(ec.ToString()); //切换到默讀音效 LoadSound(); } } return false; } #endregion #region 加蜜指定音效文件 /// <summary> /// 从路埄加蜜音效 /// </summary> /// <param name="file">路埄</param> /// <param name="resource">指瀺是吊是系统资源</param> /// <returns></returns> public bool Load(SoundType soundType, string file, bool resource = true) { try { var player = players[soundType]; if (resource) { Uri soundUri = new Uri(file, UriKind.RelativeOrAbsolute); StreamResourceInfo info = Application.GetResourceStream(soundUri); player.Stream = info.Stream; } else { player.SoundLocation = file; } player.LoadAsync(); return true; } catch (Exception ec) { //Debug.WriteLine(ec); LogHelper.Warning(ec.ToString()); return false; } } /// <summary> /// 加蜜指定音效文件 /// </summary> /// <param name="path">音效文件路埄䞺空时加蜜默讀音效</param> public void LoadSound(SoundType soundType = SoundType.RestOverSound, string path = null) { bool isDefault = false; if (string.IsNullOrEmpty(path)) { isDefault = true; path = "/ProjectEye;component/Resources/relentless.wav"; } bool loadResult = Load(soundType, path, isDefault); //加蜜音效倱莥 if (!loadResult && !isDefault) { //加蜜自定义音效倱莥 //尝试加蜜默讀音效 LoadSound(); } } #endregion #region 测试倖郚音效 /// <summary> /// 测试倖郚音效 /// </summary> /// <param name="file"></param> /// <returns></returns> public bool Test(string file) { if (Load(SoundType.Other, file, false)) { if (Play(SoundType.Other)) { return true; } } return false; } #endregion } }
{ "pile_set_name": "Github" }
texinode(Arithmetic Evaluation)(Conditional Expressions)(Jobs & Signals)(Top) chapter(Arithmetic Evaluation) ifzman(\ sect(Arithmetic Evaluation) )\ cindex(arithmetic evaluation) cindex(evaluation, arithmetic) findex(let, use of) The shell can perform integer and floating point arithmetic, either using the builtin tt(let), or via a substitution of the form tt($LPAR()LPAR())var(...)tt(RPAR()RPAR()). For integers, the shell is usually compiled to use 8-byte precision where this is available, otherwise precision is 4 bytes. This can be tested, for example, by giving the command `tt(print - $(( 12345678901 )))'; if the number appears unchanged, the precision is at least 8 bytes. Floating point arithmetic always uses the `double' type with whatever corresponding precision is provided by the compiler and the library. The tt(let) builtin command takes arithmetic expressions as arguments; each is evaluated separately. Since many of the arithmetic operators, as well as spaces, require quoting, an alternative form is provided: for any command which begins with a `tt(LPAR()LPAR())', all the characters until a matching `tt(RPAR()RPAR())' are treated as a quoted expression and arithmetic expansion performed as for an argument of tt(let). More precisely, `tt(LPAR()LPAR())var(...)tt(RPAR()RPAR())' is equivalent to `tt(let ")var(...)tt(")'. The return status is 0 if the arithmetic value of the expression is non-zero, 1 if it is zero, and 2 if an error occurred. For example, the following statement example((( val = 2 + 1 ))) is equivalent to example(let "val = 2 + 1") both assigning the value 3 to the shell variable tt(val) and returning a zero status. cindex(arithmetic base) cindex(bases, in arithmetic) Integers can be in bases other than 10. A leading `tt(0x)' or `tt(0X)' denotes hexadecimal and a leading `tt(0b)' or `tt(0B)' binary. Integers may also be of the form `var(base)tt(#)var(n)', where var(base) is a decimal number between two and thirty-six representing the arithmetic base and var(n) is a number in that base (for example, `tt(16#ff)' is 255 in hexadecimal). The var(base)tt(#) may also be omitted, in which case base 10 is used. For backwards compatibility the form `tt([)var(base)tt(])var(n)' is also accepted. An integer expression or a base given in the form `var(base)tt(#)var(n)' may contain underscores (`tt(_)') after the leading digit for visual guidance; these are ignored in computation. Examples are tt(1_000_000) or tt(0xffff_ffff) which are equivalent to tt(1000000) and tt(0xffffffff) respectively. It is also possible to specify a base to be used for output in the form `tt([#)var(base)tt(])', for example `tt([#16])'. This is used when outputting arithmetical substitutions or when assigning to scalar parameters, but an explicitly defined integer or floating point parameter will not be affected. If an integer variable is implicitly defined by an arithmetic expression, any base specified in this way will be set as the variable's output arithmetic base as if the option `tt(-i) var(base)' to the tt(typeset) builtin had been used. The expression has no precedence and if it occurs more than once in a mathematical expression, the last encountered is used. For clarity it is recommended that it appear at the beginning of an expression. As an example: example(typeset -i 16 y print $(( [#8] x = 32, y = 32 )) print $x $y) outputs first `tt(8#40)', the rightmost value in the given output base, and then `tt(8#40 16#20)', because tt(y) has been explicitly declared to have output base 16, while tt(x) (assuming it does not already exist) is implicitly typed by the arithmetic evaluation, where it acquires the output base 8. The var(base) may be replaced or followed by an underscore, which may itself be followed by a positive integer (if it is missing the value 3 is used). This indicates that underscores should be inserted into the output string, grouping the number for visual clarity. The following integer specifies the number of digits to group together. For example: example(setopt cbases print $(( [#16_4] 65536 ** 2 ))) outputs `tt(0x1_0000_0000)'. The feature can be used with floating point numbers, in which case the base must be omitted; grouping is away from the decimal point. For example, example(zmodload zsh/mathfunc print $(( [#_] sqrt+LPAR()1e7+RPAR() ))) outputs `tt(3_162.277_660_168_379_5)' (the number of decimal places shown may vary). pindex(C_BASES, use of) pindex(OCTAL_ZEROES, use of) If the tt(C_BASES) option is set, hexadecimal numbers are output in the standard C format, for example `tt(0xFF)' instead of the usual `tt(16#FF)'. If the option tt(OCTAL_ZEROES) is also set (it is not by default), octal numbers will be treated similarly and hence appear as `tt(077)' instead of `tt(8#77)'. This option has no effect on the output of bases other than hexadecimal and octal, and these formats are always understood on input. When an output base is specified using the `tt([#)var(base)tt(])' syntax, an appropriate base prefix will be output if necessary, so that the value output is valid syntax for input. If the tt(#) is doubled, for example `tt([##16])', then no base prefix is output. Floating point constants are recognized by the presence of a decimal point or an exponent. The decimal point may be the first character of the constant, but the exponent character tt(e) or tt(E) may not, as it will be taken for a parameter name. All numeric parts (before and after the decimal point and in the exponent) may contain underscores after the leading digit for visual guidance; these are ignored in computation. cindex(arithmetic operators) cindex(operators, arithmetic) An arithmetic expression uses nearly the same syntax and associativity of expressions as in C. In the native mode of operation, the following operators are supported (listed in decreasing order of precedence): startsitem() sitem(tt(PLUS() - ! ~ PLUS()PLUS() --))(unary plus/minus, logical NOT, complement, {pre,post}{in,de}crement) sitem(tt(<< >>))(bitwise shift left, right) sitem(tt(&))(bitwise AND) sitem(tt(^))(bitwise XOR) sitem(tt(|))(bitwise OR) sitem(tt(**))(exponentiation) sitem(tt(* / %))(multiplication, division, modulus (remainder)) sitem(tt(PLUS() -))(addition, subtraction) sitem(tt(< > <= >=))(comparison) sitem(tt(== !=))(equality and inequality) sitem(tt(&&))(logical AND) sitem(tt(|| ^^))(logical OR, XOR) sitem(tt(? :))(ternary operator) sitem(tt(= PLUS()= -= *= /= %= &= ^= |= <<= >>= &&= ||= ^^= **=))(assignment) sitem(tt(,))(comma operator) endsitem() The operators `tt(&&)', `tt(||)', `tt(&&=)', and `tt(||=)' are short-circuiting, and only one of the latter two expressions in a ternary operator is evaluated. Note the precedence of the bitwise AND, OR, and XOR operators. With the option tt(C_PRECEDENCES) the precedences (but no other properties) of the operators are altered to be the same as those in most other languages that support the relevant operators: startsitem() sitem(tt(PLUS() - ! ~ PLUS()PLUS() --))(unary plus/minus, logical NOT, complement, {pre,post}{in,de}crement) sitem(tt(**))(exponentiation) sitem(tt(* / %))(multiplication, division, modulus (remainder)) sitem(tt(PLUS() -))(addition, subtraction) sitem(tt(<< >>))(bitwise shift left, right) sitem(tt(< > <= >=))(comparison) sitem(tt(== !=))(equality and inequality) sitem(tt(&))(bitwise AND) sitem(tt(^))(bitwise XOR) sitem(tt(|))(bitwise OR) sitem(tt(&&))(logical AND) sitem(tt(^^))(logical XOR) sitem(tt(||))(logical OR) sitem(tt(? :))(ternary operator) sitem(tt(= PLUS()= -= *= /= %= &= ^= |= <<= >>= &&= ||= ^^= **=))(assignment) sitem(tt(,))(comma operator) endsitem() Note the precedence of exponentiation in both cases is below that of unary operators, hence `tt(-3**2)' evaluates as `tt(9)', not `tt(-9)'. Use parentheses where necessary: `tt(-(3**2))'. This is for compatibility with other shells. cindex(mathematical functions, use of) cindex(functions, math, use of) Mathematical functions can be called with the syntax `var(func)tt(LPAR())var(args)tt(RPAR())', where the function decides if the var(args) is used as a string or a comma-separated list of arithmetic expressions. The shell currently defines no mathematical functions by default, but the module tt(zsh/mathfunc) may be loaded with the tt(zmodload) builtin to provide standard floating point mathematical functions. An expression of the form `tt(##)var(x)' where var(x) is any character sequence such as `tt(a)', `tt(^A)', or `tt(\M-\C-x)' gives the value of this character and an expression of the form `tt(#)var(name)' gives the value of the first character of the contents of the parameter var(name). Character values are according to the character set used in the current locale; for multibyte character handling the option tt(MULTIBYTE) must be set. Note that this form is different from `tt($#)var(name)', a standard parameter substitution which gives the length of the parameter var(name). `tt(#\)' is accepted instead of `tt(##)', but its use is deprecated. Named parameters and subscripted arrays can be referenced by name within an arithmetic expression without using the parameter expansion syntax. For example, example(((val2 = val1 * 2))) assigns twice the value of tt($val1) to the parameter named tt(val2). An internal integer representation of a named parameter can be specified with the tt(integer) builtin. cindex(parameters, integer) cindex(integer parameters) findex(integer, use of) Arithmetic evaluation is performed on the value of each assignment to a named parameter declared integer in this manner. Assigning a floating point number to an integer results in rounding towards zero. cindex(parameters, floating point) cindex(floating point parameters) findex(float, use of) Likewise, floating point numbers can be declared with the tt(float) builtin; there are two types, differing only in their output format, as described for the tt(typeset) builtin. The output format can be bypassed by using arithmetic substitution instead of the parameter substitution, i.e. `tt(${)var(float)tt(})' uses the defined format, but `tt($LPAR()LPAR())var(float)tt(RPAR()RPAR())' uses a generic floating point format. Promotion of integer to floating point values is performed where necessary. In addition, if any operator which requires an integer (`tt(&)', `tt(|)', `tt(^)', `tt(<<)', `tt(>>)' and their equivalents with assignment) is given a floating point argument, it will be silently rounded towards zero except for `tt(~)' which rounds down. Users should beware that, in common with many other programming languages but not software designed for calculation, the evaluation of an expression in zsh is taken a term at a time and promotion of integers to floating point does not occur in terms only containing integers. A typical result of this is that a division such as tt(6/8) is truncated, in this being rounded towards 0. The tt(FORCE_FLOAT) shell option can be used in scripts or functions where floating point evaluation is required throughout. Scalar variables can hold integer or floating point values at different times; there is no memory of the numeric type in this case. If a variable is first assigned in a numeric context without previously being declared, it will be implicitly typed as tt(integer) or tt(float) and retain that type either until the type is explicitly changed or until the end of the scope. This can have unforeseen consequences. For example, in the loop example(for (( f = 0; f < 1; f += 0.1 )); do # use $f done) if tt(f) has not already been declared, the first assignment will cause it to be created as an integer, and consequently the operation `tt(f += 0.1)' will always cause the result to be truncated to zero, so that the loop will fail. A simple fix would be to turn the initialization into `tt(f = 0.0)'. It is therefore best to declare numeric variables with explicit types.
{ "pile_set_name": "Github" }
/* * Copyright 2017 Google * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #import <Foundation/Foundation.h> #import "FIRStorageObservableTask.h" NS_ASSUME_NONNULL_BEGIN /** * FIRStorageDownloadTask implements resumable downloads from an object in Firebase Storage. * Downloads can be returned on completion with a completion handler, and can be monitored * by attaching observers, or controlled by calling FIRStorageTask#pause, FIRStorageTask#resume, * or FIRStorageTask#cancel. * Downloads can currently be returned as NSData in memory, or as an NSURL to a file on disk. * Downloads are performed on a background queue, and callbacks are raised on the developer * specified callbackQueue in FIRStorage, or the main queue if left unspecified. * Currently all uploads must be initiated and managed on the main queue. */ NS_SWIFT_NAME(StorageDownloadTask) @interface FIRStorageDownloadTask : FIRStorageObservableTask <FIRStorageTaskManagement> @end NS_ASSUME_NONNULL_END
{ "pile_set_name": "Github" }
# Return To The Roots "Return To The Roots" is a fan-project, which aims to renew the original The Settlers 2. We aim to extend new features such as a multiplayer mode via internet as well as the support for modern hardware and several operating systems like Windows XP/Vista/Seven, Linux and MacOS X. Likewise we want to invent some smaller upgrades. Unfortunately it is necessary to rewrite the whole game, but we will stick to the original graphics and sounds, because they are still common and nice to be heard or seen. So you will still need an original "The Settlers 2 Gold Edition" version to play Return To The Roots. see more information on <http://www.rttr.info> ## Current Build Info Travis CI: [![Travis CI Build Info](https://travis-ci.com/Return-To-The-Roots/s25client.svg?branch=master)](https://travis-ci.com/Return-To-The-Roots/s25client) Appveyor: [![Appveyor CI Build Info](https://ci.appveyor.com/api/projects/status/ufw8v9mi80va1me7/branch/master?svg=true)](https://ci.appveyor.com/project/Flow86/s25client/branch/master) Coverage: [![Coverage Status](https://coveralls.io/repos/github/Return-To-The-Roots/s25client/badge.svg?branch=master)](https://coveralls.io/github/Return-To-The-Roots/s25client?branch=master) / [![codecov](https://codecov.io/gh/Return-To-The-Roots/s25client/branch/master/graph/badge.svg)](https://codecov.io/gh/Return-To-The-Roots/s25client) ## How to install - Download the game for your OS at [Downloads](https://www.rttr.info/index.php?com=dynamic&mod=2) - stable: Usually more stable - nightly: Latest features and bug fixes, but might be broken sometimes - Extract into a folder of your choice - Locate the file `put your S2-Installation in here` in that folder (usually at the root or in S2) - Copy the DATA and GFX folder from the original The Settlers II Gold into the folder containing the above file - Start `rttr.bat`/`rttr.sh` or the bundle (OSX only) to auto-update and start the game - Alternatively start `s25client` directly, but updates and music might be missing - WARNING: Do not use symlinks/junction points/... for subfolders of your installation. Putting RttR in a symlinked folder should work though. ## How to build ### On Linux or Darwin/MacOSX #### Prerequisite Linux - C++14 compatible compiler (e.g. GCC-6) - cmake - git - libboost-dev (at least v1.64.0, i.e <http://www.boost.org/>) or only: libboost-test-dev libboost-locale-dev, libboost-iostreams-dev, libboost-filesystem-dev, libboost-program-options-dev (at least v1.64.0) - libsdl2-dev - libsdl2-mixer-dev - libcurl-dev (in libcurl4-openssl-dev) - libbz2-dev - lua5.2-dev - gettext - libminiupnpc-dev All of them can be installed with the package manager. #### Prerequisite MacOSX - cmake - git - boost - sdl2 - sdl2_mixer - gettext (make sure it is in your path with e.g. `brew link --force gettext`) - miniupnpc All of them can be installed via homebrew #### Prerequisites with Nix Nix users can open a nix-shell to get a development environment with all packages ready. #### Checkout and build ```bash git clone --recursive https://github.com/Return-To-The-Roots/s25client s25client cd s25client nix-shell # Optional, for Nix users only mkdir -p build && cd build cmake -DCMAKE_BUILD_TYPE=Release .. make ``` Note: by using the `-G` option of `cmake` you can specify a generator, e.g. `cmake -G Xcode -DCMAKE_BUILD_TYPE=Release ..` will generate an Xcode project. Please check `cmake --help` for more options. #### Optimizations There are various CMake options to control the build and optimization including ARM (Raspberry PI etc.) related ones. Examples: - RTTR_ENABLE_OPTIMIZATIONS/RTTR_ENABLE_WERROR - RTTR_OPTIMIZATION_VECTOR_EXT (Non-Windows x86/x64 only) - RTTR_OPTIMIZATION_TUNE (Non-Windows only) - RTTR_TARGET_BOARD (ARM only) See the description in CMake-GUI/ccmake for details. Note that due to the use of submodules you always need to `git pull && git submodule update --init --recursive` to get the latest version. (The `--init` and `--recursive` arguments are only required should we add *new* submodules to the existing set.) #### Tests Especially for developing you should build in Debug mode (`-DCMAKE_BUILD_TYPE=Debug`) and run the tests after executing `make` via `make test` or `ctest --output-on-failure`. There is also an option to enable checks for undefined behavior (UBSAN) and memory errors (ASAN) like use-after-free or leaks. Just pass `-DRTTR_ENABLE_SANITIZERS=ON` to CMake and use a recent GCC or Clang compiler to build. Then just run (tests or application) as usual. **Note**: Boost.Endian < 1.67 is known to have UB so use at least 1.67 when running the sanitizers. ### On Windows #### Prerequisites - cmake (i.e from <http://www.cmake.org/download/>) - boost (i.e from <http://www.boost.org/>) - Visual Studio (at least 2017, you can get the community edition for free) - Git Client (i.e TortoiseGit) #### Steps - Clone GIT Repository from <https://github.com/Return-To-The-Roots/s25client> - Using Git bash: ```bash git clone --recursive https://github.com/Return-To-The-Roots/s25client s25client ``` - **OR** using TortoiseGit: - Rightclick -> "Git clone..." - Put in <https://github.com/Return-To-The-Roots/s25client> as URL - Select "Directory" to clone to - press OK - Rightclick on the newly created folder -> TortoiseGit-> Submodule Update - Make sure all modules are selected and "Initialize submodules (--init)" is checked - press OK - If you haven't installed boost, install boost Fast Way: - extract boost-1.64.zip (i.e to external/boost, so that external/boost/bootstrap.bat exist) - run that "bootstrap.bat" - run created "b2.exe": this should build boost Notice: if you have multiple Visual Studio versions installed, use the latest one with the "toolset"-parameter. i.e "b2 toolset=msvc-14.0" for Visual Studio 2015 - run "b2 install --prefix=%CD%": this should install everything so the system can find it Notice: Don't forget to add the toolset parameter if you already used it before - Use cmake-gui: - "Where is the source code": Select checked out directory - "Where to build the binaries": Select "build" directory (create if required) - Press configure - Select your compiler version (i.e Visual Studio 2015 x64) - If it can't find boost: - "Add Entry" - Enter as "Name" "BOOST_ROOT" (exact casing!) - Select for "Type" "PATH" - Enter boost installation path for "Value" - Press ok - Press generate - Open and use build/s25client.sln -- For advanced info or help see [FAQ in the wiki](https://github.com/Return-To-The-Roots/s25client/wiki/How-to-install-RttR) or <http://www.rttr.info>
{ "pile_set_name": "Github" }
/** * Module dependencies. */ var Route = require('./route'); var Layer = require('./layer'); var methods = require('methods'); var debug = require('debug')('express:router'); var parseUrl = require('parseurl'); /** * Initialize a new `Router` with the given `options`. * * @param {Object} options * @return {Router} which is an callable function * @api public */ var proto = module.exports = function(options) { options = options || {}; function router(req, res, next) { router.handle(req, res, next); } // mixin Router class functions router.__proto__ = proto; router.params = {}; router._params = []; router.caseSensitive = options.caseSensitive; router.strict = options.strict; router.stack = []; return router; }; /** * Map the given param placeholder `name`(s) to the given callback. * * Parameter mapping is used to provide pre-conditions to routes * which use normalized placeholders. For example a _:user_id_ parameter * could automatically load a user's information from the database without * any additional code, * * The callback uses the same signature as middleware, the only difference * being that the value of the placeholder is passed, in this case the _id_ * of the user. Once the `next()` function is invoked, just like middleware * it will continue on to execute the route, or subsequent parameter functions. * * Just like in middleware, you must either respond to the request or call next * to avoid stalling the request. * * app.param('user_id', function(req, res, next, id){ * User.find(id, function(err, user){ * if (err) { * return next(err); * } else if (!user) { * return next(new Error('failed to load user')); * } * req.user = user; * next(); * }); * }); * * @param {String} name * @param {Function} fn * @return {app} for chaining * @api public */ proto.param = function(name, fn){ // param logic if ('function' == typeof name) { this._params.push(name); return; } // apply param functions var params = this._params; var len = params.length; var ret; if (name[0] === ':') { name = name.substr(1); } for (var i = 0; i < len; ++i) { if (ret = params[i](name, fn)) { fn = ret; } } // ensure we end up with a // middleware function if ('function' != typeof fn) { throw new Error('invalid param() call for ' + name + ', got ' + fn); } (this.params[name] = this.params[name] || []).push(fn); return this; }; /** * Dispatch a req, res into the router. * * @api private */ proto.handle = function(req, res, done) { var self = this; debug('dispatching %s %s', req.method, req.url); var method = req.method.toLowerCase(); var search = 1 + req.url.indexOf('?'); var pathlength = search ? search - 1 : req.url.length; var fqdn = 1 + req.url.substr(0, pathlength).indexOf('://'); var protohost = fqdn ? req.url.substr(0, req.url.indexOf('/', 2 + fqdn)) : ''; var idx = 0; var removed = ''; var slashAdded = false; // store options for OPTIONS request // only used if OPTIONS request var options = []; // middleware and routes var stack = self.stack; // for options requests, respond with a default if nothing else responds if (method === 'options') { var old = done; done = function(err) { if (err || options.length === 0) return old(err); var body = options.join(','); return res.set('Allow', body).send(body); }; } (function next(err) { if (err === 'route') { err = undefined; } var layer = stack[idx++]; if (!layer) { return done(err); } if (slashAdded) { req.url = req.url.substr(1); slashAdded = false; } req.url = protohost + removed + req.url.substr(protohost.length); req.originalUrl = req.originalUrl || req.url; removed = ''; try { var path = parseUrl(req).pathname; if (undefined == path) path = '/'; if (!layer.match(path)) return next(err); // route object and not middleware var route = layer.route; // if final route, then we support options if (route) { // we don't run any routes with error first if (err) { return next(err); } req.route = route; // we can now dispatch to the route if (method === 'options' && !route.methods['options']) { options.push.apply(options, route._options()); } } req.params = layer.params; // this should be done for the layer return self.process_params(layer, req, res, function(err) { if (err) { return next(err); } if (route) { return layer.handle(req, res, next); } trim_prefix(); }); } catch (err) { next(err); } function trim_prefix() { var c = path[layer.path.length]; if (c && '/' != c && '.' != c) return next(err); // Trim off the part of the url that matches the route // middleware (.use stuff) needs to have the path stripped debug('trim prefix (%s) from url %s', removed, req.url); removed = layer.path; req.url = protohost + req.url.substr(protohost.length + removed.length); // Ensure leading slash if (!fqdn && '/' != req.url[0]) { req.url = '/' + req.url; slashAdded = true; } debug('%s %s : %s', layer.handle.name || 'anonymous', layer.path, req.originalUrl); var arity = layer.handle.length; if (err) { if (arity === 4) { layer.handle(err, req, res, next); } else { next(err); } } else if (arity < 4) { layer.handle(req, res, next); } else { next(err); } } })(); }; /** * Process any parameters for the route. * * @api private */ proto.process_params = function(route, req, res, done) { var params = this.params; // captured parameters from the route, keys and values var keys = route.keys; // fast track if (!keys || keys.length === 0) { return done(); } var i = 0; var paramIndex = 0; var key; var paramVal; var paramCallbacks; // process params in order // param callbacks can be async function param(err) { if (err) { return done(err); } if (i >= keys.length ) { return done(); } paramIndex = 0; key = keys[i++]; paramVal = key && req.params[key.name]; paramCallbacks = key && params[key.name]; try { if (paramCallbacks && undefined !== paramVal) { return paramCallback(); } else if (key) { return param(); } } catch (err) { return done(err); } done(); } // single param callbacks function paramCallback(err) { var fn = paramCallbacks[paramIndex++]; if (err || !fn) return param(err); fn(req, res, paramCallback, paramVal, key.name); } param(); }; /** * Use the given middleware function, with optional path, defaulting to "/". * * Use (like `.all`) will run for any http METHOD, but it will not add * handlers for those methods so OPTIONS requests will not consider `.use` * functions even if they could respond. * * The other difference is that _route_ path is stripped and not visible * to the handler function. The main effect of this feature is that mounted * handlers can operate without any code changes regardless of the "prefix" * pathname. * * @param {String|Function} route * @param {Function} fn * @return {app} for chaining * @api public */ proto.use = function(route, fn){ // default route to '/' if ('string' != typeof route) { fn = route; route = '/'; } if (typeof fn !== 'function') { var type = {}.toString.call(fn); var msg = 'Router.use() requires callback functions but got a ' + type; throw new Error(msg); } // strip trailing slash if ('/' == route[route.length - 1]) { route = route.slice(0, -1); } var layer = new Layer(route, { sensitive: this.caseSensitive, strict: this.strict, end: false }, fn); // add the middleware debug('use %s %s', route || '/', fn.name || 'anonymous'); this.stack.push(layer); return this; }; /** * Create a new Route for the given path. * * Each route contains a separate middleware stack and VERB handlers. * * See the Route api documentation for details on adding handlers * and middleware to routes. * * @param {String} path * @return {Route} * @api public */ proto.route = function(path){ var route = new Route(path); var layer = new Layer(path, { sensitive: this.caseSensitive, strict: this.strict, end: true }, route.dispatch.bind(route)); layer.route = route; this.stack.push(layer); return route; }; // create Router#VERB functions methods.concat('all').forEach(function(method){ proto[method] = function(path){ var route = this.route(path) route[method].apply(route, [].slice.call(arguments, 1)); return this; }; });
{ "pile_set_name": "Github" }
#!/bin/bash #MALLET_HOME= #JAVA_HOME= if ! [[ -d $JAVA_HOME ]] ; then echo "You need to set the JAVA_HOME environement variable to" echo "a directory in order for this to work. This script will" echo "execute \$JAVA_HOME/bin/java. You can also edit this " echo "script to set it here" exit fi if [[ -z $MALLET_HOME ]]; then MALLET_HOME=`dirname $0`/.. echo set MALLET_HOME to $MALLET_HOME >&2 fi if ! [[ -d $MALLET_HOME ]] ; then echo "You need to set the MALLET_HOME environement variable to the directory" echo "where mallet was unpacked in order for this to work. Alternatively" echo "edit this script to set it here." exit fi PYCACHE=`echo ~/.mallet/mallethon/` if ! [[ -e $PYCACHE ]] ; then if ! mkdir -p $PYCACHE ; then echo "Failed to create a chache directory for mallethon:" echo "please edit this script to set:" echo "PYCACHE=$PYCACHE" echo "to something else" exit fi fi if ! [[ -d $PYCACHE ]] ; then echo "The default location of $PYCACHE exists but is not a directory" echo "please edit this script to set:" echo "PYCACHE=$PYCACHE" echo "to something else" exit fi PYPATH="$MALLET_HOME/lib/jython/Lib/:$MALLET_HOME/lib/jython/:$MALLET_HOME/class/" if [ ! -z $CLASSPATH ] ; then CP="$MALLET_HOME/lib/jython.jar:$MALLET_HOME/lib/mallet-deps.jar:$PYPATH:$CLASSPATH"; else CP="$MALLET_HOME/lib/jython.jar:$MALLET_HOME/lib/mallet-deps.jar:$PYPATH"; fi echo "Using classpath: $CP" >&2 echo $JAVA_HOME/bin/java -Xmx1800m -Dpython.cachedir=$PYCACHE -Dpython.path=$PYPATH -classpath $CP "org.python.util.jython" "$@" >&2 $JAVA_HOME/bin/java -Xmx1800m -Dpython.cachedir=$PYCACHE -Dpython.path=$PYPATH -classpath $CP "org.python.util.jython" "$@"
{ "pile_set_name": "Github" }
/* * File: test.c * Author: Vincent Gramoli <[email protected]>, * Vasileios Trigonakis <[email protected]> * Description: * test.c is part of ASCYLIB * * Copyright (c) 2014 Vasileios Trigonakis <[email protected]>, * Tudor David <[email protected]> * Distributed Programming Lab (LPD), EPFL * * ASCYLIB 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, version 2 * of the License. * * 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. * */ #include "intset.h" #include "utils.h" __thread unsigned long* seeds; int verbose = 0; ALIGNED(64) uint8_t running[64]; typedef ALIGNED(64) struct thread_data { skey_t first; long range; int update; int unit_tx; int alternate; int effective; unsigned long nb_add; unsigned long nb_added; unsigned long nb_remove; unsigned long nb_removed; unsigned long nb_contains; unsigned long nb_found; unsigned long nb_aborts; unsigned long nb_aborts_locked_read; unsigned long nb_aborts_locked_write; unsigned long nb_aborts_validate_read; unsigned long nb_aborts_validate_write; unsigned long nb_aborts_validate_commit; unsigned long nb_aborts_invalid_memory; unsigned long max_retries; unsigned int seed; intset_l_t *set; barrier_t *barrier; int id; uint8_t padding[16]; } thread_data_t; /* extern __thread size_t num_pause, num_total, num_xtest; */ void* test(void *data) { PF_MSG(0, "rand_range"); PF_MSG(1, "malloc"); PF_MSG(2, "free"); int unext, last = -1; skey_t val = 0; thread_data_t *d = (thread_data_t *)data; int transactional = d->unit_tx; set_cpu(d->id); ssalloc_init(); PF_CORRECTION; seeds = seed_rand(); #if defined(HTICKET) init_thread_htlocks(the_cores[d->id]); #elif defined(CLH) init_clh_thread(&clh_local_p); #endif /* Wait on barrier */ barrier_cross(d->barrier); /* Is the first op an update? */ unext = (rand_range_re(&d->seed, 100) - 1 < d->update); /* while (stop == 0) */ while (*running) { if (unext) { // update if (last < 0) { // add val = rand_range_re(&d->seed, d->range); if (set_add_l(d->set, val, val, TRANSACTIONAL)) { d->nb_added++; last = val; } d->nb_add++; } else { // remove if (d->alternate) { // alternate mode if (set_remove_l(d->set, last, TRANSACTIONAL)) { d->nb_removed++; } last = -1; } else { val = rand_range_re(&d->seed, d->range); if (set_remove_l(d->set, val, TRANSACTIONAL)) { d->nb_removed++; last = -1; } } d->nb_remove++; } } else { // read if (d->alternate) { if (d->update == 0) { if (last < 0) { val = d->first; last = val; } else { // last >= 0 val = rand_range_re(&d->seed, d->range); last = -1; } } else { // update != 0 if (last < 0) { val = rand_range_re(&d->seed, d->range); //last = val; } else { val = last; } } } else val = rand_range_re(&d->seed, d->range); if (set_contains_l(d->set, val, TRANSACTIONAL)) d->nb_found++; d->nb_contains++; } /* Is the next op an update? */ if (d->effective) { // a failed remove/add is a read-only tx unext = ((100 * (d->nb_added + d->nb_removed)) < (d->update * (d->nb_add + d->nb_remove + d->nb_contains))); } else { // remove/add (even failed) is considered an update unext = (rand_range_re(&d->seed, 100) - 1 < d->update); } } PF_PRINT; /* printf("[%d] tot: %10lu / pause: %10lu / ratio: %5.2f / xtests: %lu\n", */ /* d->id, num_total, num_pause, 1.0*num_pause/num_total, num_xtest); */ return NULL; } int main(int argc, char **argv) { #if defined(CLH) init_clh_thread(&clh_local_p); #endif set_cpu(0); ssalloc_init(); seeds = seed_rand(); struct option long_options[] = { // These options don't set a flag {"help", no_argument, NULL, 'h'}, {"verbose", no_argument, NULL, 'v'}, {"duration", required_argument, NULL, 'd'}, {"initial-size", required_argument, NULL, 'i'}, {"num-threads", required_argument, NULL, 'n'}, {"range", required_argument, NULL, 'r'}, {"seed", required_argument, NULL, 's'}, {"update-rate", required_argument, NULL, 'u'}, {"load-factor", required_argument, NULL, 'l'}, {"unit-tx", required_argument, NULL, 'x'}, {NULL, 0, NULL, 0} }; intset_l_t *set; int i, c, size; skey_t last = 0; skey_t val = 0; unsigned long reads, effreads, updates, effupds; #if defined(STM) unsigned long aborts, aborts_locked_read, aborts_locked_write, aborts_validate_read, aborts_validate_write, aborts_validate_commit, aborts_invalid_memory, max_retries; #endif thread_data_t *data; pthread_t *threads; pthread_attr_t attr; barrier_t barrier; struct timeval start, end; struct timespec timeout; int duration = DEFAULT_DURATION; int initial = DEFAULT_INITIAL; int nb_threads = DEFAULT_NB_THREADS; long range = DEFAULT_RANGE; int seed = 0; int update = DEFAULT_UPDATE; int unit_tx = DEFAULT_LOCKTYPE; int alternate = DEFAULT_ALTERNATE; int effective = DEFAULT_EFFECTIVE; sigset_t block_set; while(1) { i = 0; c = getopt_long(argc, argv, "hvAf:d:i:n:r:s:u:l:x:" ,long_options, &i); if(c == -1) break; if(c == 0 && long_options[i].flag == 0) c = long_options[i].val; switch(c) { case 0: /* Flag is automatically set */ break; case 'h': printf("ASCYLIB -- stress test " "\n" "\n" "Usage:\n" " %s [options...]\n" "\n" "Options:\n" " -h, --help\n" " Print this message\n" " -v, --verbose\n" " Print detailed (per core) results\n" " -A, --alternate (default="XSTR(DEFAULT_ALTERNATE)")\n" " Consecutive insert/remove target the same value\n" " -f, --effective <int>\n" " update txs must effectively write (0=trial, 1=effective, default=" XSTR(DEFAULT_EFFECTIVE) ")\n" " -d, --duration <int>\n" " Test duration in milliseconds (0=infinite, default=" XSTR(DEFAULT_DURATION) ")\n" " -i, --initial-size <int>\n" " Number of elements to insert before test (default=" XSTR(DEFAULT_INITIAL) ")\n" " -n, --num-threads <int>\n" " Number of threads (default=" XSTR(DEFAULT_NB_THREADS) ")\n" " -r, --range <int>\n" " Range of integer values inserted in set (default=" XSTR(DEFAULT_RANGE) ")\n" " -s, --seed <int>\n" " RNG seed (0=time-based, default=" XSTR(DEFAULT_SEED) ")\n" " -u, --update-rate <int>\n" " Percentage of update transactions (default=" XSTR(DEFAULT_UPDATE) ")\n" " -x, --lock-based algorithm (default=1)\n" " Use lock-based algorithm\n" " 1 = lock-coupling,\n" " 2 = lazy algorithm\n" , argv[0]); exit(0); case 'A': alternate = 1; break; case 'v': verbose = 1; break; case 'f': effective = atoi(optarg); break; case 'd': duration = atoi(optarg); break; case 'i': initial = atoi(optarg); break; case 'n': nb_threads = atoi(optarg); break; case 'r': range = atol(optarg); break; case 's': seed = atoi(optarg); break; case 'u': update = atoi(optarg); break; case 'l': break; case 'x': unit_tx = atoi(optarg); break; case '?': printf("Use -h or --help for help\n"); exit(0); default: exit(1); } } assert(duration >= 0); assert(initial >= 0); assert(nb_threads > 0); assert(range > 0 && range >= initial); assert(update >= 0 && update <= 100); printf("Set type : linked list\n"); printf("Duration : %d\n", duration); printf("Initial size : %d\n", initial); printf("Nb threads : %d\n", nb_threads); printf("Value range : %ld\n", range); printf("Seed : %d\n", seed); printf("Update rate : %d\n", update); printf("Lock alg : %d\n", unit_tx); printf("Alternate : %d\n", alternate); printf("Effective : %d\n", effective); printf("Type sizes : int=%d/long=%d/ptr=%d/word=%d\n", (int)sizeof(int), (int)sizeof(long), (int)sizeof(void *), (int)sizeof(uintptr_t)); timeout.tv_sec = duration / 1000; timeout.tv_nsec = (duration % 1000) * 1000000; if ((data = (thread_data_t *)malloc(nb_threads * sizeof(thread_data_t))) == NULL) { perror("malloc"); exit(1); } if ((threads = (pthread_t *)malloc(nb_threads * sizeof(pthread_t))) == NULL) { perror("malloc"); exit(1); } if (seed == 0) srand((int)time(0)); else srand(seed); set = set_new_l(); /* stop = 0; */ *running = 1; /* printf("Initializing STM\n"); */ size_t ten_perc = initial / 10, tens = 1; size_t ten_perc_nxt = ten_perc; /* Populate set */ printf("Adding %d entries to set\n", initial); if (initial < 10000) { i = 0; while (i < initial) { val = rand_range(range); if (set_add_l(set, val, val, 0)) { if (i == ten_perc_nxt) { printf("%02lu%% ", tens * 10); fflush(stdout); tens++; ten_perc_nxt = tens * ten_perc; } i++; } } } else { for (i = initial; i > 0; i--) { set_add_l(set, i, i, 0); } } printf("\n"); size = set_size_l(set); printf("Set size : %d\n", size); /* Access set from all threads */ barrier_init(&barrier, nb_threads + 1); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); printf("Creating threads: "); for (i = 0; i < nb_threads; i++) { printf("%d,", i); data[i].first = last; data[i].range = range; data[i].update = update; data[i].alternate = alternate; data[i].unit_tx = unit_tx; data[i].alternate = alternate; data[i].effective = effective; data[i].nb_add = 0; data[i].nb_added = 0; data[i].nb_remove = 0; data[i].nb_removed = 0; data[i].nb_contains = 0; data[i].nb_found = 0; data[i].nb_aborts = 0; data[i].nb_aborts_locked_read = 0; data[i].nb_aborts_locked_write = 0; data[i].nb_aborts_validate_read = 0; data[i].nb_aborts_validate_write = 0; data[i].nb_aborts_validate_commit = 0; data[i].nb_aborts_invalid_memory = 0; data[i].max_retries = 0; data[i].seed = rand(); data[i].set = set; data[i].barrier = &barrier; data[i].id = i; if (pthread_create(&threads[i], &attr, test, (void *)(&data[i])) != 0) { fprintf(stderr, "Error creating thread\n"); exit(1); } } printf("\n"); pthread_attr_destroy(&attr); /* Start threads */ barrier_cross(&barrier); printf("STARTING...\n"); gettimeofday(&start, NULL); if (duration > 0) { nanosleep(&timeout, NULL); } else { sigemptyset(&block_set); sigsuspend(&block_set); } /* AO_store_full(&stop, 1); */ *running = 0; gettimeofday(&end, NULL); printf("STOPPING...\n"); /* Wait for thread completion */ for (i = 0; i < nb_threads; i++) { if (pthread_join(threads[i], NULL) != 0) { fprintf(stderr, "Error waiting for thread completion\n"); exit(1); } } duration = (end.tv_sec * 1000 + end.tv_usec / 1000) - (start.tv_sec * 1000 + start.tv_usec / 1000); #if defined(STM) aborts = 0; aborts_locked_read = 0; aborts_locked_write = 0; aborts_validate_read = 0; aborts_validate_write = 0; aborts_validate_commit = 0; aborts_invalid_memory = 0; max_retries = 0; #endif reads = 0; effreads = 0; updates = 0; effupds = 0; for (i = 0; i < nb_threads; i++) { if (verbose) { printf("Thread %d\n", i); printf(" #add : %lu\n", data[i].nb_add); printf(" #added : %lu\n", data[i].nb_added); printf(" #remove : %lu\n", data[i].nb_remove); printf(" #removed : %lu\n", data[i].nb_removed); printf(" #contains : %lu\n", data[i].nb_contains); printf(" #found : %lu\n", data[i].nb_found); } #if defined(STM) if (verbose) { printf(" #aborts : %lu\n", data[i].nb_aborts); printf(" #lock-r : %lu\n", data[i].nb_aborts_locked_read); printf(" #lock-w : %lu\n", data[i].nb_aborts_locked_write); printf(" #val-r : %lu\n", data[i].nb_aborts_validate_read); printf(" #val-w : %lu\n", data[i].nb_aborts_validate_write); printf(" #val-c : %lu\n", data[i].nb_aborts_validate_commit); printf(" #inv-mem : %lu\n", data[i].nb_aborts_invalid_memory); printf(" Max retries : %lu\n", data[i].max_retries); } aborts += data[i].nb_aborts; aborts_locked_read += data[i].nb_aborts_locked_read; aborts_locked_write += data[i].nb_aborts_locked_write; aborts_validate_read += data[i].nb_aborts_validate_read; aborts_validate_write += data[i].nb_aborts_validate_write; aborts_validate_commit += data[i].nb_aborts_validate_commit; aborts_invalid_memory += data[i].nb_aborts_invalid_memory; if (max_retries < data[i].max_retries) max_retries = data[i].max_retries; #endif reads += data[i].nb_contains; effreads += data[i].nb_contains + (data[i].nb_add - data[i].nb_added) + (data[i].nb_remove - data[i].nb_removed); updates += (data[i].nb_add + data[i].nb_remove); effupds += data[i].nb_removed + data[i].nb_added; //size += data[i].diff; size += data[i].nb_added - data[i].nb_removed; } int size_after = set_size_l(set); printf("Set size : %d (expected: %d)\n", size_after, size); assert(size_after == size); printf("Duration : %d (ms)\n", duration); printf("#txs : %lu (%f / s)\n", reads + updates, (reads + updates) * 1000.0 / duration); printf("#read txs : "); if (effective) { printf("%lu (%f / s)\n", effreads, effreads * 1000.0 / duration); printf(" #contains : %lu (%f / s)\n", reads, reads * 1000.0 / duration); } else printf("%lu (%f / s)\n", reads, reads * 1000.0 / duration); printf("#eff. upd rate: %f \n", 100.0 * effupds / (effupds + effreads)); printf("#update txs : "); if (effective) { printf("%lu (%f / s)\n", effupds, effupds * 1000.0 / duration); printf(" #upd trials : %lu (%f / s)\n", updates, updates * 1000.0 / duration); } else printf("%lu (%f / s)\n", updates, updates * 1000.0 / duration); #if defined(STM) printf("#aborts : %lu (%f / s)\n", aborts, aborts * 1000.0 / duration); printf(" #lock-r : %lu (%f / s)\n", aborts_locked_read, aborts_locked_read * 1000.0 / duration); printf(" #lock-w : %lu (%f / s)\n", aborts_locked_write, aborts_locked_write * 1000.0 / duration); printf(" #val-r : %lu (%f / s)\n", aborts_validate_read, aborts_validate_read * 1000.0 / duration); printf(" #val-w : %lu (%f / s)\n", aborts_validate_write, aborts_validate_write * 1000.0 / duration); printf(" #val-c : %lu (%f / s)\n", aborts_validate_commit, aborts_validate_commit * 1000.0 / duration); printf(" #inv-mem : %lu (%f / s)\n", aborts_invalid_memory, aborts_invalid_memory * 1000.0 / duration); printf("Max retries : %lu\n", max_retries); #endif /* Delete set */ set_delete_l(set); free(threads); free(data); return 0; }
{ "pile_set_name": "Github" }
// // Object+StorageEntityType.swift // StorageKit // // Copyright (c) 2017 StorageKit (https://github.com/StorageKit) // // 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. // import RealmSwift extension Object: StorageEntityType { @nonobjc public static var name: String { return self.description() } }
{ "pile_set_name": "Github" }
define( //begin v1.x content { "group": ",", "percentSign": "%", "exponential": "E", "scientificFormat": "#E0", "percentFormat": "#,##0%", "list": ";", "infinity": "∞", "minusSign": "-", "decimal": ".", "nan": "NaN", "perMille": "‰", "decimalFormat": "#,##0.###", "currencyFormat": "#,##0.00 €", "plusSign": "+", "decimalFormat-long": "‏000 ט׹יליון", "decimalFormat-short": "000T" } //end v1.x content );
{ "pile_set_name": "Github" }
/* * Copyright (c) 2012 cocos2d-x.org * http://www.cocos2d-x.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. * * * Converted to c++ / cocos2d-x by Angus C */ #include "CCInvocation.h" NS_CC_EXT_BEGIN CCInvocation* CCInvocation::create(CCObject* target, SEL_CCControlHandler action, CCControlEvent controlEvent) { CCInvocation* pRet = new CCInvocation(target, action, controlEvent); if (pRet != NULL) { pRet->autorelease(); } return pRet; } CCInvocation::CCInvocation(CCObject* target, SEL_CCControlHandler action, CCControlEvent controlEvent) { m_target=target; m_action=action; m_controlEvent=controlEvent; } void CCInvocation::invoke(CCObject* sender) { if (m_target && m_action) { (m_target->*m_action)(sender, m_controlEvent); } } NS_CC_EXT_END
{ "pile_set_name": "Github" }
/* Copyright (C) 1991-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #include <errno.h> #include <time.h> #define SECS_PER_HOUR (60 * 60) #define SECS_PER_DAY (SECS_PER_HOUR * 24) /* Compute the `struct tm' representation of *T, offset OFFSET seconds east of UTC, and store year, yday, mon, mday, wday, hour, min, sec into *TP. Return nonzero if successful. */ int __offtime (const time_t *t, long int offset, struct tm *tp) { time_t days, rem, y; const unsigned short int *ip; days = *t / SECS_PER_DAY; rem = *t % SECS_PER_DAY; rem += offset; while (rem < 0) { rem += SECS_PER_DAY; --days; } while (rem >= SECS_PER_DAY) { rem -= SECS_PER_DAY; ++days; } tp->tm_hour = rem / SECS_PER_HOUR; rem %= SECS_PER_HOUR; tp->tm_min = rem / 60; tp->tm_sec = rem % 60; /* January 1, 1970 was a Thursday. */ tp->tm_wday = (4 + days) % 7; if (tp->tm_wday < 0) tp->tm_wday += 7; y = 1970; #define DIV(a, b) ((a) / (b) - ((a) % (b) < 0)) #define LEAPS_THRU_END_OF(y) (DIV (y, 4) - DIV (y, 100) + DIV (y, 400)) while (days < 0 || days >= (__isleap (y) ? 366 : 365)) { /* Guess a corrected year, assuming 365 days per year. */ time_t yg = y + days / 365 - (days % 365 < 0); /* Adjust DAYS and Y to match the guessed year. */ days -= ((yg - y) * 365 + LEAPS_THRU_END_OF (yg - 1) - LEAPS_THRU_END_OF (y - 1)); y = yg; } tp->tm_year = y - 1900; if (tp->tm_year != y - 1900) { /* The year cannot be represented due to overflow. */ __set_errno (EOVERFLOW); return 0; } tp->tm_yday = days; ip = __mon_yday[__isleap(y)]; for (y = 11; days < (long int) ip[y]; --y) continue; days -= ip[y]; tp->tm_mon = y; tp->tm_mday = days + 1; return 1; }
{ "pile_set_name": "Github" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_35) on Tue Oct 16 22:49:47 ICT 2012 --> <TITLE> org.apache.fop.util (Apache FOP 1.1 API) </TITLE> <META NAME="date" CONTENT="2012-10-16"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="org.apache.fop.util (Apache FOP 1.1 API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> fop 1.1</EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../org/apache/fop/traits/package-summary.html"><B>PREV PACKAGE</B></A>&nbsp; &nbsp;<A HREF="../../../../org/apache/fop/util/bitmap/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?org/apache/fop/util/package-summary.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <H2> Package org.apache.fop.util </H2> Various utility classes (I/O, codecs, color support, service discovers etc.). <P> <B>See:</B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<A HREF="#package_description"><B>Description</B></A> <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Interface Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/apache/fop/util/ContentHandlerFactory.html" title="interface in org.apache.fop.util">ContentHandlerFactory</A></B></TD> <TD>Factory interface implemented by classes that can instantiate ContentHandler subclasses which parse a SAX stream into Java objects.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/apache/fop/util/ContentHandlerFactory.ObjectBuiltListener.html" title="interface in org.apache.fop.util">ContentHandlerFactory.ObjectBuiltListener</A></B></TD> <TD>EventListener interface for objects which want to get notified when ContentHandler implementing the ObjectSource interface has finished parsing.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/apache/fop/util/ContentHandlerFactory.ObjectSource.html" title="interface in org.apache.fop.util">ContentHandlerFactory.ObjectSource</A></B></TD> <TD>Interface that ContentHandler implementations that parse Java objects from XML can implement to return these objects.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/apache/fop/util/XMLConstants.html" title="interface in org.apache.fop.util">XMLConstants</A></B></TD> <TD>A collection of constants for XML handling.</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Class Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/apache/fop/util/AbstractPaintingState.html" title="class in org.apache.fop.util">AbstractPaintingState</A></B></TD> <TD>A base class which holds information about the current painting state.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/apache/fop/util/BreakUtil.html" title="class in org.apache.fop.util">BreakUtil</A></B></TD> <TD>A utility class for manipulating break classes (the break-before and break-after properties).</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/apache/fop/util/CharUtilities.html" title="class in org.apache.fop.util">CharUtilities</A></B></TD> <TD>This class provides utilities to distinguish various kinds of Unicode whitespace and to get character widths in a given FontState.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/apache/fop/util/CloseBlockerOutputStream.html" title="class in org.apache.fop.util">CloseBlockerOutputStream</A></B></TD> <TD>This is a decorator to block calls to close() to the underlying stream.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/apache/fop/util/ColorExt.html" title="class in org.apache.fop.util">ColorExt</A></B></TD> <TD><B>Deprecated.</B>&nbsp;<I>Replaced by <CODE>ColorWithAlternatives</CODE></I></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/apache/fop/util/ColorProfileUtil.html" title="class in org.apache.fop.util">ColorProfileUtil</A></B></TD> <TD><B>Deprecated.</B>&nbsp;<I>use org.apache.xmlgraphics.java2d.color.profile.ColorProfileUtil directly</I></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/apache/fop/util/ColorSpaceCache.html" title="class in org.apache.fop.util">ColorSpaceCache</A></B></TD> <TD>Map with cached ICC based ColorSpace objects.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/apache/fop/util/ColorUtil.html" title="class in org.apache.fop.util">ColorUtil</A></B></TD> <TD>Generic Color helper class.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/apache/fop/util/ColorWithFallback.html" title="class in org.apache.fop.util">ColorWithFallback</A></B></TD> <TD>This class is a <CODE>Color</CODE> subclass adding a fallback color that FOP uses to re-serialize color specifications as textual functions.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/apache/fop/util/CommandLineLogger.html" title="class in org.apache.fop.util">CommandLineLogger</A></B></TD> <TD>This is a commons-logging logger for command line use.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/apache/fop/util/CompareUtil.html" title="class in org.apache.fop.util">CompareUtil</A></B></TD> <TD>A utility class that provides helper methods for implementing equals and hashCode.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/apache/fop/util/ContentHandlerFactoryRegistry.html" title="class in org.apache.fop.util">ContentHandlerFactoryRegistry</A></B></TD> <TD>This class holds references to various XML handlers used by FOP.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/apache/fop/util/ConversionUtils.html" title="class in org.apache.fop.util">ConversionUtils</A></B></TD> <TD>This class contains utility methods for conversions, like a java.lang.String to an array of int or double.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/apache/fop/util/DataURIResolver.html" title="class in org.apache.fop.util">DataURIResolver</A></B></TD> <TD><B>Deprecated.</B>&nbsp;<I></I>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/apache/fop/util/DataURLUtil.html" title="class in org.apache.fop.util">DataURLUtil</A></B></TD> <TD><B>Deprecated.</B>&nbsp;<I>use org.apache.xmlgraphics.util.uri.DataURLUtil directly</I></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/apache/fop/util/DefaultErrorListener.html" title="class in org.apache.fop.util">DefaultErrorListener</A></B></TD> <TD>Standard ErrorListener implementation for in-FOP use.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/apache/fop/util/DelegatingContentHandler.html" title="class in org.apache.fop.util">DelegatingContentHandler</A></B></TD> <TD>SAX 2 Event Handler which simply delegates all calls to another ContentHandler.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/apache/fop/util/DOM2SAX.html" title="class in org.apache.fop.util">DOM2SAX</A></B></TD> <TD>Helper class that produces a SAX stream from a DOM Document.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/apache/fop/util/DOMBuilderContentHandlerFactory.html" title="class in org.apache.fop.util">DOMBuilderContentHandlerFactory</A></B></TD> <TD>ContentHandlerFactory which constructs ContentHandlers that build DOM Documents.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/apache/fop/util/GenerationHelperContentHandler.html" title="class in org.apache.fop.util">GenerationHelperContentHandler</A></B></TD> <TD>This class is a delegating SAX ContentHandler which has the purpose to provide a few handy methods that make life easier when generating SAX events.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/apache/fop/util/HexEncoder.html" title="class in org.apache.fop.util">HexEncoder</A></B></TD> <TD>A helper class to create hex-encoded representations of numbers.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/apache/fop/util/LanguageTags.html" title="class in org.apache.fop.util">LanguageTags</A></B></TD> <TD>Provides utility methods for manipulating language tags compliant with the RFC 3066 specification available at http://www.ietf.org/rfc/rfc3066.txt.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/apache/fop/util/ListUtil.html" title="class in org.apache.fop.util">ListUtil</A></B></TD> <TD>Provides helper functions for <CODE>List</CODE>.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/apache/fop/util/LogUtil.html" title="class in org.apache.fop.util">LogUtil</A></B></TD> <TD>Convenience Logging utility methods used in FOP</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/apache/fop/util/QName.html" title="class in org.apache.fop.util">QName</A></B></TD> <TD><B>Deprecated.</B>&nbsp;<I>Use the XML Graphics Commons variant instead!</I></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/apache/fop/util/TransformerDefaultHandler.html" title="class in org.apache.fop.util">TransformerDefaultHandler</A></B></TD> <TD>A DefaultHandler implementation that delegates all the method calls to a <CODE>TransformerHandler</CODE> instance.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/apache/fop/util/UnclosableInputStream.html" title="class in org.apache.fop.util">UnclosableInputStream</A></B></TD> <TD>Provides an InputStreamFilter which avoids closing the original stream.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/apache/fop/util/UnitConv.html" title="class in org.apache.fop.util">UnitConv</A></B></TD> <TD><B>Deprecated.</B>&nbsp;<I>use org.apache.xmlgraphics.util.UnitConv instead.</I></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/apache/fop/util/WriterOutputStream.html" title="class in org.apache.fop.util">WriterOutputStream</A></B></TD> <TD><B>Deprecated.</B>&nbsp;<I>use org.apache.xmlgraphics.util.WriterOutputStream instead</I></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/apache/fop/util/XMLResourceBundle.html" title="class in org.apache.fop.util">XMLResourceBundle</A></B></TD> <TD>This class is a ResourceBundle that loads its contents from XML files instead of properties files (like PropertiesResourceBundle).</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/apache/fop/util/XMLUtil.html" title="class in org.apache.fop.util">XMLUtil</A></B></TD> <TD>A collection of utility method for XML handling.</TD> </TR> </TABLE> &nbsp; <P> <A NAME="package_description"><!-- --></A><H2> Package org.apache.fop.util Description </H2> <P> <P>Various utility classes (I/O, codecs, color support, service discovers etc.).</P> <P> <P> <DL> </DL> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> fop 1.1</EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../org/apache/fop/traits/package-summary.html"><B>PREV PACKAGE</B></A>&nbsp; &nbsp;<A HREF="../../../../org/apache/fop/util/bitmap/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?org/apache/fop/util/package-summary.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright 1999-2012 The Apache Software Foundation. All Rights Reserved. </BODY> </HTML>
{ "pile_set_name": "Github" }
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on 16/06/2019 @author: Maurizio Ferrari Dacrema """ import scipy.sparse as sps import numpy as np import traceback def logical_iff(a, b): a_or_not_b = np.logical_or(a, np.logical_not(b)) not_a_or_b = np.logical_or(np.logical_not(a), b) xnor = np.logical_and(a_or_not_b, not_a_or_b) return xnor def logical_implies(p, q): return np.logical_or(np.logical_not(p), q) def logical_implies_false_count(p, q): return np.logical_not(logical_implies(p, q)).sum() def print_implication_result(string_message, p, q): p_true_count = np.sum(p) # # implication_flag_array = logical_implies(p, q) # Count how many times the implication is false # So, how many times P is True but Q is false false_count = logical_implies_false_count(p, q) print("{}, False for {}/{} ({:.2f} %) users".format(string_message, false_count, p_true_count, false_count/p_true_count*100)) def print_iff_result(string_message, p, q): iff_outcome = logical_iff(p, q) true_count = iff_outcome.sum() false_count = len(iff_outcome) - true_count print("{}, True for {}/{} ({:.2f} %) users, False for {}".format(string_message, true_count, len(p), true_count/len(p)*100, false_count) ) def print_negative_items_stats(URM_train, URM_validation, URM_test, URM_test_negative): URM_train = URM_train.copy() URM_validation = URM_validation.copy() URM_test = URM_test.copy() URM_test_negative = URM_test_negative.copy() import traceback URM_test_negative_csr = sps.csr_matrix(URM_test_negative) user_negatives = np.ediff1d(URM_test_negative_csr.indptr) print("Max num negatives is {}, min num negatives is {} (nonzero is {}), users with less than max are {} of {}".format(np.max(user_negatives), np.min(user_negatives), np.min(user_negatives[user_negatives!=0]), np.sum(user_negatives!=np.max(user_negatives)), URM_test_negative_csr.shape[0])) from Utils.assertions_on_data_for_experiments import assert_disjoint_matrices remove_overlapping_data_flag = False print("Intersection between URM_test_negative and URM_train + URM_validation") try: assert_disjoint_matrices([URM_train + URM_validation, URM_test_negative]) except: traceback.print_exc() remove_overlapping_data_flag = True print("Intersection between URM_test_negative and URM_test") try: assert_disjoint_matrices([URM_test, URM_test_negative]) except: traceback.print_exc() remove_overlapping_data_flag = True if remove_overlapping_data_flag: print("Removing overlapping data from URM_negative") URM_positive = URM_train + URM_validation + URM_test URM_positive.data = np.ones_like(URM_positive.data) URM_test_negative.data = np.ones_like(URM_test_negative.data) # Subtract from the URM_test_negative train items # A - B = B - A*B URM_test_negative_not_positive = URM_test_negative - URM_test_negative.multiply(URM_positive) URM_test_negative_not_positive = sps.csr_matrix(URM_test_negative_not_positive) user_negatives_not_positives = np.ediff1d(URM_test_negative_not_positive.indptr) print("URM test negatives non overlapping with positives: Max num negatives is {}, min num negatives is {} (nonzero is {}), users with less than max are {} of {}".format(np.max(user_negatives_not_positives), np.min(user_negatives_not_positives), np.min(user_negatives_not_positives[user_negatives_not_positives!=0]), np.sum(user_negatives_not_positives!=np.max(user_negatives_not_positives)), URM_test_negative_csr.shape[0])) URM_train_all = URM_train + URM_validation URM_train_all = sps.csr_matrix(URM_train_all) user_train_profile = np.ediff1d(URM_train_all.indptr) user_test_profile = np.ediff1d(sps.csr_matrix(URM_test).indptr) assert np.array_equal(logical_iff(np.array([False, False, True, True]), np.array([False, True, False, True])), np.array([True, False, False, True])) print_iff_result("User presence in train data IFF presence in test", user_train_profile>0, user_test_profile>0) print_iff_result("User presence in test data IFF presence in negative items test", user_test_profile>0, user_negatives>0) print_iff_result("User presence in train data IFF presence in negative items test", user_train_profile>0, user_negatives>0)
{ "pile_set_name": "Github" }
// Copyright 2017 Google LLC // // 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 storage import ( "context" "errors" "fmt" "regexp" "cloud.google.com/go/internal/trace" raw "google.golang.org/api/storage/v1" ) // A Notification describes how to send Cloud PubSub messages when certain // events occur in a bucket. type Notification struct { //The ID of the notification. ID string // The ID of the topic to which this subscription publishes. TopicID string // The ID of the project to which the topic belongs. TopicProjectID string // Only send notifications about listed event types. If empty, send notifications // for all event types. // See https://cloud.google.com/storage/docs/pubsub-notifications#events. EventTypes []string // If present, only apply this notification configuration to object names that // begin with this prefix. ObjectNamePrefix string // An optional list of additional attributes to attach to each Cloud PubSub // message published for this notification subscription. CustomAttributes map[string]string // The contents of the message payload. // See https://cloud.google.com/storage/docs/pubsub-notifications#payload. PayloadFormat string } // Values for Notification.PayloadFormat. const ( // Send no payload with notification messages. NoPayload = "NONE" // Send object metadata as JSON with notification messages. JSONPayload = "JSON_API_V1" ) // Values for Notification.EventTypes. const ( // Event that occurs when an object is successfully created. ObjectFinalizeEvent = "OBJECT_FINALIZE" // Event that occurs when the metadata of an existing object changes. ObjectMetadataUpdateEvent = "OBJECT_METADATA_UPDATE" // Event that occurs when an object is permanently deleted. ObjectDeleteEvent = "OBJECT_DELETE" // Event that occurs when the live version of an object becomes an // archived version. ObjectArchiveEvent = "OBJECT_ARCHIVE" ) func toNotification(rn *raw.Notification) *Notification { n := &Notification{ ID: rn.Id, EventTypes: rn.EventTypes, ObjectNamePrefix: rn.ObjectNamePrefix, CustomAttributes: rn.CustomAttributes, PayloadFormat: rn.PayloadFormat, } n.TopicProjectID, n.TopicID = parseNotificationTopic(rn.Topic) return n } var topicRE = regexp.MustCompile("^//pubsub.googleapis.com/projects/([^/]+)/topics/([^/]+)") // parseNotificationTopic extracts the project and topic IDs from from the full // resource name returned by the service. If the name is malformed, it returns // "?" for both IDs. func parseNotificationTopic(nt string) (projectID, topicID string) { matches := topicRE.FindStringSubmatch(nt) if matches == nil { return "?", "?" } return matches[1], matches[2] } func toRawNotification(n *Notification) *raw.Notification { return &raw.Notification{ Id: n.ID, Topic: fmt.Sprintf("//pubsub.googleapis.com/projects/%s/topics/%s", n.TopicProjectID, n.TopicID), EventTypes: n.EventTypes, ObjectNamePrefix: n.ObjectNamePrefix, CustomAttributes: n.CustomAttributes, PayloadFormat: string(n.PayloadFormat), } } // AddNotification adds a notification to b. You must set n's TopicProjectID, TopicID // and PayloadFormat, and must not set its ID. The other fields are all optional. The // returned Notification's ID can be used to refer to it. func (b *BucketHandle) AddNotification(ctx context.Context, n *Notification) (ret *Notification, err error) { ctx = trace.StartSpan(ctx, "cloud.google.com/go/storage.Bucket.AddNotification") defer func() { trace.EndSpan(ctx, err) }() if n.ID != "" { return nil, errors.New("storage: AddNotification: ID must not be set") } if n.TopicProjectID == "" { return nil, errors.New("storage: AddNotification: missing TopicProjectID") } if n.TopicID == "" { return nil, errors.New("storage: AddNotification: missing TopicID") } call := b.c.raw.Notifications.Insert(b.name, toRawNotification(n)) setClientHeader(call.Header()) if b.userProject != "" { call.UserProject(b.userProject) } rn, err := call.Context(ctx).Do() if err != nil { return nil, err } return toNotification(rn), nil } // Notifications returns all the Notifications configured for this bucket, as a map // indexed by notification ID. func (b *BucketHandle) Notifications(ctx context.Context) (n map[string]*Notification, err error) { ctx = trace.StartSpan(ctx, "cloud.google.com/go/storage.Bucket.Notifications") defer func() { trace.EndSpan(ctx, err) }() call := b.c.raw.Notifications.List(b.name) setClientHeader(call.Header()) if b.userProject != "" { call.UserProject(b.userProject) } var res *raw.Notifications err = runWithRetry(ctx, func() error { res, err = call.Context(ctx).Do() return err }) if err != nil { return nil, err } return notificationsToMap(res.Items), nil } func notificationsToMap(rns []*raw.Notification) map[string]*Notification { m := map[string]*Notification{} for _, rn := range rns { m[rn.Id] = toNotification(rn) } return m } // DeleteNotification deletes the notification with the given ID. func (b *BucketHandle) DeleteNotification(ctx context.Context, id string) (err error) { ctx = trace.StartSpan(ctx, "cloud.google.com/go/storage.Bucket.DeleteNotification") defer func() { trace.EndSpan(ctx, err) }() call := b.c.raw.Notifications.Delete(b.name, id) setClientHeader(call.Header()) if b.userProject != "" { call.UserProject(b.userProject) } return call.Context(ctx).Do() }
{ "pile_set_name": "Github" }
//----------------------------------------------------------------------------- // Microsoft Local Test Manager (LTM) // Copyright (C) 1997 - 1999 By Microsoft Corporation. // // @doc // // @module MODULECORE.CPP // //----------------------------------------------------------------------------------- /////////////////////////////////////////////////////////////////////////// // Includes // ////////////////////////////////////////////////////////////////////////// #include "MODStandard.hpp" #include <initguid.h> #include "DTMGuids.hpp" DWORD g_cLock = 0; CSuperLog odtLog; ///////////////////////////////////////////////////////////////////////// // Defines // ///////////////////////////////////////////////////////////////////////// #define CHECK_MEMORY(pv) if(!pv) goto CLEANUP #define SAFE_ALLOC(pv, type, cb) { pv = CoTaskMemAlloc((cb)*sizeof(type)); CHECK_MEMORY(pv); } #define SAFE_REALLOC(pv, type, cb) { pv = (type*)CoTaskMemRealloc(pv, (cb)*sizeof(type)); CHECK_MEMORY(pv); } #define SAFE_SYSALLOC(pv, bstr) { pv = SysAllocString(bstr); CHECK_MEMORY(pv); } #define SAFE_FREE(pv) { CoTaskMemFree(pv); pv = NULL; } #define SAFE_SYSFREE(bstr) { SysFreeString(bstr); bstr = NULL; } //IUnknown->Release Wrapper #define SAFE_ADDREF(pv) if(pv) { (pv)->AddRef(); } #define SAFE_RELEASE(pv) if(pv) { (pv)->Release(); (pv) = NULL; } #define SAFE_DELETE(pv) if(pv) { delete pv; pv = NULL; } //Error Checking (tracing) #ifdef _TRACING #define TRACE(string) OutputDebugStringA(string) #else #define TRACE(string) #endif //_TRACING /////////////////////////////////////////////////////////////////////////// // CTestModuleClassFactory // ////////////////////////////////////////////////////////////////////////// CTestModuleClassFactory::CTestModuleClassFactory(GlobalModuleData *pTTM) { m_cRef = 0; m_pGlobData = pTTM; } CTestModuleClassFactory::~CTestModuleClassFactory() { } STDMETHODIMP CTestModuleClassFactory::QueryInterface( REFIID riid, //@parm [in] Interface ID to query for LPVOID* ppv) //@parm [out] Interface pointer for interface ID { if(ppv == NULL) return E_INVALIDARG; *ppv = NULL; // Check if we support the interface asked for if(riid == IID_IUnknown) *ppv = (IUnknown*)this; else if(riid == IID_IClassFactory) *ppv = (IClassFactory*)this; else return E_NOINTERFACE; ((IUnknown *)*ppv)->AddRef(); return S_OK; } STDMETHODIMP_(DWORD) CTestModuleClassFactory::AddRef() { return InterlockedIncrement((LONG*)&m_cRef); } STDMETHODIMP_(DWORD) CTestModuleClassFactory::Release() { InterlockedDecrement((LONG*)&m_cRef); if(m_cRef == 0) { delete this; return 0; } return m_cRef; } STDMETHODIMP CTestModuleClassFactory::CreateInstance( LPUNKNOWN pUnkOuter, //@parm [in] Pointer to the controlling IUNKNOWN REFIID riid, //@parm [in] Interface ID for object initialization LPVOID * ppvObj) //@parm [out] Interface pointer for Interface ID { if(ppvObj == NULL) return E_INVALIDARG; *ppvObj = NULL; // Do we support the interface? if(pUnkOuter != NULL) return CLASS_E_NOAGGREGATION; CThisTestModule* pCThisTestModule = new CThisTestModule(m_pGlobData); if(pCThisTestModule == NULL) return E_OUTOFMEMORY; HRESULT hr = pCThisTestModule->QueryInterface(riid, ppvObj); if(FAILED(hr)) delete pCThisTestModule; return hr; } STDMETHODIMP CTestModuleClassFactory::LockServer( BOOL fLock) //@parm [in] Increment lock count(TRUE/FALSE) { if (fLock) g_cLock++; // TRUE increment lock count else g_cLock--; // FALSE decrement lock count return NOERROR; } /////////////////////////////////////////////////////////////////////////// // CThisTestModule // ////////////////////////////////////////////////////////////////////////// CThisTestModule::CThisTestModule(GlobalModuleData *pgmd) { m_cRef = 0; m_gmd = *pgmd; m_nTestCount = 0; m_pwszProviderName = NULL; m_pwszProviderFName = NULL; m_pwszInitString = NULL; m_ProviderClsid = GUID_NULL; m_pwszMachineName = NULL; m_clsctxProvider = CLSCTX_INPROC_SERVER; m_pError = NULL; m_pIProviderInfo = NULL; m_pIUnknown = NULL; m_pIUnknown2 = NULL; m_pVoid = NULL; m_pVoid2 = NULL; } CThisTestModule::~CThisTestModule() { SAFE_DELETE(m_pError); SAFE_RELEASE(m_pIProviderInfo); SAFE_SYSFREE(m_pwszProviderName); SAFE_SYSFREE(m_pwszProviderFName); SAFE_SYSFREE(m_pwszInitString); SAFE_SYSFREE(m_pwszMachineName); } STDMETHODIMP CThisTestModule::QueryInterface( REFIID riid, void **ppvObject) { if(ppvObject == NULL) return E_INVALIDARG; *ppvObject = NULL; if(riid == IID_IUnknown) *ppvObject = (IUnknown*)this; else if(riid == IID_ITestModule) *ppvObject = (ITestModule*)this; else return E_NOINTERFACE; ((IUnknown *)*ppvObject)->AddRef(); return S_OK; } STDMETHODIMP_(DWORD) CThisTestModule::AddRef(void) { return InterlockedIncrement((LONG*)&m_cRef); } STDMETHODIMP_(DWORD) CThisTestModule::Release(void) { InterlockedDecrement((LONG*)&m_cRef); if(m_cRef == 0) { delete this; return 0; } return m_cRef; } STDMETHODIMP CThisTestModule::GetName(BSTR *pbstrName) { TRACE("CThisTestModule::GetName\n"); if(pbstrName == NULL) return E_INVALIDARG; *pbstrName = SysAllocString(m_gmd.m_wszModuleName); return S_OK; } STDMETHODIMP CThisTestModule::GetDescription(BSTR *pbstrDescription) { TRACE("CThisTestModule::GetDescription\n"); if(pbstrDescription == NULL) return E_INVALIDARG; *pbstrDescription = SysAllocString(m_gmd.m_wszDescription); return S_OK; } STDMETHODIMP CThisTestModule::GetOwnerName(BSTR *pbstrOwner) { TRACE("CThisTestModule::GetOwnerName\n"); if(pbstrOwner == NULL) return E_INVALIDARG; *pbstrOwner = SysAllocString(m_gmd.m_wszModuleOwner); return S_OK; } STDMETHODIMP CThisTestModule::GetCLSID(BSTR* pGUID) { TRACE("CThisTestModule::GetCLSID\n"); if(pGUID == NULL) return E_INVALIDARG; WCHAR* pwszClsid = NULL; StringFromCLSID(*(m_gmd.m_pguidModuleCLSID), &pwszClsid); *pGUID = SysAllocString(pwszClsid); SAFE_FREE(pwszClsid); return S_OK; } STDMETHODIMP CThisTestModule::GetVersion(LONG *plVer) { TRACE("CThisTestModule::GetVersion\n"); if(plVer == NULL) return E_INVALIDARG; *plVer = m_gmd.m_dwVersion; return S_OK; } STDMETHODIMP CThisTestModule::GetProviderInterface(IProviderInfo** ppIProviderInfo) { TRACE("CThisTestModule::GetProviderInterface\n"); if(ppIProviderInfo == NULL) return E_INVALIDARG; if(m_pIProviderInfo) return m_pIProviderInfo->QueryInterface(IID_IProviderInfo, (void**)ppIProviderInfo); *ppIProviderInfo = NULL; return E_FAIL; } STDMETHODIMP CThisTestModule::SetProviderInterface(IProviderInfo *pIProviderInfo) { TRACE("CThisTestModule::SetProviderInterface\n"); HRESULT hr = S_OK; if(!pIProviderInfo) return E_INVALIDARG; SAFE_RELEASE(m_pIProviderInfo); SAFE_SYSFREE(m_pwszProviderName); SAFE_SYSFREE(m_pwszProviderFName); SAFE_SYSFREE(m_pwszInitString); SAFE_SYSFREE(m_pwszMachineName); //Obtain IProviderInfo from the user... if(FAILED(hr = pIProviderInfo->QueryInterface(IID_IProviderInfo, (void**)&m_pIProviderInfo))) return hr; //ProviderInfo pIProviderInfo->GetName(&m_pwszProviderName); pIProviderInfo->GetFriendlyName(&m_pwszProviderFName); pIProviderInfo->GetInitString(&m_pwszInitString); pIProviderInfo->GetMachineName(&m_pwszMachineName); //CLSID BSTR bstr = NULL; pIProviderInfo->GetCLSID(&bstr); CLSIDFromString(bstr, &m_ProviderClsid); SAFE_SYSFREE(bstr); //CLSCTX pIProviderInfo->GetCLSCTX((LONG*)&m_clsctxProvider); return hr; } STDMETHODIMP CThisTestModule::SetErrorInterface(IError *pIError) { TRACE("CThisTestModule::SetErrorInterface\n"); SAFE_DELETE(m_pError); m_pError = new CError; if(m_pError == NULL) return E_OUTOFMEMORY; //Delegate return m_pError->SetErrorInterface(pIError); } STDMETHODIMP CThisTestModule::GetErrorInterface(IError **ppIError) { TRACE("CThisTestModule::GetErrorInterface\n"); if(ppIError == NULL) return E_INVALIDARG; //Delegate if(m_pError) return m_pError->GetErrorInterface(ppIError); *ppIError = NULL; return E_FAIL; } STDMETHODIMP CThisTestModule::Init(LONG *pdwResult) { TRACE("CThisTestModule::Init\n"); LONG dwResult = m_gmd.m_pfnModuleInit(this); if(pdwResult) *pdwResult = dwResult; return S_OK; } STDMETHODIMP CThisTestModule::Terminate(VARIANT_BOOL* pbResult) { TRACE("CThisTestModule::Terminate\n"); VARIANT_BOOL bResult = (VARIANT_BOOL)m_gmd.m_pfnModuleTerminate(this); if(pbResult) *pbResult = bResult; return S_OK; } STDMETHODIMP CThisTestModule::GetCaseCount(LONG *pc) { TRACE("CThisTestModule::GetCaseCount\n"); if(pc == NULL) return E_INVALIDARG; *pc = m_gmd.m_wTestCount; return S_OK; } STDMETHODIMP CThisTestModule::GetCase(LONG iCase, ITestCases** ppITestCases) { TRACE("CThisTestModule::GetCase\n"); //Range Checking if(iCase < 0 || iCase >= m_gmd.m_wTestCount || ppITestCases == NULL) { if(ppITestCases) *ppITestCases = NULL; return E_INVALIDARG; } ITestCases* pITestCases = (ITestCases*)m_gmd.m_pfnModuleGetCase(iCase + 1, this); if(pITestCases) return pITestCases->QueryInterface(IID_ITestCases, (void**)ppITestCases); *ppITestCases = NULL; return E_FAIL; } /////////////////////////////////////////////////////////////////////////// // CTestCases // ////////////////////////////////////////////////////////////////////////// CTestCases::CTestCases(const WCHAR* pwszTestCaseName) { m_cRef = 0; m_dwTestCaseNumber = 0; m_pwszCLSID = NULL; m_pwszTestCaseName = NULL; m_pwszTestCaseDesc = NULL; m_pThisTestModule = NULL; m_pError = NULL; m_pwszProviderName = NULL; m_pwszProviderFName = NULL; m_pwszInitString = NULL; m_ProviderClsid = GUID_NULL; m_pwszMachineName = NULL; m_clsctxProvider = CLSCTX_INPROC_SERVER; m_pIStats = NULL; m_pTmdSpy = NULL; } CTestCases::~CTestCases(void) { SAFE_RELEASE(m_pThisTestModule); SAFE_DELETE(m_pError); DeleteProviderInfo(); } HRESULT CTestCases::SetOwningMod(LONG i, CThisTestModule* pCThisTestModule) { TRACE("CTestCases::SetOwningMod\n"); SAFE_RELEASE(m_pThisTestModule); m_pThisTestModule = pCThisTestModule; SAFE_ADDREF(m_pThisTestModule); SAFE_DELETE(m_pError); m_pError = new CError; m_dwTestCaseNumber = i; return SyncProviderInterface(); } void CTestCases::DeleteProviderInfo(void) { TRACE("CTestCases::DeleteProviderInfo\n"); SAFE_SYSFREE(m_pwszProviderName); SAFE_SYSFREE(m_pwszProviderFName); SAFE_SYSFREE(m_pwszInitString); SAFE_SYSFREE(m_pwszMachineName); } STDMETHODIMP CTestCases::QueryInterface( REFIID riid, //@parm [in] Interface ID to query for LPVOID* ppv) //@parm [out] Interface pointer for interface ID { if(ppv == NULL) return E_INVALIDARG; *ppv = NULL; // Check if we support the interface asked for if(riid == IID_IUnknown) *ppv = (IUnknown*)this; else if(riid == IID_ITestCases) *ppv = (ITestCases*)this; else return E_NOINTERFACE; ((IUnknown *)*ppv)->AddRef(); return S_OK; } STDMETHODIMP_(DWORD) CTestCases::AddRef() { return InterlockedIncrement((LONG*)&m_cRef); } STDMETHODIMP_(DWORD) CTestCases::Release() { InterlockedDecrement((LONG*)&m_cRef); if(m_cRef == 0) { delete this; return 0; } return m_cRef; } STDMETHODIMP CTestCases::GetName(BSTR *pbstrName) { TRACE("CTestCases::GetName\n"); if(pbstrName == NULL) return E_INVALIDARG; *pbstrName = SysAllocString(GetCaseName()); return S_OK; } STDMETHODIMP CTestCases::GetDescription(BSTR *pbstrDesc) { TRACE("CTestCases::GetDescription\n"); if(pbstrDesc == NULL) return E_INVALIDARG; *pbstrDesc = SysAllocString(GetCaseDesc()); return S_OK; } STDMETHODIMP CTestCases::GetProviderInterface(IProviderInfo** ppIProviderInfo) { TRACE("CTestCases::GetProviderInterface\n"); if(ppIProviderInfo == NULL) return E_INVALIDARG; if(m_pThisTestModule) return m_pThisTestModule->GetProviderInterface(ppIProviderInfo); *ppIProviderInfo = NULL; return E_FAIL; } STDMETHODIMP CTestCases::GetOwningITestModule(ITestModule** ppITestModule) { TRACE("CTestCases::GetOwningITestModule\n"); if(ppITestModule == NULL) return E_INVALIDARG; if(m_pThisTestModule) return m_pThisTestModule->QueryInterface(IID_ITestModule, (void**)ppITestModule); *ppITestModule = NULL; return E_FAIL; } STDMETHODIMP CTestCases::Init(LONG *pdwResult) { TRACE("CTestCases::Init\n"); //Delegate to the derived class... LONG dwResult = Init(); if(pdwResult) *pdwResult = dwResult; return S_OK; } STDMETHODIMP CTestCases::Terminate(VARIANT_BOOL* pbResult) { TRACE("CTestCases::Terminate\n"); //Delegate to the derived class... VARIANT_BOOL bResult = (VARIANT_BOOL)Terminate(); if(pbResult) *pbResult = bResult ? VARIANT_TRUE : VARIANT_FALSE; return S_OK; } STDMETHODIMP CTestCases::GetVariationCount(LONG *pc) { TRACE("CTestCases::GetVariationCount\n"); if(pc == NULL) return E_INVALIDARG; *pc = GetVarCount(); return S_OK; } STDMETHODIMP CTestCases::ExecuteVariation(LONG iVariation, VARIATION_STATUS *pdwResult) { TRACE("CTestCases::ExecuteVariation\n"); if(pdwResult) *pdwResult = eVariationStatusNonExistent; //Range Checking if(iVariation < 0 || iVariation >= (LONG)GetVarCount()) return E_INVALIDARG; //Find the correct Variation funcion to execute VARINFO* rgVarInfo = (VARINFO*)GetVarInfoArray(); PFNVARIATION pVarFunction = rgVarInfo[iVariation].pfnVariation; //TODO: (compiler file 'E:\8168\vc98\p2\src\P2\main.c', line 494) //Please choose the Technical Support command on the Visual C++ //Help menu, or open the Technical Support help file for more information //if(!pVarFunction) if(pVarFunction == NULL) return E_FAIL; //Execute the Variation... VARIATION_STATUS dwResult = (VARIATION_STATUS)((this->*pVarFunction)()); //Result if(pdwResult) *pdwResult = dwResult; return S_OK; } STDMETHODIMP CTestCases::GetVariationDesc(LONG iVariation, BSTR *pbstrDesc) { TRACE("CTestCases::GetVariationDesc\n"); //Range Checking if(iVariation < 0 || iVariation >= (LONG)GetVarCount() || pbstrDesc == NULL) { if(pbstrDesc) *pbstrDesc = NULL; return E_INVALIDARG; } const VARINFO* rgVarInfo = GetVarInfoArray(); *pbstrDesc = SysAllocString(rgVarInfo[iVariation].wszDescription); return S_OK; } STDMETHODIMP CTestCases::GetVariationID(LONG iVariation, LONG *pdwID) { TRACE("CTestCases::GetVariationID\n"); //Range Checking if(iVariation < 0 || iVariation >= (LONG)GetVarCount() || pdwID == NULL) { if(pdwID) *pdwID = 0; return E_INVALIDARG; } const VARINFO* rgVarInfo = GetVarInfoArray(); *pdwID = rgVarInfo[iVariation].id; return S_OK; } STDMETHODIMP CTestCases::SyncProviderInterface(void) { TRACE("CTestCases::SyncProviderInterface\n"); IProviderInfo* pIProviderInfo = NULL; HRESULT hr = S_OK; if(m_pThisTestModule == NULL) return E_FAIL; //Obtain the CProviderInfo from the TestModule if(FAILED(hr = m_pThisTestModule->GetProviderInterface(&pIProviderInfo))) return hr; DeleteProviderInfo(); if(pIProviderInfo) { //ProviderInfo pIProviderInfo->GetName(&m_pwszProviderName); pIProviderInfo->GetFriendlyName(&m_pwszProviderFName); pIProviderInfo->GetInitString(&m_pwszInitString); pIProviderInfo->GetMachineName(&m_pwszMachineName); //CLSID BSTR bstr = NULL; pIProviderInfo->GetCLSID(&bstr); CLSIDFromString(bstr, &m_ProviderClsid); SAFE_SYSFREE(bstr); //CLSCTX pIProviderInfo->GetCLSCTX((LONG*)&m_clsctxProvider); } SAFE_RELEASE(pIProviderInfo); return S_OK; }
{ "pile_set_name": "Github" }
package main import ( "github.com/fogleman/gg" "github.com/golang/freetype/truetype" "golang.org/x/image/font/gofont/goregular" ) func main() { const S = 400 dc := gg.NewContext(S, S) dc.SetRGB(1, 1, 1) dc.Clear() dc.SetRGB(0, 0, 0) font, err := truetype.Parse(goregular.TTF) if err != nil { panic("") } face := truetype.NewFace(font, &truetype.Options{ Size: 40, }) dc.SetFontFace(face) text := "Hello, world!" w, h := dc.MeasureString(text) dc.Rotate(gg.Radians(10)) dc.DrawRectangle(100, 180, w, h) dc.Stroke() dc.DrawStringAnchored(text, 100, 180, 0.0, 0.0) dc.SavePNG("out.png") }
{ "pile_set_name": "Github" }
create table t_department( id int not null identity(1, 1), name varchar(128) not null, location varchar(128) not null ); create table t_employee( id int not null identity(1, 1), name varchar(128) not null, job varchar(128) not null, manager_id int null, hire_date date not null, salary bigint not null, department_id int not null ); insert into t_department(name, location) values ('tech', 'Guangzhou'); insert into t_department(name, location) values ('finance', 'Beijing'); insert into t_employee(name, job, manager_id, hire_date, salary, department_id) values ('vince', 'engineer', null, '2018-01-01', 100, 1); insert into t_employee(name, job, manager_id, hire_date, salary, department_id) values ('marry', 'trainee', 1, '2019-01-01', 50, 1); insert into t_employee(name, job, manager_id, hire_date, salary, department_id) values ('tom', 'director', null, '2018-01-01', 200, 2); insert into t_employee(name, job, manager_id, hire_date, salary, department_id) values ('penny', 'assistant', 3, '2019-01-01', 100, 2); create table foo (bar datetimeoffset(7) not null, bar1 datetime not null); insert into foo (bar, bar1) values ('2012-10-25 12:32:10 +01:00', '2012-10-25 19:32:10');
{ "pile_set_name": "Github" }
@model ActiveLogin.Authentication.BankId.AspNetCore.Areas.BankIdAuthentication.Models.BankIdLoginViewModel <script> (function (options) { // Pre check var statusElement = document.querySelector('#bankIdLoginStatus'); var statusWrapperElement = statusElement.querySelector('.status-wrapper'); var statusSpinnerElement = statusElement.querySelector('.status-spinner'); var statusMessageElement = statusElement.querySelector('.status-message'); var cancelButtonElement = statusElement.querySelector('.btn-cancel'); var requiredFeatures = [window.fetch, window.sessionStorage]; var isMissingSomeFeature = requiredFeatures.some(function(x) { return !x; }); if (isMissingSomeFeature) { showStatus(options.unsupportedBrowserErrorMessage, 'danger', false, true); return; } // OrderRef var sessionStorageOrderRefKey = 'ActiveLogin_BankId_OrderRef'; var orderRef = sessionStorage.getItem(sessionStorageOrderRefKey); sessionStorage.removeItem(sessionStorageOrderRefKey); // Elements var startBankIdAppButtonElement = document.querySelector('#bankIdLoginStartApp'); var qrCodeElement = statusElement.querySelector('.qr-code-image'); var formElement = document.querySelector('#bankIdLoginForm'); var formFieldsetElement = formElement.querySelector('fieldset'); var autoLoginElement = formElement.querySelector('[name="AutoLogin"]'); var autoLogin = autoLoginElement.value === 'true'; var formSubmitButtonElement = formElement.querySelector('button[type="submit"]'); var formSubmitButtonTextElement = null; var formSubmitButtonSpinnerElement = null; if (formSubmitButtonElement) { formSubmitButtonTextElement = formSubmitButtonElement.querySelector('.submit-text'); formSubmitButtonSpinnerElement = formSubmitButtonElement.querySelector('.status-spinner'); } // Events if (orderRef) { showOrderRefStatus(orderRef); } else if (autoLogin) { document.addEventListener('DOMContentLoaded', function () { resetUi(); login(); }); } else { formElement.addEventListener('submit', function (event) { event.preventDefault(); resetUi(); login(); }); } // Boot function showOrderRefStatus(orderRef) { var requestVerificationTokenElement = formElement.querySelector('[name="RequestVerificationToken"]'); var returnUrlElement = formElement.querySelector('[name="ReturnUrl"]'); var loginOptionsElement = formElement.querySelector('[name="LoginOptions"]'); hide(formElement); showStatus(options.initialStatusMessage, 'white', true); checkStatus(requestVerificationTokenElement.value, returnUrlElement.value, loginOptionsElement.value, orderRef); } function login() { var requestVerificationTokenElement = formElement.querySelector('[name="RequestVerificationToken"]'); var returnUrlElement = formElement.querySelector('[name="ReturnUrl"]'); var cancelReturnUrlElement = formElement.querySelector('[name="CancelReturnUrl"]'); var loginOptionsElement = formElement.querySelector('[name="LoginOptions"]'); var personalIdentityNumberElement = formElement.querySelector('[name="PersonalIdentityNumber"]'); var personalIdentityNumber = !!personalIdentityNumberElement ? personalIdentityNumberElement.value : ''; initialize(requestVerificationTokenElement.value, returnUrlElement.value, cancelReturnUrlElement.value, loginOptionsElement.value, personalIdentityNumber, personalIdentityNumberElement); } function resetUi() { formFieldsetElement.disabled = true; show(formSubmitButtonSpinnerElement); hide(formSubmitButtonTextElement); hide(qrCodeElement); } // BankID var autoStartAttempts = 0; var loginIsCancelledByUser = false; function initialize(requestVerificationToken, returnUrl, cancelUrl, loginOptions, personalIdentityNumber, personalIdentityNumberElement) { loginIsCancelledByUser = false; function enableCancelButton(orderRef) { var onCancelButtonClick = function(event) { cancel(requestVerificationToken, cancelUrl, orderRef, loginOptions); event.target.removeEventListener('click', onCancelButtonClick); }; cancelButtonElement.addEventListener('click', onCancelButtonClick); } postJson(options.bankIdInitializeApiUrl, requestVerificationToken, { 'personalIdentityNumber': personalIdentityNumber, 'returnUrl': returnUrl, 'loginOptions': loginOptions }) .then(function (data) { if (data.isAutoLaunch) { if (!data.checkStatus) { sessionStorage.setItem(sessionStorageOrderRefKey, data.orderRef); } if (data.deviceMightRequireUserInteractionToLaunchBankIdApp) { var startBankIdAppButtonOnClick = function(event) { window.location.href = data.redirectUri; hide(startBankIdAppButtonElement); event.target.removeEventListener('click', startBankIdAppButtonOnClick); }; startBankIdAppButtonElement.addEventListener('click', startBankIdAppButtonOnClick); show(startBankIdAppButtonElement); } else { window.location.href = data.redirectUri; } } if (!!data.qrCodeAsBase64) { qrCodeElement.src = 'data:image/png;base64, ' + data.qrCodeAsBase64; show(qrCodeElement); } if (!!data.personalIdentityNumber) { setInvalidUntilChange(personalIdentityNumberElement); formFieldsetElement.disabled = false; } else { enableCancelButton(data.orderRef); hide(formElement); showStatus(options.initialStatusMessage, 'white', true); if (data.checkStatus) { checkStatus(requestVerificationToken, returnUrl, loginOptions, data.orderRef); } } show(formSubmitButtonTextElement); hide(formSubmitButtonSpinnerElement); }).catch(function (error) { showStatus(error.message, 'danger', false); hide(qrCodeElement); hide(startBankIdAppButtonElement); show(formSubmitButtonTextElement); hide(formSubmitButtonSpinnerElement); formFieldsetElement.disabled = false; enableCancelButton(); }); } function checkStatus(requestVerificationToken, returnUrl, loginOptions, orderRef) { if (loginIsCancelledByUser) { return; } postJson(options.bankIdStatusApiUrl, requestVerificationToken, { 'orderRef': orderRef, 'returnUrl': returnUrl, 'loginOptions': loginOptions, 'autoStartAttempts': autoStartAttempts }) .then(function (data) { if (data.retryLogin) { autoStartAttempts++; login(); } else if (data.isFinished) { window.location.href = data.redirectUri; } else if (!loginIsCancelledByUser) { autoStartAttempts = 0; showStatus(data.statusMessage, 'white', true); setTimeout(function () { checkStatus(requestVerificationToken, returnUrl, loginOptions, orderRef); }, options.refreshIntervalMs); } }).catch(function (error) { if (!loginIsCancelledByUser) { showStatus(error.message, 'danger', false); hide(startBankIdAppButtonElement); } hide(qrCodeElement); }); } function cancel(requestVerificationToken, cancelReturnUrl, orderRef, loginOptions) { loginIsCancelledByUser = true; if (!orderRef) { window.location.href = cancelReturnUrl; return; } postJson(options.bankIdCancelApiUrl, requestVerificationToken, { 'orderRef': orderRef, 'loginOptions': loginOptions }).finally(function() { window.location.href = cancelReturnUrl; }); } // Helpers function postJson(url, requestVerificationToken, data) { return fetch(url, { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'RequestVerificationToken': requestVerificationToken }, credentials: 'include', body: JSON.stringify(data) }) .then(function (response) { var contentType = response.headers.get("content-type"); if (contentType && contentType.indexOf("application/json") !== -1) { return response.json(); } throw Error(options.unknownErrorMessage); }) .then(function (data) { if (!!data.errorMessage) { throw Error(data.errorMessage); } return data; }); } function showStatus(status, type, spinner, html) { var textClass = 'text-white'; if (type === 'white') { textClass = ''; } statusWrapperElement.className = 'card status-wrapper bg-' + type + ' ' + textClass; if (!!html) { statusMessageElement.innerHTML = status; } else { statusMessageElement.innerText = status; } setVisibility(statusSpinnerElement, spinner, 'inline-block'); show(statusElement); } function setVisibility(element, visible, display) { if (!!visible) { show(element, display); } else { hide(element, display); } } function show(element, display) { if (!element) { return; } element.style.display = display || 'block'; } function hide(element) { if (!element) { return; } element.style.display = 'none'; } function setInvalidUntilChange(element) { if (!element || !element.classList) { return; } element.classList.add('is-invalid'); element.addEventListener('input', removeInvalid); function removeInvalid() { element.removeEventListener('input', removeInvalid); element.classList.remove('is-invalid'); } } }(@Html.Raw(Model.LoginScriptOptionsJson))); </script>
{ "pile_set_name": "Github" }
# ASJ Japanese Newspaper Article Sentences Read Speech Corpus (JNAS) http://research.nii.ac.jp/src/JNAS.html We assume that the database structure is as follows: ``` /database/JNAS ├── DOCS/ ├── OriginalText/ ├── readme_en.txt ├── readme_jp.txt ├── reference_en.pdf ├── reference_jp.pdf ├── Transcription/ ├── WAVES_DT/ └── WAVES_HS/ /database/JNAS/DOCS/Test_set ├── ASJ_1998.pdf ├── IPA98_testset_100/ ├── JNAS_testset_100/ ├── JNAS_testset_500/ └── readme.txt ``` ## asr1 TO BE FILLED. ## tts1 JNAS provides transcriptions in 挢字仮名亀じり文. However, due to the large number of vocabularies in Chinese characters, we convert the input transcription to more compact representation: kana or phoneme. For this reason, you will have to install the text processing frontend ([OpenJTalk](http://open-jtalk.sp.nitech.ac.jp/)) to run the recipe. Please try the following to install the dependencies: ``` cd ${MAIN_ROOT}/tools && make pyopenjtalk.done ``` or manually install dependencies by following the instruction in https://github.com/r9y9/pyopenjtalk if you are working on your own python environment.
{ "pile_set_name": "Github" }
" vimtex - LaTeX plugin for Vim " " Maintainer: Karl Yngve LervÃ¥g " Email: [email protected] " function! vimtex#bib#files() abort " {{{1 if has_key(b:vimtex.packages, 'biblatex') let l:file = b:vimtex.ext('bcf') if filereadable(l:file) let l:bibs = map( \ filter(readfile(l:file), "v:val =~# 'bcf:datasource'"), \ {_, x -> matchstr(x, '<[^>]*>\zs[^<]*')}) if !empty(l:bibs) | return s:validate(l:bibs) | endif endif endif let l:file = b:vimtex.ext('blg') if filereadable(l:file) let l:bibs = map( \ filter(readfile(l:file), 'v:val =~# ''^Database file #\d'''), \ {_, x -> matchstr(x, '#\d\+: \zs.*\ze\.bib$')}) " Ignore '{name}-blx.bib' file (created by biblatex) if has_key(b:vimtex.packages, 'biblatex') call filter(l:bibs, 'v:val !~# ''-blx$''') endif if !empty(l:bibs) | return s:validate(l:bibs) | endif endif return s:validate(s:files_manual()) endfunction " }}}1 function! s:validate(files) abort " {{{1 call filter(a:files, {_, x -> !empty(x)}) call map(a:files, {_, x -> substitute(x, '\%(\.bib\)\?$', '.bib', '')}) call map(a:files, {_, x -> filereadable(x) ? x : vimtex#kpsewhich#find(x)}) call filter(a:files, {_, x -> filereadable(x)}) return a:files endfunction " }}}1 function! s:files_manual() abort " {{{1 " " Search for bibliography files by parsing the source code " * Parse commands such as \bibliography{file1,file2.bib,...} " let l:cache = vimtex#cache#open('bibfiles', { \ 'local': 1, \ 'default': {'files': [], 'ftime': -1} \}) " Handle local file editing (e.g. subfiles package) let l:id = get(get(b:, 'vimtex_local', {'main_id' : b:vimtex_id}), 'main_id') let l:vimtex = vimtex#state#get(l:id) let l:bibfiles = [] for l:file in map(copy(l:vimtex.sources), 'l:vimtex.root . ''/'' . v:val') let l:current = l:cache.get(l:file) let l:ftime = getftime(l:file) if l:ftime > l:current.ftime let l:cache.modified = 1 let l:current.ftime = l:ftime let l:current.files = [] for l:entry in map( \ filter(readfile(l:file), {_, x -> x =~# s:bib_re}), \ {_, x -> matchstr(x, s:bib_re)}) let l:files = [] let l:entry = substitute(l:entry, '\\jobname', b:vimtex.name, 'g') for l:f in split(l:entry, ',') if stridx(l:f, '*') >= 0 let l:files += glob(l:f, 0, 1) else let l:files += [fnamemodify(l:f, ':r')] endif endfor let l:current.files += l:files endfor endif let l:bibfiles += l:current.files endfor " Write cache to file call l:cache.write() return uniq(l:bibfiles) endfunction " }}}1 let s:bib_re = g:vimtex#re#not_comment . '\\(' \ . join(g:vimtex_bibliography_commands, '|') \ . ')\s*\{\zs[^}]+\ze}'
{ "pile_set_name": "Github" }
package liquibase.command.core; import liquibase.CatalogAndSchema; import liquibase.Scope; import liquibase.command.AbstractCommand; import liquibase.command.CommandResult; import liquibase.command.CommandValidationErrors; import liquibase.database.Database; import liquibase.database.ObjectQuotingStrategy; import liquibase.database.core.*; import liquibase.exception.LiquibaseException; import liquibase.license.LicenseServiceUtils; import liquibase.serializer.SnapshotSerializerFactory; import liquibase.snapshot.DatabaseSnapshot; import liquibase.snapshot.SnapshotControl; import liquibase.snapshot.SnapshotGeneratorFactory; import liquibase.snapshot.SnapshotListener; import liquibase.util.StringUtil; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Map; public class SnapshotCommand extends AbstractCommand<SnapshotCommand.SnapshotCommandResult> { private Database database; private CatalogAndSchema[] schemas; private String serializerFormat; private SnapshotListener snapshotListener; private Map<String, Object> snapshotMetadata; @Override public String getName() { return "snapshot"; } public void setDatabase(Database database) { this.database = database; } public Database getDatabase() { return database; } public SnapshotCommand setSchemas(CatalogAndSchema... catalogAndSchema) { schemas = catalogAndSchema; return this; } public SnapshotCommand setSchemas(String... schemas) { if ((schemas == null) || (schemas.length == 0) || (schemas[0] == null)) { this.schemas = null; return this; } schemas = StringUtil.join(schemas, ",").split("\\s*,\\s*"); List<CatalogAndSchema> finalList = new ArrayList<>(); for (String schema : schemas) { finalList.add(new CatalogAndSchema(null, schema).customize(database)); } this.schemas = finalList.toArray(new CatalogAndSchema[finalList.size()]); return this; } public String getSerializerFormat() { return serializerFormat; } public SnapshotCommand setSerializerFormat(String serializerFormat) { this.serializerFormat = serializerFormat; return this; } public SnapshotListener getSnapshotListener() { return snapshotListener; } public void setSnapshotListener(SnapshotListener snapshotListener) { this.snapshotListener = snapshotListener; } public Map<String, Object> getSnapshotMetadata() { return snapshotMetadata; } public void setSnapshotMetadata(Map<String, Object> snapshotMetadata) { this.snapshotMetadata = snapshotMetadata; } @Override protected SnapshotCommandResult run() throws Exception { SnapshotCommand.logUnsupportedDatabase(database, this.getClass()); SnapshotControl snapshotControl = new SnapshotControl(database); snapshotControl.setSnapshotListener(snapshotListener); CatalogAndSchema[] schemas = this.schemas; if (schemas == null) { schemas = new CatalogAndSchema[]{database.getDefaultSchema()}; } ObjectQuotingStrategy originalQuotingStrategy = database.getObjectQuotingStrategy(); database.setObjectQuotingStrategy(ObjectQuotingStrategy.QUOTE_ALL_OBJECTS); DatabaseSnapshot snapshot; try { snapshot = SnapshotGeneratorFactory.getInstance().createSnapshot(schemas, database, snapshotControl); } finally { database.setObjectQuotingStrategy(originalQuotingStrategy); } snapshot.setMetadata(this.getSnapshotMetadata()); return new SnapshotCommandResult(snapshot); } @Override public CommandValidationErrors validate() { return new CommandValidationErrors(this); } public class SnapshotCommandResult extends CommandResult { public DatabaseSnapshot snapshot; public SnapshotCommandResult() { } public SnapshotCommandResult(DatabaseSnapshot snapshot) { this.snapshot = snapshot; } @Override public String print() throws LiquibaseException { String format = getSerializerFormat(); if (format == null) { format = "txt"; } return SnapshotSerializerFactory.getInstance().getSerializer(format.toLowerCase(Locale.US)).serialize(snapshot, true); } public void merge(SnapshotCommandResult resultToMerge) { this.snapshot.merge(resultToMerge.snapshot); } } public static void logUnsupportedDatabase(Database database, Class callingClass) { if (LicenseServiceUtils.checkForValidLicense("Liquibase Pro")) { if (!(database instanceof MSSQLDatabase || database instanceof OracleDatabase || database instanceof DB2Database || database instanceof PostgresDatabase)) { Scope.getCurrentScope().getUI().sendMessage("INFO This command might not yet capture Liquibase Pro additional object types on " + database.getShortName()); } } } }
{ "pile_set_name": "Github" }
// go generate gen.go // GENERATED BY THE COMMAND ABOVE; DO NOT EDIT package ipv4 // Internet Control Message Protocol (ICMP) Parameters, Updated: 2013-04-19 const ( ICMPTypeEchoReply ICMPType = 0 // Echo Reply ICMPTypeDestinationUnreachable ICMPType = 3 // Destination Unreachable ICMPTypeRedirect ICMPType = 5 // Redirect ICMPTypeEcho ICMPType = 8 // Echo ICMPTypeRouterAdvertisement ICMPType = 9 // Router Advertisement ICMPTypeRouterSolicitation ICMPType = 10 // Router Solicitation ICMPTypeTimeExceeded ICMPType = 11 // Time Exceeded ICMPTypeParameterProblem ICMPType = 12 // Parameter Problem ICMPTypeTimestamp ICMPType = 13 // Timestamp ICMPTypeTimestampReply ICMPType = 14 // Timestamp Reply ICMPTypePhoturis ICMPType = 40 // Photuris ) // Internet Control Message Protocol (ICMP) Parameters, Updated: 2013-04-19 var icmpTypes = map[ICMPType]string{ 0: "echo reply", 3: "destination unreachable", 5: "redirect", 8: "echo", 9: "router advertisement", 10: "router solicitation", 11: "time exceeded", 12: "parameter problem", 13: "timestamp", 14: "timestamp reply", 40: "photuris", }
{ "pile_set_name": "Github" }
acroread-9.5.5-1.el6_4.1.i686.rpm acroread-plugin-9.5.5-1.el6_4.1.i686.rpm chromium-browser-37.0.2062.120-1.el6.x86_64.rpm flash-plugin-11.2.202.406-1.el6.i686.rpm java-1.5.0-ibm-1.5.0.16.7-1jpp.1.el6_5.x86_64.rpm java-1.5.0-ibm-demo-1.5.0.16.7-1jpp.1.el6_5.x86_64.rpm java-1.5.0-ibm-devel-1.5.0.16.7-1jpp.1.el6_5.i686.rpm java-1.5.0-ibm-devel-1.5.0.16.7-1jpp.1.el6_5.x86_64.rpm java-1.5.0-ibm-javacomm-1.5.0.16.7-1jpp.1.el6_5.x86_64.rpm java-1.5.0-ibm-jdbc-1.5.0.16.7-1jpp.1.el6_5.i686.rpm java-1.5.0-ibm-plugin-1.5.0.16.7-1jpp.1.el6_5.i686.rpm java-1.5.0-ibm-src-1.5.0.16.7-1jpp.1.el6_5.x86_64.rpm java-1.6.0-ibm-1.6.0.16.1-1jpp.1.el6_5.x86_64.rpm java-1.6.0-ibm-demo-1.6.0.16.1-1jpp.1.el6_5.x86_64.rpm java-1.6.0-ibm-devel-1.6.0.16.1-1jpp.1.el6_5.i686.rpm java-1.6.0-ibm-devel-1.6.0.16.1-1jpp.1.el6_5.x86_64.rpm java-1.6.0-ibm-javacomm-1.6.0.16.1-1jpp.1.el6_5.x86_64.rpm java-1.6.0-ibm-jdbc-1.6.0.16.1-1jpp.1.el6_5.x86_64.rpm java-1.6.0-ibm-plugin-1.6.0.16.1-1jpp.1.el6_5.x86_64.rpm java-1.6.0-ibm-src-1.6.0.16.1-1jpp.1.el6_5.x86_64.rpm java-1.7.1-ibm-1.7.1.1.1-1jpp.2.el6.i686.rpm java-1.7.1-ibm-1.7.1.1.1-1jpp.2.el6.x86_64.rpm java-1.7.1-ibm-demo-1.7.1.1.1-1jpp.2.el6.x86_64.rpm java-1.7.1-ibm-devel-1.7.1.1.1-1jpp.2.el6.i686.rpm java-1.7.1-ibm-devel-1.7.1.1.1-1jpp.2.el6.x86_64.rpm java-1.7.1-ibm-jdbc-1.7.1.1.1-1jpp.2.el6.x86_64.rpm java-1.7.1-ibm-plugin-1.7.1.1.1-1jpp.2.el6.x86_64.rpm java-1.7.1-ibm-src-1.7.1.1.1-1jpp.2.el6.x86_64.rpm kmod-kspiceusb-rhel60-4.9-14.el6.x86_64.rpm spice-usb-share-4.9-9.el6.x86_64.rpm system-switch-java-1.1.5-5.el6.noarch.rpm virtio-win-1.7.2-2.el6.noarch.rpm
{ "pile_set_name": "Github" }
from __future__ import print_function from flask_script import Command, Option from skylines.database import db from skylines.model import TrackingFix class Clear(Command): """ Clear all live tracks for a certain user """ option_list = (Option("user", type=int, help="a user ID"),) def run(self, user): result = TrackingFix.query(pilot_id=user).delete() db.session.commit() print("%d live tracks cleared." % result)
{ "pile_set_name": "Github" }
/* * Licensed to the SkyAPM under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The SkyAPM 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. * */ using Microsoft.Extensions.Logging; using System; using System.Threading.Tasks; namespace Surging.Apm.Skywalking.Transport.Grpc.Common { internal class Call { private readonly ILogger _logger; private readonly ConnectionManager _connectionManager; public Call(ILogger logger, ConnectionManager connectionManager) { _logger = logger; _connectionManager = connectionManager; } public async Task Execute(Func<Task> task, Func<string> errMessage) { try { await task(); } catch (Exception ex) { _logger.LogError(errMessage(), ex); _connectionManager.Failure(ex); } } public async Task<T> Execute<T>(Func<Task<T>> task, Func<T> errCallback, Func<string> errMessage) { try { return await task(); } catch (Exception ex) { _logger.LogError(errMessage(), ex); _connectionManager.Failure(ex); return errCallback(); } } } }
{ "pile_set_name": "Github" }
use crate::runtime::{blocking, context, driver, Spawner}; /// Handle to the runtime. /// /// The handle is internally reference-counted and can be freely cloned. A handle can be /// obtained using the [`Runtime::handle`] method. /// /// [`Runtime::handle`]: crate::runtime::Runtime::handle() #[derive(Debug, Clone)] pub(crate) struct Handle { pub(super) spawner: Spawner, /// Handles to the I/O drivers pub(super) io_handle: driver::IoHandle, /// Handles to the signal drivers pub(super) signal_handle: driver::SignalHandle, /// Handles to the time drivers pub(super) time_handle: driver::TimeHandle, /// Source of `Instant::now()` pub(super) clock: driver::Clock, /// Blocking pool spawner pub(super) blocking_spawner: blocking::Spawner, } impl Handle { /// Enter the runtime context. This allows you to construct types that must /// have an executor available on creation such as [`Delay`] or [`TcpStream`]. /// It will also allow you to call methods such as [`tokio::spawn`]. pub(crate) fn enter<F, R>(&self, f: F) -> R where F: FnOnce() -> R, { context::enter(self.clone(), f) } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <Fingerprint> <Header> <Name>JAUS Robots</Name> <Author>Default</Author> <Description>This fingerprint looks for evidence of JAUS Robots traffic.</Description> </Header> <Filter For="JAUS Robots" Name="DstPort"> <DstPort>3794</DstPort> </Filter> <Payload For="JAUS Robots"> <Description>This fingerprint looks for evidence of JAUS Robots traffic.</Description> <Always> <Return Confidence="5"> <Details> <Category>ICS_HOST</Category> <Detail Name="ICSProtocol">JAUS Robots</Detail> </Details> </Return> </Always> </Payload> </Fingerprint>
{ "pile_set_name": "Github" }
CREATE TABLE `tb_teqnorpcun` ( `col_ufqdyzbxyc` longtext CHARACTER SET utf8mb4, UNIQUE KEY `col_ufqdyzbxyc` (`col_ufqdyzbxyc`(19)), UNIQUE KEY `col_ufqdyzbxyc_2` (`col_ufqdyzbxyc`(18)) ) DEFAULT CHARSET=utf8; RENAME TABLE `tb_teqnorpcun` TO `tb_plmerlrvqm`; RENAME TABLE `tb_plmerlrvqm` TO `tb_putsugoooc`; ALTER TABLE `tb_putsugoooc` ADD `col_eykecckmna` float(240,27) FIRST; ALTER TABLE `tb_putsugoooc` ADD `col_anwqmnbtnq` char CHARACTER SET utf8 FIRST; ALTER TABLE `tb_putsugoooc` ADD `col_zqtvmwyqye` tinyblob AFTER `col_ufqdyzbxyc`; ALTER TABLE `tb_putsugoooc` ADD (`col_ptbaaugrfk` timestamp NULL, `col_nzheqbovze` longtext CHARACTER SET utf8mb4); ALTER TABLE `tb_putsugoooc` ADD COLUMN `col_ewavlcwcvf` bigint(210) unsigned zerofill NOT NULL FIRST; ALTER TABLE `tb_putsugoooc` ADD (`col_kxxvdiusoj` tinyblob, `col_gkjiivrixs` double(212,20) NULL); ALTER TABLE `tb_putsugoooc` CHARACTER SET utf8mb4; ALTER TABLE `tb_putsugoooc` ADD PRIMARY KEY (`col_ewavlcwcvf`); ALTER TABLE `tb_putsugoooc` CHANGE COLUMN `col_nzheqbovze` `col_hwjcbrppgw` set('enum_or_set_0','enum_or_set_1','enum_or_set_2') CHARACTER SET utf8 DEFAULT 'enum_or_set_0' FIRST; ALTER TABLE `tb_putsugoooc` CHANGE `col_ufqdyzbxyc` `col_ynpynwnkjv` mediumtext CHARACTER SET utf8mb4 FIRST; ALTER TABLE `tb_putsugoooc` DROP `col_anwqmnbtnq`; ALTER TABLE `tb_putsugoooc` DROP `col_gkjiivrixs`, DROP `col_kxxvdiusoj`; ALTER TABLE `tb_putsugoooc` DROP COLUMN `col_zqtvmwyqye`; ALTER TABLE `tb_putsugoooc` DROP `col_hwjcbrppgw`, DROP `col_ptbaaugrfk`; ALTER TABLE `tb_putsugoooc` DROP `col_eykecckmna`; ALTER TABLE `tb_putsugoooc` DROP COLUMN `col_ewavlcwcvf`; ALTER TABLE `tb_putsugoooc` DROP INDEX `col_ufqdyzbxyc`;
{ "pile_set_name": "Github" }
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import sys import ssl import socket import tlslite.api from Peach.Publishers.tcp import TcpListener from Peach.publisher import PublisherSoftException from Peach.Engine.common import PeachException class SSL(TcpListener): def __init__(self, host, port, cert, pkey, timeout=0.25): TcpListener.__init__(self, host, port, timeout) self.cert = cert self.pkey = pkey def accept(self): print("[*] Waiting for incoming connection") client, addr = self._listen.accept() print("[*] Client:", addr[0], addr[1]) print("[*] Wrapping socket to TLS/SSL") try: self._socket = ssl.wrap_socket(client, server_side=True, certfile=self.cert, keyfile=self.pkey, do_handshake_on_connect=False) except ssl.SSLError as e: raise PeachException(str(e)) print("[*] Performing TLS/SSL handshake") try: self._socket.do_handshake() except ssl.SSLError as e: raise PeachException(str(e)) def close(self): try: if self._socket is not None: self._socket.shutdown(socket.SHUT_RDWR) self._socket.close() except: pass finally: self._socket = None class TLSLiteServer(TcpListener): def __init__(self, host, port, version, cert, pkey, timeout=0.25): TcpListener.__init__(self, host, port, timeout) self.cert = cert self.pkey = pkey self.version = version try: with open(self.cert) as fd: cert_content = fd.read() except IOError: raise PeachException("Unable to open %s" % self.cert) x509 = tlslite.api.X509() x509.parse(cert_content) self.certChain = tlslite.api.X509CertChain([x509]) try: with open(self.pkey) as fd: pkey_content = fd.read() except IOError: raise PeachException("Unable to open %s" % self.pkey) self.privateKey = tlslite.api.parsePEMKey(pkey_content, private=True) def accept(self): print("[*] Waiting for incoming connection") sys.stdout.flush() client, addr = self._listen.accept() print("[*] Connected by %s:%s" % (addr[0], str(addr[1]))) print("[*] Wrapping socket to TLS/SSL") try: self._socket = tlslite.api.TLSConnection(client) except: client.close() value = sys.exc_info()[1] msg = "[!] Wrapping socket failed, reason: %s" % value raise PublisherSoftException(msg) print("[*] Performing TLS/SSL handshake)") try: self._socket.handshakeServer(certChain=self.certChain, privateKey=self.privateKey, #reqCert=True, nextProtos=[self.version]) except: self.close() value = sys.exc_info()[1] msg = "[!] Performing TLS/SSL handshake failed, reason: %s" % value raise PublisherSoftException(msg) print("done!") class SPDYPublisher(TLSLiteServer): def __init__(self, host, port, cert, pkey, timeout=0.25): TLSLiteServer.__init__(self, host, port, cert, pkey, timeout)
{ "pile_set_name": "Github" }
/* * ----------------------------------------------------------------------- * Copyright © 2013-2018 Meno Hochschild, <http://www.menodata.de/> * ----------------------------------------------------------------------- * This file (CopticEra.java) is part of project Time4J. * * Time4J is free software: You can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 2.1 of the License, or * (at your option) any later version. * * Time4J is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Time4J. If not, see <http://www.gnu.org/licenses/>. * ----------------------------------------------------------------------- */ package net.time4j.calendar; import net.time4j.engine.CalendarEra; import net.time4j.format.CalendarText; import net.time4j.format.TextWidth; import java.util.Locale; /** * <p>The Coptic calendar only supports one single era called &quot;Anno Martyrum&quot; with the * numerical value {@code 1} which is sometimes also called &quot;Diocletian era&quot; and starts * on Julian date AD-284-08-29. </p> * * @author Meno Hochschild * @since 3.11/4.8 */ /*[deutsch] * <p>Der koptische Kalender unterst&uuml;tzt nur eine einzige &Auml;ra, die &quot;Anno Martyrum&quot; * oder manchmal die diokletianische &Auml;ra genannt wird, den numerischen Wert {@code 1} hat und zum * julianischen Datum AD-284-08-29 beginnt. </p> * * @author Meno Hochschild * @since 3.11/4.8 */ public enum CopticEra implements CalendarEra { //~ Statische Felder/Initialisierungen -------------------------------- /** * Called after the victims of persecutions against Christians by the Roman emperator Diocletian * (often abbreviated as &quot;A.M.&quot;). */ /*[deutsch] * Benannt nach den Opfern der Christenverfolgungen des r&ouml;mischen Kaisers Diocletian * (oft als &quot;A.M.&quot; abgek&uuml;rzt). */ ANNO_MARTYRUM; //~ Methoden ---------------------------------------------------------- /** * <p>Equivalent to the expression {@code getDisplayName(locale, TextWidth.WIDE)}. </p> * * @param locale language setting * @return descriptive text (long form, never {@code null}) * @see #getDisplayName(Locale, TextWidth) * @since 3.11/4.8 */ /*[deutsch] * <p>Entspricht dem Ausdruck {@code getDisplayName(locale, TextWidth.WIDE)}. </p> * * @param locale language setting * @return descriptive text (long form, never {@code null}) * @see #getDisplayName(Locale, TextWidth) * @since 3.11/4.8 */ public String getDisplayName(Locale locale) { return this.getDisplayName(locale, TextWidth.WIDE); } /** * <p>Gets the description text dependent on the locale and style parameters. </p> * * <p>The second argument controls the width of description. </p> * * @param locale language setting * @param width text width * @return descriptive text for given locale and style (never {@code null}) * @since 3.11/4.8 */ /*[deutsch] * <p>Liefert den sprachabh&auml;ngigen Beschreibungstext. </p> * * <p>&Uuml;ber das zweite Argument kann gesteuert werden, ob eine kurze * oder eine lange Form des Beschreibungstexts ausgegeben werden soll. Das * ist besonders sinnvoll in Benutzeroberfl&auml;chen, wo zwischen der * Beschriftung und der detaillierten Erl&auml;uterung einer graphischen * Komponente unterschieden wird. </p> * * @param locale language setting * @param width text width * @return descriptive text for given locale and style (never {@code null}) * @since 3.11/4.8 */ public String getDisplayName( Locale locale, TextWidth width ) { CalendarText names = CalendarText.getInstance("coptic", locale); return names.getEras(width).print(this); } }
{ "pile_set_name": "Github" }
import { SHOW_MSG, HIDE_MSG } from '../types' const state = { message:{ type: '', content: '', title: '' } } const mutations = { [SHOW_MSG](state , action){ state.message = {...action} }, [HIDE_MSG](state, action){ state.message = { type: '', content: '', title: '' } } } export default { state, mutations }
{ "pile_set_name": "Github" }
/* * S390 CCW boot loader * * Copyright (c) 2013 Alexander Graf <[email protected]> * * This work is licensed under the terms of the GNU GPL, version 2 or (at * your option) any later version. See the COPYING file in the top-level * directory. */ #ifndef S390_CCW_H #define S390_CCW_H /* #define DEBUG */ typedef unsigned char u8; typedef unsigned short u16; typedef unsigned int u32; typedef unsigned long long u64; typedef unsigned long ulong; typedef unsigned char __u8; typedef unsigned short __u16; typedef unsigned int __u32; typedef unsigned long long __u64; #define true 1 #define false 0 #define PAGE_SIZE 4096 #ifndef EIO #define EIO 1 #endif #ifndef EBUSY #define EBUSY 2 #endif #ifndef NULL #define NULL 0 #endif #ifndef MIN #define MIN(a, b) (((a) < (b)) ? (a) : (b)) #endif #ifndef MIN_NON_ZERO #define MIN_NON_ZERO(a, b) ((a) == 0 ? (b) : \ ((b) == 0 ? (a) : (MIN(a, b)))) #endif #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) #include "cio.h" #include "iplb.h" /* start.s */ void disabled_wait(void); void consume_sclp_int(void); void consume_io_int(void); /* main.c */ void panic(const char *string); void write_subsystem_identification(void); void write_iplb_location(void); extern char stack[PAGE_SIZE * 8] __attribute__((__aligned__(PAGE_SIZE))); unsigned int get_loadparm_index(void); /* sclp.c */ void sclp_print(const char *string); void sclp_set_write_mask(uint32_t receive_mask, uint32_t send_mask); void sclp_setup(void); void sclp_get_loadparm_ascii(char *loadparm); int sclp_read(char *str, size_t count); /* virtio.c */ unsigned long virtio_load_direct(ulong rec_list1, ulong rec_list2, ulong subchan_id, void *load_addr); bool virtio_is_supported(SubChannelId schid); void virtio_blk_setup_device(SubChannelId schid); int virtio_read(ulong sector, void *load_addr); u64 get_clock(void); ulong get_second(void); /* bootmap.c */ void zipl_load(void); /* jump2ipl.c */ void jump_to_IPL_code(uint64_t address); void jump_to_low_kernel(void); /* menu.c */ void menu_set_parms(uint8_t boot_menu_flag, uint32_t boot_menu_timeout); int menu_get_zipl_boot_index(const char *menu_data); bool menu_is_enabled_zipl(void); int menu_get_enum_boot_index(bool *valid_entries); bool menu_is_enabled_enum(void); #define MAX_BOOT_ENTRIES 31 static inline void fill_hex(char *out, unsigned char val) { const char hex[] = "0123456789abcdef"; out[0] = hex[(val >> 4) & 0xf]; out[1] = hex[val & 0xf]; } static inline void fill_hex_val(char *out, void *ptr, unsigned size) { unsigned char *value = ptr; unsigned int i; for (i = 0; i < size; i++) { fill_hex(&out[i*2], value[i]); } } static inline void print_int(const char *desc, u64 addr) { char out[] = ": 0xffffffffffffffff\n"; fill_hex_val(&out[4], &addr, sizeof(addr)); sclp_print(desc); sclp_print(out); } static inline void debug_print_int(const char *desc, u64 addr) { #ifdef DEBUG print_int(desc, addr); #endif } static inline void debug_print_addr(const char *desc, void *p) { #ifdef DEBUG debug_print_int(desc, (unsigned int)(unsigned long)p); #endif } /*********************************************** * Hypercall functions * ***********************************************/ #define KVM_S390_VIRTIO_NOTIFY 0 #define KVM_S390_VIRTIO_RESET 1 #define KVM_S390_VIRTIO_SET_STATUS 2 #define KVM_S390_VIRTIO_CCW_NOTIFY 3 static inline void yield(void) { asm volatile ("diag 0,0,0x44" : : : "memory", "cc"); } #define MAX_SECTOR_SIZE 4096 static inline void sleep(unsigned int seconds) { ulong target = get_second() + seconds; while (get_second() < target) { yield(); } } static inline void IPL_assert(bool term, const char *message) { if (!term) { sclp_print("\n! "); sclp_print(message); panic(" !\n"); /* no return */ } } static inline void IPL_check(bool term, const char *message) { if (!term) { sclp_print("\n! WARNING: "); sclp_print(message); sclp_print(" !\n"); } } extern const unsigned char ebc2asc[256]; static inline void ebcdic_to_ascii(const char *src, char *dst, unsigned int size) { unsigned int i; for (i = 0; i < size; i++) { unsigned c = src[i]; dst[i] = ebc2asc[c]; } } #endif /* S390_CCW_H */
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: 88ac36f8b5d597e4eb221c608e14e06d MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
{ "A fast and open replacement for Windows and macOS &sdot; elementary OS": "A fast and open replacement for Windows and macOS ⋅ elementary OS", "Support": "მხარდაჭერა", "Developer": "დეველოპერი", "Get Involved": "ჩაერიეთ", "Store": "მაჩაზია", "This is a development site.": "ეს არის დეველოპმენტის საიტი.", "You are viewing a development version of our site. Some pages here may not work or act as you expect. If you got here by accident please go to <a href=\"http://elementary.io\">elementary.io</a>, our actual website address.": "You are viewing a development version of our site. Some pages here may not work or act as you expect. If you got here by accident please go to <a href=\"http://elementary.io\">elementary.io</a>, our actual website address.", "Copyright &copy; 2017 elementary LLC.": "Copyright © 2017 elementary LLC.", "Language": "ენა", "Change Site Language": "ლეცვალეთ საიტის ენა", "Brand": "ბრენდი", "Privacy Policy": "Privacy Policy", "Team": "Team", "Open Source": "჊ია წყარო" }
{ "pile_set_name": "Github" }
DUNE ?= dune all: @$(DUNE) build test: @$(DUNE) runtest check: test clean: @$(DUNE) clean .PHONY: check test all clean .PHONY: all-supported-ocaml-versions all-supported-ocaml-versions: dune build @runtest --workspace dune-workspace.dev
{ "pile_set_name": "Github" }
// // UIFont+PingFang.h // SHSegmentedControlTableView // // Created by angle on 2017/10/10. // Copyright © 2017幎 angle. All rights reserved. // #import <UIKit/UIKit.h> @interface UIFont (PingFang_sh) + (UIFont *)sh_pingFangSCFontOfSize:(CGFloat)fontSize; + (UIFont *)sh_boldPingFangSCFontOfSize:(CGFloat)fontSize; @end
{ "pile_set_name": "Github" }
INCLUDES = ../../common ../../lib all: $(DEFAULT_TARGETS) .PHONY: all riscv.uo: ../../lib/assemblerLib.uo ../../lib/MutableMap16.uo riscv.sml riscv.ui $(HOLMOSMLC) -c -toplevel assemblerLib.uo MutableMap16.ui riscv.sml
{ "pile_set_name": "Github" }
package com.hiernate.persistence; import java.sql.Date; public class Waichu { private int id; private String content; private Date time1; private Date time2; private String name1; private String department; private int state; public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName1() { return name1; } public void setName1(String name1) { this.name1 = name1; } public int getState() { return state; } public void setState(int state) { this.state = state; } public Date getTime1() { return time1; } public void setTime1(Date time1) { this.time1 = time1; } public Date getTime2() { return time2; } public void setTime2(Date time2) { this.time2 = time2; } }
{ "pile_set_name": "Github" }
<resources> <!-- keyword. --> <string name="date_format_short">d/M</string> <string name="date_format_long">d MMM</string> <string name="date_format_widget_short">EEEE, d MMM</string> <string name="date_format_widget_long">EEEE, d MMM</string> <string name="date_format_widget_oreo_style">EEEE, d MMM│</string> </resources>
{ "pile_set_name": "Github" }
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/robomaker/RoboMaker_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> namespace Aws { namespace RoboMaker { namespace Model { enum class SimulationJobBatchErrorCode { NOT_SET, InternalServiceError }; namespace SimulationJobBatchErrorCodeMapper { AWS_ROBOMAKER_API SimulationJobBatchErrorCode GetSimulationJobBatchErrorCodeForName(const Aws::String& name); AWS_ROBOMAKER_API Aws::String GetNameForSimulationJobBatchErrorCode(SimulationJobBatchErrorCode value); } // namespace SimulationJobBatchErrorCodeMapper } // namespace Model } // namespace RoboMaker } // namespace Aws
{ "pile_set_name": "Github" }
// // Copyright 2020 Electronic Arts Inc. // // TiberianDawn.DLL and RedAlert.dll and corresponding source code 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. // TiberianDawn.DLL and RedAlert.dll and corresponding source code is distributed // in the hope that it will be useful, but with permitted additional restrictions // under Section 7 of the GPL. See the GNU General Public License in LICENSE.TXT // distributed with this program. You should have received a copy of the // GNU General Public License along with permitted additional restrictions // with this program. If not, see https://github.com/electronicarts/CnC_Remastered_Collection /* $Header: /CounterStrike/INTRO.H 1 3/03/97 10:24a Joe_bostic $ */ /*********************************************************************************************** *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** *********************************************************************************************** * * * Project Name : Command & Conquer * * * * File Name : INTRO.H * * * * Programmer : Barry W. Green * * * * Start Date : May 8, 1995 * * * * Last Update : May 8, 1995 [BWG] * * * *---------------------------------------------------------------------------------------------* * Functions: * * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ #ifndef INTRO_H #define INTRO_H void Choose_Side(void); #endif
{ "pile_set_name": "Github" }
#ifndef VIEW_GRASP_H #define VIEW_GRASP_H #include <Klampt/Contact/Grasp.h> #include <KrisLibrary/robotics/Stability.h> #include <KrisLibrary/GLdraw/GLColor.h> #include "ViewHold.h" /** @ingroup View * @brief Displays a grasp using OpenGL. */ struct ViewGrasp { ViewGrasp(); void Draw(const Grasp& g); ViewRobot* viewRobot; ViewContact viewContact; GLDraw::GLColor forceColor; }; #endif
{ "pile_set_name": "Github" }
#import "MenuItemPostsViewController.h" #import "PostService.h" #import "WordPress-Swift.h" @interface MenuItemAbstractPostsViewController () <MenuItemSourcePostAbstractViewSubclass> @end @interface MenuItemPostsViewController () @end @implementation MenuItemPostsViewController - (NSString *)sourceItemType { return self.postType; } - (NSPredicate *)defaultFetchRequestPredicate { NSPredicate *predicate = [super defaultFetchRequestPredicate]; NSPredicate *postTypePredicate = [NSPredicate predicateWithFormat:@"postType = %@", self.sourceItemType]; return [NSCompoundPredicate andPredicateWithSubpredicates:@[predicate, postTypePredicate]]; } - (NSFetchRequest *)fetchRequest { NSFetchRequest *fetchRequest = [super fetchRequest]; NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"date_created_gmt" ascending:NO]; [fetchRequest setSortDescriptors:@[sortDescriptor]]; return fetchRequest; } - (Class)entityClass { return [Post class]; } @end
{ "pile_set_name": "Github" }
{ "runtime": ["OpenCL"], "example": "Huffman Encoding/Decoding", "overview": [ "This is an implementation of a huffman encoding/decoding algorithm targeting execution on an SDAccel supported FPGA acceleration card." ], "targets": [ "sw_emu", "hw" ], "xcl": false, "opencv": true, "cmd_args": "BUILD/krnl_huffman.xclbin -b PROJECT/data/rect_1024.bmp", "host_exe": "huffman", "host_srcs": "src/main.cpp src/huffmancodec_optimized.cpp src/huffmancodec_naive.cpp src/bit_io.cpp src/huffmancodec_optimized_cpuonly.cpp", "host_hdrs": "src/bit_io.h src/huffmancodec_naive.h src/huffmancodec_optimized.h src/huffmancodec_optimized_cpuonly.h", "output_files": "decoded.bmp", "libs": [ "logger", "cmdparser", "simplebmp", "xcl2" ], "containers" : [ { "name" : "krnl_huffman", "accelerators": [ { "name": "encode", "clflags" : "--xp param:compiler.version=31", "location": "src/krnl_huffman_singleptr.cl" }, { "name": "decode", "clflags" : "--xp param:compiler.version=31", "location": "src/krnl_huffman_singleptr.cl" } ] } ], "contributors": [ { "group": "Xilinx", "url": "http://www.xilinx.com" } ], "testinfo": { "level_up": [ { "hw_emu": "1" } ] } }
{ "pile_set_name": "Github" }
/** * @author Roger Wu */ (function($){ $.fn.jDrag = function(options){ if (typeof options == 'string') { if (options == 'destroy') return this.each(function(){ $(this).unbind('mousedown', $.rwdrag.start); $.data(this, 'pp-rwdrag', null); }); } return this.each(function(){ var el = $(this); $.data($.rwdrag, 'pp-rwdrag', { options: $.extend({ el: el, obj: el }, options) }); if (options.event) $.rwdrag.start(options.event); else { var select = options.selector; $(select, obj).bind('mousedown', $.rwdrag.start); } }); }; $.rwdrag = { start: function(e){ document.onselectstart=function(e){return false};//犁止选择 var data = $.data(this, 'pp-rwdrag'); var el = data.options.el[0]; $.data(el, 'pp-rwdrag', { options: data.options }); if (!$.rwdrag.current) { $.rwdrag.current = { el: el, oleft: parseInt(el.style.left) || 0, otop: parseInt(el.style.top) || 0, ox: e.pageX || e.screenX, oy: e.pageY || e.screenY }; $(document).bind("mouseup", $.rwdrag.stop).bind("mousemove", $.rwdrag.drag); } }, drag: function(e){ if (!e) var e = window.event; var current = $.rwdrag.current; var data = $.data(current.el, 'pp-rwdrag'); var left = (current.oleft + (e.pageX || e.clientX) - current.ox); var top = (current.otop + (e.pageY || e.clientY) - current.oy); if (top < 1) top = 0; if (data.options.move == 'horizontal') { if ((data.options.minW && left >= $(data.options.obj).cssv("left") + data.options.minW) && (data.options.maxW && left <= $(data.options.obj).cssv("left") + data.options.maxW)) current.el.style.left = left + 'px'; else if (data.options.scop) { if (data.options.relObj) { if ((left - parseInt(data.options.relObj.style.left)) > data.options.cellMinW) { current.el.style.left = left + 'px'; } } else current.el.style.left = left + 'px'; } } else if (data.options.move == 'vertical') { current.el.style.top = top + 'px'; } else { var selector = data.options.selector ? $(data.options.selector, data.options.obj) : $(data.options.obj); if (left >= -selector.outerWidth() * 2 / 3 && top >= 0 && (left + selector.outerWidth() / 3 < $(window).width()) && (top + selector.outerHeight() < $(window).height())) { //浏览噚猩攟后有bug先泚释掉 current.el.style.left = left + 'px'; current.el.style.top = top + 'px'; } } if (data.options.drag) { data.options.drag.apply(current.el, [current.el, e]); } return $.rwdrag.preventEvent(e); }, stop: function(e){ var current = $.rwdrag.current; var data = $.data(current.el, 'pp-rwdrag'); $(document).unbind('mousemove', $.rwdrag.drag).unbind('mouseup', $.rwdrag.stop); if (data.options.stop) { data.options.stop.apply(current.el, [current.el, e]); } $.rwdrag.current = null; document.onselectstart=function(e){return true};//启甚选择 return $.rwdrag.preventEvent(e); }, preventEvent:function(e){ if (e.stopPropagation) e.stopPropagation(); if (e.preventDefault) e.preventDefault(); return false; } }; })(jQuery);
{ "pile_set_name": "Github" }
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Plato.Categories.Models; using Plato.Categories.Services; using Plato.Categories.ViewModels; using Plato.Questions.Categories.Models; using PlatoCore.Navigation.Abstractions; namespace Plato.Questions.Categories.ViewComponents { public class QuestionCategoryDropDownViewComponent : ViewComponent { private readonly ICategoryService<Category> _categoryService; public QuestionCategoryDropDownViewComponent(ICategoryService<Category> categoryService) { _categoryService = categoryService; } public async Task<IViewComponentResult> InvokeAsync(CategoryDropDownViewModel model) { if (model == null) { model = new CategoryDropDownViewModel(); } if (model.SelectedCategories == null) { model.SelectedCategories = new int[0]; } model.Categories = await BuildSelectionsAsync(model); return View(model); } private async Task<IList<Selection<CategoryBase>>> BuildSelectionsAsync(CategoryDropDownViewModel model) { // Get categories var categories = await _categoryService.GetResultsAsync( model.Options, new PagerOptions() { Page = 1, Size = int.MaxValue }); // Indicate selections return categories?.Data?.Select(c => new Selection<CategoryBase> { IsSelected = model.SelectedCategories.Any(v => v == c.Id), Value = c }) .ToList(); } } }
{ "pile_set_name": "Github" }
#!/bin/bash # # NBD test case for overriding BDRV_O_PROTOCOL by explicitly specifying # a driver # # Copyright (C) 2015 Red Hat, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # creator [email protected] seq="$(basename $0)" echo "QA output created by $seq" here="$PWD" tmp=/tmp/$$ status=1 # failure is the default! _cleanup() { _cleanup_test_img } trap "_cleanup; exit \$status" 0 1 2 3 15 # get standard environment, filters and checks . ./common.rc . ./common.filter _supported_fmt raw _supported_proto nbd _supported_os Linux _make_test_img 64M # This should not crash echo "{'execute': 'qmp_capabilities'} {'execute': 'human-monitor-command', 'arguments': {'command-line': 'qemu-io drv \"read -P 0 0 64k\"'}} {'execute': 'quit'}" \ | $QEMU -nographic -drive id=drv,if=none,file="$TEST_IMG",driver=nbd \ -qmp stdio -nodefaults \ | _filter_qmp | _filter_qemu_io # success, all done echo echo '*** done' rm -f $seq.full status=0
{ "pile_set_name": "Github" }
# -*- coding: utf-8 -*- from __future__ import unicode_literals from pyscada import core __version__ = core.__version__ __author__ = core.__author__ PROTOCOL_ID = 2 default_app_config = 'pyscada.systemstat.apps.PyScadaSystemstatConfig' parent_process_list = [{'pk': PROTOCOL_ID, 'label': 'pyscada.systemstat', 'process_class': 'pyscada.systemstat.worker.Process', 'process_class_kwargs': '{"dt_set":30}', 'enabled': True}]
{ "pile_set_name": "Github" }
package com.alipay.api.response; import com.alipay.api.internal.mapping.ApiField; import com.alipay.api.AlipayResponse; /** * ALIPAY API: alipay.boss.prod.arrangement.offline.query response. * * @author auto create * @since 1.0, 2020-06-02 14:17:35 */ public class AlipayBossProdArrangementOfflineQueryResponse extends AlipayResponse { private static final long serialVersionUID = 5345521288819949994L; /** * 商户的筟纊状态 */ @ApiField("sign_status") private String signStatus; public void setSignStatus(String signStatus) { this.signStatus = signStatus; } public String getSignStatus( ) { return this.signStatus; } }
{ "pile_set_name": "Github" }
--TEST-- Test is_callable() function : usage variations - undefined functions --INI-- precision=14 error_reporting = E_ALL & ~E_NOTICE | E_STRICT --FILE-- <?php /* Prototype: bool is_callable ( mixed $var [, bool $syntax_only [, string &$callable_name]] ); Description: Verify that the contents of a variable can be called as a function In case of objects, $var = array($SomeObject, 'MethodName') */ /* Prototype: void check_iscallable( $functions ); Description: use iscallable() on given string to check for valid function name returns true if valid function name, false otherwise */ function check_iscallable( $functions ) { $counter = 1; foreach($functions as $func) { echo "-- Iteration $counter --\n"; var_dump( is_callable($func) ); //given only $var argument var_dump( is_callable($func, TRUE) ); //given $var and $syntax argument var_dump( is_callable($func, TRUE, $callable_name) ); echo $callable_name, "\n"; var_dump( is_callable($func, FALSE) ); //given $var and $syntax argument var_dump( is_callable($func, FALSE, $callable_name) ); echo $callable_name, "\n"; $counter++; } } echo "\n*** Testing is_callable() on undefined functions ***\n"; $undef_functions = array ( "", //empty string '', " ", //string with a space ' ', "12356", "\0", '\0', "hello world", 'hello world', "welcome\0", 'welcome\0', "==%%%***$$$@@@!!", "false", "\070", '\t', //escape character '\007', '123', 'echo()' ); /* use check_iscallable() to check whether given string is valid function name * expected: true with $syntax = TRUE * false with $syntax = FALSE */ check_iscallable($undef_functions); ?> ===DONE=== --EXPECTF-- *** Testing is_callable() on undefined functions *** -- Iteration 1 -- bool(false) bool(true) bool(true) bool(false) bool(false) -- Iteration 2 -- bool(false) bool(true) bool(true) bool(false) bool(false) -- Iteration 3 -- bool(false) bool(true) bool(true) bool(false) bool(false) -- Iteration 4 -- bool(false) bool(true) bool(true) bool(false) bool(false) -- Iteration 5 -- bool(false) bool(true) bool(true) 12356 bool(false) bool(false) 12356 -- Iteration 6 -- bool(false) bool(true) bool(true) bool(false) bool(false) -- Iteration 7 -- bool(false) bool(true) bool(true) \0 bool(false) bool(false) \0 -- Iteration 8 -- bool(false) bool(true) bool(true) hello world bool(false) bool(false) hello world -- Iteration 9 -- bool(false) bool(true) bool(true) hello world bool(false) bool(false) hello world -- Iteration 10 -- bool(false) bool(true) bool(true) welcome bool(false) bool(false) welcome -- Iteration 11 -- bool(false) bool(true) bool(true) welcome\0 bool(false) bool(false) welcome\0 -- Iteration 12 -- bool(false) bool(true) bool(true) ==%%%***$$$@@@!! bool(false) bool(false) ==%%%***$$$@@@!! -- Iteration 13 -- bool(false) bool(true) bool(true) false bool(false) bool(false) false -- Iteration 14 -- bool(false) bool(true) bool(true) 8 bool(false) bool(false) 8 -- Iteration 15 -- bool(false) bool(true) bool(true) \t bool(false) bool(false) \t -- Iteration 16 -- bool(false) bool(true) bool(true) \007 bool(false) bool(false) \007 -- Iteration 17 -- bool(false) bool(true) bool(true) 123 bool(false) bool(false) 123 -- Iteration 18 -- bool(false) bool(true) bool(true) echo() bool(false) bool(false) echo() ===DONE===
{ "pile_set_name": "Github" }
// Core javascript helper functions // basic browser identification & version var isOpera = (navigator.userAgent.indexOf("Opera")>=0) && parseFloat(navigator.appVersion); var isIE = ((document.all) && (!isOpera)) && parseFloat(navigator.appVersion.split("MSIE ")[1].split(";")[0]); // Cross-browser event handlers. function addEvent(obj, evType, fn) { if (obj.addEventListener) { obj.addEventListener(evType, fn, false); return true; } else if (obj.attachEvent) { var r = obj.attachEvent("on" + evType, fn); return r; } else { return false; } } function removeEvent(obj, evType, fn) { if (obj.removeEventListener) { obj.removeEventListener(evType, fn, false); return true; } else if (obj.detachEvent) { obj.detachEvent("on" + evType, fn); return true; } else { return false; } } function cancelEventPropagation(e) { if (!e) e = window.event; e.cancelBubble = true; if (e.stopPropagation) e.stopPropagation(); } // quickElement(tagType, parentReference [, textInChildNode, attribute, attributeValue ...]); function quickElement() { var obj = document.createElement(arguments[0]); if (arguments[2]) { var textNode = document.createTextNode(arguments[2]); obj.appendChild(textNode); } var len = arguments.length; for (var i = 3; i < len; i += 2) { obj.setAttribute(arguments[i], arguments[i+1]); } arguments[1].appendChild(obj); return obj; } // "a" is reference to an object function removeChildren(a) { while (a.hasChildNodes()) a.removeChild(a.lastChild); } // ---------------------------------------------------------------------------- // Cross-browser xmlhttp object // from http://jibbering.com/2002/4/httprequest.html // ---------------------------------------------------------------------------- var xmlhttp; /*@cc_on @*/ /*@if (@_jscript_version >= 5) try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (E) { xmlhttp = false; } } @else xmlhttp = false; @end @*/ if (!xmlhttp && typeof XMLHttpRequest != 'undefined') { xmlhttp = new XMLHttpRequest(); } // ---------------------------------------------------------------------------- // Find-position functions by PPK // See http://www.quirksmode.org/js/findpos.html // ---------------------------------------------------------------------------- function findPosX(obj) { var curleft = 0; if (obj.offsetParent) { while (obj.offsetParent) { curleft += obj.offsetLeft - ((isOpera) ? 0 : obj.scrollLeft); obj = obj.offsetParent; } // IE offsetParent does not include the top-level if (isIE && obj.parentElement){ curleft += obj.offsetLeft - obj.scrollLeft; } } else if (obj.x) { curleft += obj.x; } return curleft; } function findPosY(obj) { var curtop = 0; if (obj.offsetParent) { while (obj.offsetParent) { curtop += obj.offsetTop - ((isOpera) ? 0 : obj.scrollTop); obj = obj.offsetParent; } // IE offsetParent does not include the top-level if (isIE && obj.parentElement){ curtop += obj.offsetTop - obj.scrollTop; } } else if (obj.y) { curtop += obj.y; } return curtop; } //----------------------------------------------------------------------------- // Date object extensions // ---------------------------------------------------------------------------- Date.prototype.getTwelveHours = function() { hours = this.getHours(); if (hours == 0) { return 12; } else { return hours <= 12 ? hours : hours-12 } } Date.prototype.getTwoDigitMonth = function() { return (this.getMonth() < 9) ? '0' + (this.getMonth()+1) : (this.getMonth()+1); } Date.prototype.getTwoDigitDate = function() { return (this.getDate() < 10) ? '0' + this.getDate() : this.getDate(); } Date.prototype.getTwoDigitTwelveHour = function() { return (this.getTwelveHours() < 10) ? '0' + this.getTwelveHours() : this.getTwelveHours(); } Date.prototype.getTwoDigitHour = function() { return (this.getHours() < 10) ? '0' + this.getHours() : this.getHours(); } Date.prototype.getTwoDigitMinute = function() { return (this.getMinutes() < 10) ? '0' + this.getMinutes() : this.getMinutes(); } Date.prototype.getTwoDigitSecond = function() { return (this.getSeconds() < 10) ? '0' + this.getSeconds() : this.getSeconds(); } Date.prototype.getHourMinute = function() { return this.getTwoDigitHour() + ':' + this.getTwoDigitMinute(); } Date.prototype.getHourMinuteSecond = function() { return this.getTwoDigitHour() + ':' + this.getTwoDigitMinute() + ':' + this.getTwoDigitSecond(); } Date.prototype.strftime = function(format) { var fields = { c: this.toString(), d: this.getTwoDigitDate(), H: this.getTwoDigitHour(), I: this.getTwoDigitTwelveHour(), m: this.getTwoDigitMonth(), M: this.getTwoDigitMinute(), p: (this.getHours() >= 12) ? 'PM' : 'AM', S: this.getTwoDigitSecond(), w: '0' + this.getDay(), x: this.toLocaleDateString(), X: this.toLocaleTimeString(), y: ('' + this.getFullYear()).substr(2, 4), Y: '' + this.getFullYear(), '%' : '%' }; var result = '', i = 0; while (i < format.length) { if (format.charAt(i) === '%') { result = result + fields[format.charAt(i + 1)]; ++i; } else { result = result + format.charAt(i); } ++i; } return result; } // ---------------------------------------------------------------------------- // String object extensions // ---------------------------------------------------------------------------- String.prototype.pad_left = function(pad_length, pad_string) { var new_string = this; for (var i = 0; new_string.length < pad_length; i++) { new_string = pad_string + new_string; } return new_string; } String.prototype.strptime = function(format) { var split_format = format.split(/[.\-/]/); var date = this.split(/[.\-/]/); var i = 0; while (i < split_format.length) { switch (split_format[i]) { case "%d": var day = date[i]; break; case "%m": var month = date[i] - 1; break; case "%Y": var year = date[i]; break; case "%y": var year = date[i]; break; } ++i; }; return new Date(year, month, day); } // ---------------------------------------------------------------------------- // Get the computed style for and element // ---------------------------------------------------------------------------- function getStyle(oElm, strCssRule){ var strValue = ""; if(document.defaultView && document.defaultView.getComputedStyle){ strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule); } else if(oElm.currentStyle){ strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){ return p1.toUpperCase(); }); strValue = oElm.currentStyle[strCssRule]; } return strValue; }
{ "pile_set_name": "Github" }
<!-- HTML header for doxygen 1.8.13--> <!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.6"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>Generic Image Library: Pixel Locator</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="doxygen.css" rel="stylesheet" type="text/css" /> <link href="doxygen-boost.css" rel="stylesheet" type="text/css"/> </head> <body> <div class="boost-header"> <table border="0" cellpadding="7" cellspacing="0" width="100%" summary="header"> <tr> <td valign="top" width="300"> <h3><a href="../index.html"><img alt="Boost GIL" src="../_static/gil.png" border="0"></a></h3> </td> <td ><h1 align="center"><a href="../index.html"></a></h1></td> <td></td> </tr> </table> </div> <hr/> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <!-- Generated by Doxygen 1.8.6 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="#groups">Modules</a> </div> <div class="headertitle"> <div class="title">Pixel Locator</div> </div> </div><!--header--> <div class="contents"> <p>Generalization of an iterator to multiple dimensions. <a href="#details">More...</a></p> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="groups"></a> Modules</h2></td></tr> <tr class="memitem:group___pixel_locator_concept"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___pixel_locator_concept.html">Concepts</a></td></tr> <tr class="memdesc:group___pixel_locator_concept"><td class="mdescLeft">&#160;</td><td class="mdescRight">Pixel locator concepts. <br/></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:group___pixel_locator_model"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group___pixel_locator_model.html">Models</a></td></tr> <tr class="memdesc:group___pixel_locator_model"><td class="mdescLeft">&#160;</td><td class="mdescRight">Pixel locator models. <br/></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2> <p>Generalization of an iterator to multiple dimensions. </p> </div><!-- contents --> <!-- HTML footer for doxygen 1.8.13--> <!-- start footer part --> <hr class="footer"/> <address class="footer"> <small> Generated on Wed Dec 5 2018 20:05:50 for Generic Image Library by &#160;<a href="http://www.doxygen.org/index.html">doxygen</a> 1.8.6 </small> </address> </body> </html>
{ "pile_set_name": "Github" }
module Mccloud module Provider module Core class Ip attr_reader :env attr_accessor :provider attr_accessor :name attr_accessor :auto_selection def initialize(env) @auto_selection=true @env=env end def auto_selected? return auto_selection end end end end end
{ "pile_set_name": "Github" }
var Stream = require('stream').Stream module.exports = legacy function legacy (fs) { return { ReadStream: ReadStream, WriteStream: WriteStream } function ReadStream (path, options) { if (!(this instanceof ReadStream)) return new ReadStream(path, options); Stream.call(this); var self = this; this.path = path; this.fd = null; this.readable = true; this.paused = false; this.flags = 'r'; this.mode = 438; /*=0666*/ this.bufferSize = 64 * 1024; options = options || {}; // Mixin options into this var keys = Object.keys(options); for (var index = 0, length = keys.length; index < length; index++) { var key = keys[index]; this[key] = options[key]; } if (this.encoding) this.setEncoding(this.encoding); if (this.start !== undefined) { if ('number' !== typeof this.start) { throw TypeError('start must be a Number'); } if (this.end === undefined) { this.end = Infinity; } else if ('number' !== typeof this.end) { throw TypeError('end must be a Number'); } if (this.start > this.end) { throw new Error('start must be <= end'); } this.pos = this.start; } if (this.fd !== null) { process.nextTick(function() { self._read(); }); return; } fs.open(this.path, this.flags, this.mode, function (err, fd) { if (err) { self.emit('error', err); self.readable = false; return; } self.fd = fd; self.emit('open', fd); self._read(); }) } function WriteStream (path, options) { if (!(this instanceof WriteStream)) return new WriteStream(path, options); Stream.call(this); this.path = path; this.fd = null; this.writable = true; this.flags = 'w'; this.encoding = 'binary'; this.mode = 438; /*=0666*/ this.bytesWritten = 0; options = options || {}; // Mixin options into this var keys = Object.keys(options); for (var index = 0, length = keys.length; index < length; index++) { var key = keys[index]; this[key] = options[key]; } if (this.start !== undefined) { if ('number' !== typeof this.start) { throw TypeError('start must be a Number'); } if (this.start < 0) { throw new Error('start must be >= zero'); } this.pos = this.start; } this.busy = false; this._queue = []; if (this.fd === null) { this._open = fs.open; this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); this.flush(); } } }
{ "pile_set_name": "Github" }
<?php /* For licensing terms, see /license.txt */ /** * @author Julio Montoya <[email protected]> */ $cidReset = true; require_once __DIR__.'/../inc/global.inc.php'; api_block_anonymous_users(); if ('true' !== api_get_setting('allow_social_tool')) { api_not_allowed(true); } if ('false' === api_get_setting('allow_students_to_create_groups_in_social') && !api_is_allowed_to_edit()) { api_not_allowed(true); } $table_message = Database::get_main_table(TABLE_MESSAGE); $usergroup = new UserGroup(); $form = new FormValidator('add_group'); $usergroup->setGroupType($usergroup::SOCIAL_CLASS); $usergroup->setForm($form, 'add', []); if ($form->validate()) { $values = $form->exportValues(); $values['group_type'] = UserGroup::SOCIAL_CLASS; $values['relation_type'] = GROUP_USER_PERMISSION_ADMIN; $groupId = $usergroup->save($values); if ($groupId) { Display::addFlash(Display::return_message(get_lang('Group added'))); api_location(api_get_path(WEB_CODE_PATH).'social/group_view.php?id='.$groupId); } api_location(api_get_self()); } $nameTools = get_lang('Add group'); $this_section = SECTION_SOCIAL; $interbreadcrumb[] = ['url' => 'home.php', 'name' => get_lang('Social')]; $interbreadcrumb[] = ['url' => 'groups.php', 'name' => get_lang('Groups')]; $interbreadcrumb[] = ['url' => '#', 'name' => $nameTools]; $social_avatar_block = SocialManager::show_social_avatar_block('group_add'); $social_menu_block = SocialManager::show_social_menu('group_add'); $social_right_content = $form->returnForm(); $tpl = new Template(null); SocialManager::setSocialUserBlock($tpl, api_get_user_id(), null, null); $tpl->setHelp('Groups'); $tpl->assign('social_menu_block', $social_menu_block); $tpl->assign('social_right_content', $social_right_content); $social_layout = $tpl->get_template('social/add_groups.tpl'); $content = $tpl->fetch($social_layout); $tpl->assign('content', $content); $tpl->display_one_col_template();
{ "pile_set_name": "Github" }
#source: start.s #source: bpo-9.s #as: -linker-allocated-gregs #ld: -m mmo #objdump: -st # 223 (max) linker-allocated GREGs, four relocs merged for each register # allocated. .*: file format mmo SYMBOL TABLE: 0+ g \.text Main 0+ g \.text _start Contents of section \.text: 0000 e3fd0001 230b2000 230b2040 230b2080 .* 0010 230b20c0 230b2100 230b2140 230b2180 .* 0020 230b21c0 230b2200 230b2240 230b2280 .* #... 0dd0 230bfcc0 230bfd00 230bfd40 230bfd80 .* 0de0 230bfdc0 230bfe00 230bfe40 230bfe80 .* 0df0 230bfec0 .* Contents of section \.MMIX\.reg_contents: 0100 00000000 00000000 00000000 00000100 .* 0110 00000000 00000200 00000000 00000300 .* #... 07d0 00000000 0000da00 00000000 0000db00 .* 07e0 00000000 0000dc00 00000000 0000dd00 .* 07f0 00000000 0000de00 .*
{ "pile_set_name": "Github" }
/* * Copyright (C) 2004 Manuel Novoa III <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* July 29, 2004 * * This is a hacked replacement for the 'addpattern' utility used to * create wrt54g .bin firmware files. It isn't pretty, but it does * the job for me. * * Extensions: * -v allows setting the version string on the command line. * -{0|1} sets the (currently ignored) hw_ver flag in the header * to 0 or 1 respectively. */ /* January 12, 2005 * * Modified by rodent at rodent dot za dot net * Support added for the new WRT54G v2.2 and WRT54GS v1.1 "flags" * Without the flags set to 0x7, the above units will refuse to flash. * * Extensions: * -{0|1|2} sets {0|1} sets hw_ver flag to 0/1. {2} sets hw_ver to 1 * and adds the new hardware "flags" for the v2.2/v1.1 units */ /* January 1, 2007 * * Modified by juan.i.gonzalez at subdown dot net * Support added for the AG241v2 and similar * * Extensions: * -r #.# adds revision hardware flags. AG241v2 and similar. * * AG241V2 firmware sets the hw_ver to 0x44. * * Example: -r 2.0 * * Convert 2.0 to 20 to be an integer, and add 0x30 to skip special ASCII * #define HW_Version ((HW_REV * 10) + 0x30) -> from cyutils.h */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <unistd.h> #include <sys/stat.h> /**********************************************************************/ #define CODE_ID "U2ND" /* from code_pattern.h */ #define CODE_PATTERN "W54S" /* from code_pattern.h */ #define PBOT_PATTERN "PBOT" #define CYBERTAN_VERSION "v3.37.2" /* from cyutils.h */ /* WRT54G v2.2 and WRT54GS v1.1 "flags" (from 3.37.32 firmware cyutils.h) */ #define SUPPORT_4712_CHIP 0x0001 #define SUPPORT_INTEL_FLASH 0x0002 #define SUPPORT_5325E_SWITCH 0x0004 /* (from 3.00.24 firmware cyutils.h) */ #define SUPPORT_4704_CHIP 0x0008 #define SUPPORT_5352E_CHIP 0x0010 /* (from WD My Net Wi-Fi Range Extender's cyutils.s) */ #define SUPPORT_4703_CHIP 0x0020 struct code_header { /* from cyutils.h */ char magic[8]; char fwdate[3]; char fwvern[3]; char id[4]; /* U2ND */ char hw_ver; /* 0: for 4702, 1: for 4712 -- new in 2.04.3 */ unsigned char sn; // Serial Number unsigned char flags[2]; /* SUPPORT_ flags new for 3.37.2 (WRT54G v2.2 and WRT54GS v1.1) */ unsigned char stable[2]; // The image is stable (for dual image) unsigned char try1[2]; // Try to boot image first time (for dual image) unsigned char try2[2]; // Try to boot image second time (for dual image) unsigned char try3[2]; // Try to boot image third time (for dual_image) unsigned char res3[2]; } ; struct board_info { char *id; char *pattern; char hw_ver; char sn; char flags[2]; }; struct board_info boards[] = { { .id = "WRT160NL", .pattern = "NL16", .hw_ver = 0x00, .sn = 0x0f, .flags = {0x3f, 0x00}, }, { .id = "E2100L", .pattern = "NL1X", .hw_ver = 0x00, .sn = 0x0f, .flags = {0x3f, 0x00}, }, { .id = "mynet-rext", .pattern = "WDHNSTFH", .hw_ver = 0x00, .sn = 0x00, .flags = {0x3f, 0x00}, }, { /* Terminating entry */ .id = NULL, } }; /**********************************************************************/ void usage(void) __attribute__ (( __noreturn__ )); void usage(void) { fprintf(stderr, "Usage: addpattern [-i trxfile] [-o binfile] [-B board_id] [-p pattern] [-s serial] [-g] [-b] [-v v#.#.#] [-r #.#] [-{0|1|2|4|5}] -h\n"); exit(EXIT_FAILURE); } struct board_info *find_board(char *id) { struct board_info *board; for (board = boards; board->id != NULL; board++) if (strcasecmp(id, board->id) == 0) return board; return NULL; } int main(int argc, char **argv) { char buf[1024]; /* keep this at 1k or adjust garbage calc below */ struct code_header *hdr; FILE *in = stdin; FILE *out = stdout; char *ifn = NULL; char *ofn = NULL; char *pattern = CODE_PATTERN; char *pbotpat = PBOT_PATTERN; char *version = CYBERTAN_VERSION; char *board_id = NULL; struct board_info *board = NULL; int gflag = 0; int pbotflag = 0; int c; int v0, v1, v2; size_t off, n; time_t t; struct tm *ptm; fprintf(stderr, "mjn3's addpattern replacement - v0.81\n"); hdr = (struct code_header *) buf; memset(hdr, 0, sizeof(struct code_header)); while ((c = getopt(argc, argv, "i:o:p:s:gbv:01245hr:B:")) != -1) { switch (c) { case 'i': ifn = optarg; break; case 'o': ofn = optarg; break; case 'p': pattern = optarg; break; case 's': hdr->sn = (unsigned char) atoi (optarg); break; case 'g': gflag = 1; break; case 'b': pbotflag = 1; break; case 'v': /* extension to allow setting version */ version = optarg; break; case '0': hdr->hw_ver = 0; break; case '1': hdr->hw_ver = 1; break; case '2': /* new 54G v2.2 and 54GS v1.1 flags */ hdr->hw_ver = 1; hdr->flags[0] |= SUPPORT_4712_CHIP; hdr->flags[0] |= SUPPORT_INTEL_FLASH; hdr->flags[0] |= SUPPORT_5325E_SWITCH; break; case '4': /* V4 firmware sets the flags to 0x1f */ hdr->hw_ver = 0; hdr->flags[0] = 0x1f; break; case '5': /* V5 is appended to trxV2 image */ hdr->stable[0] = 0x73; // force image to be stable hdr->stable[1] = 0x00; hdr->try1[0] = 0x74; // force try1 to be set hdr->try1[1] = 0x00; hdr->try2[0] = hdr->try2[1] = 0xFF; hdr->try3[0] = hdr->try3[1] = 0xFF; break; case 'r': hdr->hw_ver = (char)(atof(optarg)*10)+0x30; break; case 'B': board_id = optarg; break; case 'h': default: usage(); } } if (optind != argc || optind == 1) { fprintf(stderr, "illegal arg \"%s\"\n", argv[optind]); usage(); } if (board_id) { board = find_board(board_id); if (board == NULL) { fprintf(stderr, "unknown board \"%s\"\n", board_id); usage(); } pattern = board->pattern; hdr->hw_ver = board->hw_ver; hdr->sn = board->sn; hdr->flags[0] = board->flags[0]; hdr->flags[1] = board->flags[1]; } if (strlen(pattern) > 8) { fprintf(stderr, "illegal pattern \"%s\"\n", pattern); usage(); } if (ifn && !(in = fopen(ifn, "r"))) { fprintf(stderr, "can not open \"%s\" for reading\n", ifn); usage(); } if (ofn && !(out = fopen(ofn, "w"))) { fprintf(stderr, "can not open \"%s\" for writing\n", ofn); usage(); } if (time(&t) == (time_t)(-1)) { fprintf(stderr, "time call failed\n"); return EXIT_FAILURE; } ptm = localtime(&t); if (3 != sscanf(version, "v%d.%d.%d", &v0, &v1, &v2)) { fprintf(stderr, "bad version string \"%s\"\n", version); return EXIT_FAILURE; } memcpy(hdr->magic, pattern, strlen(pattern)); if (pbotflag) memcpy(&hdr->magic[4], pbotpat, 4); hdr->fwdate[0] = ptm->tm_year % 100; hdr->fwdate[1] = ptm->tm_mon + 1; hdr->fwdate[2] = ptm->tm_mday; hdr->fwvern[0] = v0; hdr->fwvern[1] = v1; hdr->fwvern[2] = v2; memcpy(hdr->id, CODE_ID, strlen(CODE_ID)); off = sizeof(struct code_header); fprintf(stderr, "writing firmware v%d.%d.%d on %d/%d/%d (y/m/d)\n", v0, v1, v2, hdr->fwdate[0], hdr->fwdate[1], hdr->fwdate[2]); while ((n = fread(buf + off, 1, sizeof(buf)-off, in) + off) > 0) { off = 0; if (n < sizeof(buf)) { if (ferror(in)) { FREAD_ERROR: fprintf(stderr, "fread error\n"); return EXIT_FAILURE; } if (gflag) { gflag = sizeof(buf) - n; memset(buf + n, 0xff, gflag); fprintf(stderr, "adding %d bytes of garbage\n", gflag); n = sizeof(buf); } } if (!fwrite(buf, n, 1, out)) { FWRITE_ERROR: fprintf(stderr, "fwrite error\n"); return EXIT_FAILURE; } } if (ferror(in)) { goto FREAD_ERROR; } if (fflush(out)) { goto FWRITE_ERROR; } fclose(in); fclose(out); return EXIT_SUCCESS; }
{ "pile_set_name": "Github" }
/* ChibiOS - Copyright (C) 2006..2018 Giovanni Di Sirio 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. */ #include "hal.h" #include "cry_test_root.h" /** * @file cry_test_sequence_009.c * @brief Test Sequence 009 code. * * @page cry_test_sequence_009 [9] HMAC * * File: @ref cry_test_sequence_009.c * * <h2>Description</h2> * HMAC testing. * * <h2>Test Cases</h2> * - @subpage cry_test_009_001 * - @subpage cry_test_009_002 * . */ /**************************************************************************** * Shared code. ****************************************************************************/ #include <string.h> #include "ref_hmac.h" #define plaintext msg_clear #define HMACOUT msg_encrypted #define shabuffer msg_decrypted #define MAX_SHA_BLOCK_SIZE TEST_MSG_DATA_BYTE_LEN #define MAX_SHA_BLOCK_SIZE_INWORD (MAX_SHA_BLOCK_SIZE/4) static const CRYConfig config_Polling= { TRANSFER_POLLING, 0 }; static const CRYConfig config_DMA= { TRANSFER_DMA, 0 }; static const int hmackeys_size[]= { 20, 4, 20 }; static const uint8_t hmackey_1[]= { 0x0B,0x0B,0x0B,0x0B,0x0B,0x0B,0x0B,0x0B,0x0B,0x0B, 0x0B,0x0B,0x0B,0x0B,0x0B,0x0B,0x0B,0x0B,0x0B,0x0B, }; // "Hi There", static const uint8_t hmacmsg1[8]= "Hi There"; static const size_t hmacmsg_size[]= { 8, }; static void cryHMAC256(CRYDriver *cryp) { cryerror_t ret; HMACSHA256Context hmacshactxp; uint8_t *keyp; hmacshactxp.shacontext.sha.sha_buffer = (uint8_t*)&shabuffer[0]; hmacshactxp.shacontext.sha.sha_buffer_size = MAX_SHA_BLOCK_SIZE; keyp =(uint8_t *)hmackey_1; ret = cryLoadTransientKey(&CRYD1, (cryalgorithm_t) cry_algo_hmac,hmackeys_size[0], keyp); test_assert(ret == CRY_NOERROR, "failed load transient key"); ret = cryHMACSHA256Init(cryp,&hmacshactxp); test_assert(ret == CRY_NOERROR, "failed init HMACSHA256"); ret = cryHMACSHA256Update(cryp,&hmacshactxp,hmacmsg_size[0],(const uint8_t *)&hmacmsg1); test_assert(ret == CRY_NOERROR, "failed update HMACSHA256"); ret = cryHMACSHA256Final(cryp,&hmacshactxp,(uint8_t *)HMACOUT); test_assert(ret == CRY_NOERROR, "failed final HMACSHA256"); SHOW_DATA(HMACOUT,8); } static void cryHMAC512(CRYDriver *cryp) { cryerror_t ret; HMACSHA512Context hmacshactxp; uint8_t *keyp; hmacshactxp.shacontext.sha.sha_buffer = (uint8_t*)&shabuffer[0]; hmacshactxp.shacontext.sha.sha_buffer_size = MAX_SHA_BLOCK_SIZE; keyp =(uint8_t *)hmackey_1; ret = cryLoadTransientKey(&CRYD1, (cryalgorithm_t) cry_algo_hmac,hmackeys_size[0], keyp); test_assert(ret == CRY_NOERROR, "failed load transient key"); ret = cryHMACSHA512Init(cryp,&hmacshactxp); test_assert(ret == CRY_NOERROR, "failed init HMACSHA512"); ret = cryHMACSHA512Update(cryp,&hmacshactxp,hmacmsg_size[0],(const uint8_t *)&hmacmsg1); test_assert(ret == CRY_NOERROR, "failed update HMACSHA512"); ret = cryHMACSHA512Final(cryp,&hmacshactxp,(uint8_t *)HMACOUT); test_assert(ret == CRY_NOERROR, "failed final HMACSHA512"); SHOW_DATA(HMACOUT,16); } /**************************************************************************** * Test cases. ****************************************************************************/ /** * @page cry_test_009_001 [9.1] HMAC Polling * * <h2>Description</h2> * testing HMAC in polled mode. * * <h2>Test Steps</h2> * - [9.1.1] hmac 256. * - [9.1.2] hmac 512. * . */ static void cry_test_009_001_setup(void) { memset(HMACOUT, 0xff, TEST_MSG_DATA_BYTE_LEN); cryStart(&CRYD1, &config_Polling); } static void cry_test_009_001_teardown(void) { cryStop(&CRYD1); } static void cry_test_009_001_execute(void) { /* [9.1.1] hmac 256.*/ test_set_step(1); { cryHMAC256(&CRYD1); for (int i = 0; i < 8; i++) { test_assert(HMACOUT[i] == ((uint32_t*) refHMAC_HMAC256_1)[i], "hmac mismatch"); } } /* [9.1.2] hmac 512.*/ test_set_step(2); { cryHMAC512(&CRYD1); for (int i = 0; i < 16; i++) { test_assert(HMACOUT[i] == ((uint32_t*) refHMAC_HMAC512_1)[i], "hmac mismatch"); } } } static const testcase_t cry_test_009_001 = { "HMAC Polling", cry_test_009_001_setup, cry_test_009_001_teardown, cry_test_009_001_execute }; /** * @page cry_test_009_002 [9.2] HMAC DMA * * <h2>Description</h2> * testing HMAC in DMA mode. * * <h2>Test Steps</h2> * - [9.2.1] hmac 256. * - [9.2.2] hmac 512. * . */ static void cry_test_009_002_setup(void) { memset(HMACOUT, 0xff, TEST_MSG_DATA_BYTE_LEN); cryStart(&CRYD1, &config_DMA); } static void cry_test_009_002_teardown(void) { cryStop(&CRYD1); } static void cry_test_009_002_execute(void) { /* [9.2.1] hmac 256.*/ test_set_step(1); { cryHMAC256(&CRYD1); for (int i = 0; i < 8; i++) { test_assert(HMACOUT[i] == ((uint32_t*) refHMAC_HMAC256_1)[i], "hmac mismatch"); } } /* [9.2.2] hmac 512.*/ test_set_step(2); { cryHMAC512(&CRYD1); for (int i = 0; i < 16; i++) { test_assert(HMACOUT[i] == ((uint32_t*) refHMAC_HMAC512_1)[i], "hmac mismatch"); } } } static const testcase_t cry_test_009_002 = { "HMAC DMA", cry_test_009_002_setup, cry_test_009_002_teardown, cry_test_009_002_execute }; /**************************************************************************** * Exported data. ****************************************************************************/ /** * @brief Array of test cases. */ const testcase_t * const cry_test_sequence_009_array[] = { &cry_test_009_001, &cry_test_009_002, NULL }; /** * @brief HMAC. */ const testsequence_t cry_test_sequence_009 = { "HMAC", cry_test_sequence_009_array };
{ "pile_set_name": "Github" }
Twisted==14.0.0 lxml==3.3.5 psutil==2.1.1 pyasn1==0.1.7 tlslite==0.4.6
{ "pile_set_name": "Github" }